babylon.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241
  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. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * 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)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * 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)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * 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)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * 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)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * 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)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * 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)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * 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)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * 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)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * 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)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * 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)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * 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)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * 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)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. /**
  1269. * Gather the list of keyboard event types as constants.
  1270. */
  1271. var KeyboardEventTypes = /** @class */ (function () {
  1272. function KeyboardEventTypes() {
  1273. }
  1274. /**
  1275. * The keydown event is fired when a key becomes active (pressed).
  1276. */
  1277. KeyboardEventTypes.KEYDOWN = 0x01;
  1278. /**
  1279. * The keyup event is fired when a key has been released.
  1280. */
  1281. KeyboardEventTypes.KEYUP = 0x02;
  1282. return KeyboardEventTypes;
  1283. }());
  1284. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1285. /**
  1286. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1287. */
  1288. var KeyboardInfo = /** @class */ (function () {
  1289. /**
  1290. * Instantiates a new keyboard info.
  1291. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfo(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. this.type = type;
  1305. this.event = event;
  1306. }
  1307. return KeyboardInfo;
  1308. }());
  1309. BABYLON.KeyboardInfo = KeyboardInfo;
  1310. /**
  1311. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1312. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1313. */
  1314. var KeyboardInfoPre = /** @class */ (function (_super) {
  1315. __extends(KeyboardInfoPre, _super);
  1316. /**
  1317. * Instantiates a new keyboard pre info.
  1318. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfoPre(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. var _this = _super.call(this, type, event) || this;
  1332. _this.type = type;
  1333. _this.event = event;
  1334. _this.skipOnPointerObservable = false;
  1335. return _this;
  1336. }
  1337. return KeyboardInfoPre;
  1338. }(KeyboardInfo));
  1339. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1340. })(BABYLON || (BABYLON = {}));
  1341. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. /**
  1345. * Gather the list of pointer event types as constants.
  1346. */
  1347. var PointerEventTypes = /** @class */ (function () {
  1348. function PointerEventTypes() {
  1349. }
  1350. /**
  1351. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1352. */
  1353. PointerEventTypes.POINTERDOWN = 0x01;
  1354. /**
  1355. * The pointerup event is fired when a pointer is no longer active.
  1356. */
  1357. PointerEventTypes.POINTERUP = 0x02;
  1358. /**
  1359. * The pointermove event is fired when a pointer changes coordinates.
  1360. */
  1361. PointerEventTypes.POINTERMOVE = 0x04;
  1362. /**
  1363. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1364. */
  1365. PointerEventTypes.POINTERWHEEL = 0x08;
  1366. /**
  1367. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1368. */
  1369. PointerEventTypes.POINTERPICK = 0x10;
  1370. /**
  1371. * The pointertap event is fired when a the object has been touched and released without drag.
  1372. */
  1373. PointerEventTypes.POINTERTAP = 0x20;
  1374. /**
  1375. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1376. */
  1377. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1378. return PointerEventTypes;
  1379. }());
  1380. BABYLON.PointerEventTypes = PointerEventTypes;
  1381. /**
  1382. * Base class of pointer info types.
  1383. */
  1384. var PointerInfoBase = /** @class */ (function () {
  1385. /**
  1386. * Instantiates the base class of pointers info.
  1387. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1388. * @param event Defines the related dom event
  1389. */
  1390. function PointerInfoBase(
  1391. /**
  1392. * Defines the type of event (BABYLON.PointerEventTypes)
  1393. */
  1394. type,
  1395. /**
  1396. * Defines the related dom event
  1397. */
  1398. event) {
  1399. this.type = type;
  1400. this.event = event;
  1401. }
  1402. return PointerInfoBase;
  1403. }());
  1404. BABYLON.PointerInfoBase = PointerInfoBase;
  1405. /**
  1406. * This class is used to store pointer related info for the onPrePointerObservable event.
  1407. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1408. */
  1409. var PointerInfoPre = /** @class */ (function (_super) {
  1410. __extends(PointerInfoPre, _super);
  1411. /**
  1412. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1413. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1414. * @param event Defines the related dom event
  1415. * @param localX Defines the local x coordinates of the pointer when the event occured
  1416. * @param localY Defines the local y coordinates of the pointer when the event occured
  1417. */
  1418. function PointerInfoPre(type, event, localX, localY) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. /**
  1421. * Ray from a pointer if availible (eg. 6dof controller)
  1422. */
  1423. _this.ray = null;
  1424. _this.skipOnPointerObservable = false;
  1425. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1426. return _this;
  1427. }
  1428. return PointerInfoPre;
  1429. }(PointerInfoBase));
  1430. BABYLON.PointerInfoPre = PointerInfoPre;
  1431. /**
  1432. * This type contains all the data related to a pointer event in Babylon.js.
  1433. * 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.
  1434. */
  1435. var PointerInfo = /** @class */ (function (_super) {
  1436. __extends(PointerInfo, _super);
  1437. /**
  1438. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1439. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1440. * @param event Defines the related dom event
  1441. * @param pickInfo Defines the picking info associated to the info (if any)\
  1442. */
  1443. function PointerInfo(type, event,
  1444. /**
  1445. * Defines the picking info associated to the info (if any)\
  1446. */
  1447. pickInfo) {
  1448. var _this = _super.call(this, type, event) || this;
  1449. _this.pickInfo = pickInfo;
  1450. return _this;
  1451. }
  1452. return PointerInfo;
  1453. }(PointerInfoBase));
  1454. BABYLON.PointerInfo = PointerInfo;
  1455. })(BABYLON || (BABYLON = {}));
  1456. //# sourceMappingURL=babylon.pointerEvents.js.map
  1457. var BABYLON;
  1458. (function (BABYLON) {
  1459. /**
  1460. * Constant used to convert a value to gamma space
  1461. * @ignorenaming
  1462. */
  1463. BABYLON.ToGammaSpace = 1 / 2.2;
  1464. /**
  1465. * Constant used to convert a value to linear space
  1466. * @ignorenaming
  1467. */
  1468. BABYLON.ToLinearSpace = 2.2;
  1469. /**
  1470. * Constant used to define the minimal number value in Babylon.js
  1471. * @ignorenaming
  1472. */
  1473. BABYLON.Epsilon = 0.001;
  1474. /**
  1475. * Class used to hold a RBG color
  1476. */
  1477. var Color3 = /** @class */ (function () {
  1478. /**
  1479. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1480. * @param r defines the red component (between 0 and 1, default is 0)
  1481. * @param g defines the green component (between 0 and 1, default is 0)
  1482. * @param b defines the blue component (between 0 and 1, default is 0)
  1483. */
  1484. function Color3(
  1485. /**
  1486. * Defines the red component (between 0 and 1, default is 0)
  1487. */
  1488. r,
  1489. /**
  1490. * Defines the green component (between 0 and 1, default is 0)
  1491. */
  1492. g,
  1493. /**
  1494. * Defines the blue component (between 0 and 1, default is 0)
  1495. */
  1496. b) {
  1497. if (r === void 0) { r = 0; }
  1498. if (g === void 0) { g = 0; }
  1499. if (b === void 0) { b = 0; }
  1500. this.r = r;
  1501. this.g = g;
  1502. this.b = b;
  1503. }
  1504. /**
  1505. * Creates a string with the Color3 current values
  1506. * @returns the string representation of the Color3 object
  1507. */
  1508. Color3.prototype.toString = function () {
  1509. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1510. };
  1511. /**
  1512. * Returns the string "Color3"
  1513. * @returns "Color3"
  1514. */
  1515. Color3.prototype.getClassName = function () {
  1516. return "Color3";
  1517. };
  1518. /**
  1519. * Compute the Color3 hash code
  1520. * @returns an unique number that can be used to hash Color3 objects
  1521. */
  1522. Color3.prototype.getHashCode = function () {
  1523. var hash = this.r || 0;
  1524. hash = (hash * 397) ^ (this.g || 0);
  1525. hash = (hash * 397) ^ (this.b || 0);
  1526. return hash;
  1527. };
  1528. // Operators
  1529. /**
  1530. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1531. * @param array defines the array where to store the r,g,b components
  1532. * @param index defines an optional index in the target array to define where to start storing values
  1533. * @returns the current Color3 object
  1534. */
  1535. Color3.prototype.toArray = function (array, index) {
  1536. if (index === undefined) {
  1537. index = 0;
  1538. }
  1539. array[index] = this.r;
  1540. array[index + 1] = this.g;
  1541. array[index + 2] = this.b;
  1542. return this;
  1543. };
  1544. /**
  1545. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1546. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1547. * @returns a new {BABYLON.Color4} object
  1548. */
  1549. Color3.prototype.toColor4 = function (alpha) {
  1550. if (alpha === void 0) { alpha = 1; }
  1551. return new Color4(this.r, this.g, this.b, alpha);
  1552. };
  1553. /**
  1554. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1555. * @returns the new array
  1556. */
  1557. Color3.prototype.asArray = function () {
  1558. var result = new Array();
  1559. this.toArray(result, 0);
  1560. return result;
  1561. };
  1562. /**
  1563. * Returns the luminance value
  1564. * @returns a float value
  1565. */
  1566. Color3.prototype.toLuminance = function () {
  1567. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1568. };
  1569. /**
  1570. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3 object
  1573. */
  1574. Color3.prototype.multiply = function (otherColor) {
  1575. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1576. };
  1577. /**
  1578. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines the Color3 object where to store the result
  1581. * @returns the current Color3
  1582. */
  1583. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1584. result.r = this.r * otherColor.r;
  1585. result.g = this.g * otherColor.g;
  1586. result.b = this.b * otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Determines equality between Color3 objects
  1591. * @param otherColor defines the second operand
  1592. * @returns true if the rgb values are equal to the given ones
  1593. */
  1594. Color3.prototype.equals = function (otherColor) {
  1595. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1596. };
  1597. /**
  1598. * Determines equality between the current Color3 object and a set of r,b,g values
  1599. * @param r defines the red component to check
  1600. * @param g defines the green component to check
  1601. * @param b defines the blue component to check
  1602. * @returns true if the rgb values are equal to the given ones
  1603. */
  1604. Color3.prototype.equalsFloats = function (r, g, b) {
  1605. return this.r === r && this.g === g && this.b === b;
  1606. };
  1607. /**
  1608. * Multiplies in place each rgb value by scale
  1609. * @param scale defines the scaling factor
  1610. * @returns the updated Color3
  1611. */
  1612. Color3.prototype.scale = function (scale) {
  1613. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1614. };
  1615. /**
  1616. * Multiplies the rgb values by scale and stores the result into "result"
  1617. * @param scale defines the scaling factor
  1618. * @param result defines the Color3 object where to store the result
  1619. * @returns the unmodified current Color3
  1620. */
  1621. Color3.prototype.scaleToRef = function (scale, result) {
  1622. result.r = this.r * scale;
  1623. result.g = this.g * scale;
  1624. result.b = this.b * scale;
  1625. return this;
  1626. };
  1627. /**
  1628. * Scale the current Color3 values by a factor and add the result to a given Color3
  1629. * @param scale defines the scale factor
  1630. * @param result defines color to store the result into
  1631. * @returns the unmodified current Color3
  1632. */
  1633. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1634. result.r += this.r * scale;
  1635. result.g += this.g * scale;
  1636. result.b += this.b * scale;
  1637. return this;
  1638. };
  1639. /**
  1640. * Clamps the rgb values by the min and max values and stores the result into "result"
  1641. * @param min defines minimum clamping value (default is 0)
  1642. * @param max defines maximum clamping value (default is 1)
  1643. * @param result defines color to store the result into
  1644. * @returns the original Color3
  1645. */
  1646. Color3.prototype.clampToRef = function (min, max, result) {
  1647. if (min === void 0) { min = 0; }
  1648. if (max === void 0) { max = 1; }
  1649. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1650. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1651. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1652. return this;
  1653. };
  1654. /**
  1655. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1656. * @param otherColor defines the second operand
  1657. * @returns the new Color3
  1658. */
  1659. Color3.prototype.add = function (otherColor) {
  1660. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1661. };
  1662. /**
  1663. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1664. * @param otherColor defines the second operand
  1665. * @param result defines Color3 object to store the result into
  1666. * @returns the unmodified current Color3
  1667. */
  1668. Color3.prototype.addToRef = function (otherColor, result) {
  1669. result.r = this.r + otherColor.r;
  1670. result.g = this.g + otherColor.g;
  1671. result.b = this.b + otherColor.b;
  1672. return this;
  1673. };
  1674. /**
  1675. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1676. * @param otherColor defines the second operand
  1677. * @returns the new Color3
  1678. */
  1679. Color3.prototype.subtract = function (otherColor) {
  1680. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1681. };
  1682. /**
  1683. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1684. * @param otherColor defines the second operand
  1685. * @param result defines Color3 object to store the result into
  1686. * @returns the unmodified current Color3
  1687. */
  1688. Color3.prototype.subtractToRef = function (otherColor, result) {
  1689. result.r = this.r - otherColor.r;
  1690. result.g = this.g - otherColor.g;
  1691. result.b = this.b - otherColor.b;
  1692. return this;
  1693. };
  1694. /**
  1695. * Copy the current object
  1696. * @returns a new Color3 copied the current one
  1697. */
  1698. Color3.prototype.clone = function () {
  1699. return new Color3(this.r, this.g, this.b);
  1700. };
  1701. /**
  1702. * Copies the rgb values from the source in the current Color3
  1703. * @param source defines the source Color3 object
  1704. * @returns the updated Color3 object
  1705. */
  1706. Color3.prototype.copyFrom = function (source) {
  1707. this.r = source.r;
  1708. this.g = source.g;
  1709. this.b = source.b;
  1710. return this;
  1711. };
  1712. /**
  1713. * Updates the Color3 rgb values from the given floats
  1714. * @param r defines the red component to read from
  1715. * @param g defines the green component to read from
  1716. * @param b defines the blue component to read from
  1717. * @returns the current Color3 object
  1718. */
  1719. Color3.prototype.copyFromFloats = function (r, g, b) {
  1720. this.r = r;
  1721. this.g = g;
  1722. this.b = b;
  1723. return this;
  1724. };
  1725. /**
  1726. * Updates the Color3 rgb values from the given floats
  1727. * @param r defines the red component to read from
  1728. * @param g defines the green component to read from
  1729. * @param b defines the blue component to read from
  1730. * @returns the current Color3 object
  1731. */
  1732. Color3.prototype.set = function (r, g, b) {
  1733. return this.copyFromFloats(r, g, b);
  1734. };
  1735. /**
  1736. * Compute the Color3 hexadecimal code as a string
  1737. * @returns a string containing the hexadecimal representation of the Color3 object
  1738. */
  1739. Color3.prototype.toHexString = function () {
  1740. var intR = (this.r * 255) | 0;
  1741. var intG = (this.g * 255) | 0;
  1742. var intB = (this.b * 255) | 0;
  1743. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1744. };
  1745. /**
  1746. * Computes a new Color3 converted from the current one to linear space
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.prototype.toLinearSpace = function () {
  1750. var convertedColor = new Color3();
  1751. this.toLinearSpaceToRef(convertedColor);
  1752. return convertedColor;
  1753. };
  1754. /**
  1755. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1756. * @param convertedColor defines the Color3 object where to store the linear space version
  1757. * @returns the unmodified Color3
  1758. */
  1759. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1760. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1761. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1762. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1763. return this;
  1764. };
  1765. /**
  1766. * Computes a new Color3 converted from the current one to gamma space
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.prototype.toGammaSpace = function () {
  1770. var convertedColor = new Color3();
  1771. this.toGammaSpaceToRef(convertedColor);
  1772. return convertedColor;
  1773. };
  1774. /**
  1775. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1776. * @param convertedColor defines the Color3 object where to store the gamma space version
  1777. * @returns the unmodified Color3
  1778. */
  1779. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1780. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1781. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1782. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1783. return this;
  1784. };
  1785. // Statics
  1786. /**
  1787. * Creates a new Color3 from the string containing valid hexadecimal values
  1788. * @param hex defines a string containing valid hexadecimal values
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.FromHexString = function (hex) {
  1792. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1793. return new Color3(0, 0, 0);
  1794. }
  1795. var r = parseInt(hex.substring(1, 3), 16);
  1796. var g = parseInt(hex.substring(3, 5), 16);
  1797. var b = parseInt(hex.substring(5, 7), 16);
  1798. return Color3.FromInts(r, g, b);
  1799. };
  1800. /**
  1801. * Creates a new Vector3 from the starting index of the given array
  1802. * @param array defines the source array
  1803. * @param offset defines an offset in the source array
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.FromArray = function (array, offset) {
  1807. if (offset === void 0) { offset = 0; }
  1808. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1809. };
  1810. /**
  1811. * Creates a new Color3 from integer values (< 256)
  1812. * @param r defines the red component to read from (value between 0 and 255)
  1813. * @param g defines the green component to read from (value between 0 and 255)
  1814. * @param b defines the blue component to read from (value between 0 and 255)
  1815. * @returns a new Color3 object
  1816. */
  1817. Color3.FromInts = function (r, g, b) {
  1818. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1819. };
  1820. /**
  1821. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1822. * @param start defines the start Color3 value
  1823. * @param end defines the end Color3 value
  1824. * @param amount defines the gradient value between start and end
  1825. * @returns a new Color3 object
  1826. */
  1827. Color3.Lerp = function (start, end, amount) {
  1828. var result = new Color3(0.0, 0.0, 0.0);
  1829. Color3.LerpToRef(start, end, amount, result);
  1830. return result;
  1831. };
  1832. /**
  1833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1834. * @param left defines the start value
  1835. * @param right defines the end value
  1836. * @param amount defines the gradient factor
  1837. * @param result defines the Color3 object where to store the result
  1838. */
  1839. Color3.LerpToRef = function (left, right, amount, result) {
  1840. result.r = left.r + ((right.r - left.r) * amount);
  1841. result.g = left.g + ((right.g - left.g) * amount);
  1842. result.b = left.b + ((right.b - left.b) * amount);
  1843. };
  1844. /**
  1845. * Returns a Color3 value containing a red color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Red = function () { return new Color3(1, 0, 0); };
  1849. /**
  1850. * Returns a Color3 value containing a green color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Green = function () { return new Color3(0, 1, 0); };
  1854. /**
  1855. * Returns a Color3 value containing a blue color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1859. /**
  1860. * Returns a Color3 value containing a black color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Black = function () { return new Color3(0, 0, 0); };
  1864. /**
  1865. * Returns a Color3 value containing a white color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.White = function () { return new Color3(1, 1, 1); };
  1869. /**
  1870. * Returns a Color3 value containing a purple color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1874. /**
  1875. * Returns a Color3 value containing a magenta color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1879. /**
  1880. * Returns a Color3 value containing a yellow color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1884. /**
  1885. * Returns a Color3 value containing a gray color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1889. /**
  1890. * Returns a Color3 value containing a teal color
  1891. * @returns a new Color3 object
  1892. */
  1893. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1894. /**
  1895. * Returns a Color3 value containing a random color
  1896. * @returns a new Color3 object
  1897. */
  1898. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1899. return Color3;
  1900. }());
  1901. BABYLON.Color3 = Color3;
  1902. /**
  1903. * Class used to hold a RBGA color
  1904. */
  1905. var Color4 = /** @class */ (function () {
  1906. /**
  1907. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1908. * @param r defines the red component (between 0 and 1, default is 0)
  1909. * @param g defines the green component (between 0 and 1, default is 0)
  1910. * @param b defines the blue component (between 0 and 1, default is 0)
  1911. * @param a defines the alpha component (between 0 and 1, default is 1)
  1912. */
  1913. function Color4(
  1914. /**
  1915. * Defines the red component (between 0 and 1, default is 0)
  1916. */
  1917. r,
  1918. /**
  1919. * Defines the green component (between 0 and 1, default is 0)
  1920. */
  1921. g,
  1922. /**
  1923. * Defines the blue component (between 0 and 1, default is 0)
  1924. */
  1925. b,
  1926. /**
  1927. * Defines the alpha component (between 0 and 1, default is 1)
  1928. */
  1929. a) {
  1930. if (r === void 0) { r = 0; }
  1931. if (g === void 0) { g = 0; }
  1932. if (b === void 0) { b = 0; }
  1933. if (a === void 0) { a = 1; }
  1934. this.r = r;
  1935. this.g = g;
  1936. this.b = b;
  1937. this.a = a;
  1938. }
  1939. // Operators
  1940. /**
  1941. * Adds in place the given Color4 values to the current Color4 object
  1942. * @param right defines the second operand
  1943. * @returns the current updated Color4 object
  1944. */
  1945. Color4.prototype.addInPlace = function (right) {
  1946. this.r += right.r;
  1947. this.g += right.g;
  1948. this.b += right.b;
  1949. this.a += right.a;
  1950. return this;
  1951. };
  1952. /**
  1953. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1954. * @returns the new array
  1955. */
  1956. Color4.prototype.asArray = function () {
  1957. var result = new Array();
  1958. this.toArray(result, 0);
  1959. return result;
  1960. };
  1961. /**
  1962. * Stores from the starting index in the given array the Color4 successive values
  1963. * @param array defines the array where to store the r,g,b components
  1964. * @param index defines an optional index in the target array to define where to start storing values
  1965. * @returns the current Color4 object
  1966. */
  1967. Color4.prototype.toArray = function (array, index) {
  1968. if (index === undefined) {
  1969. index = 0;
  1970. }
  1971. array[index] = this.r;
  1972. array[index + 1] = this.g;
  1973. array[index + 2] = this.b;
  1974. array[index + 3] = this.a;
  1975. return this;
  1976. };
  1977. /**
  1978. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1979. * @param right defines the second operand
  1980. * @returns a new Color4 object
  1981. */
  1982. Color4.prototype.add = function (right) {
  1983. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1984. };
  1985. /**
  1986. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1987. * @param right defines the second operand
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.subtract = function (right) {
  1991. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1992. };
  1993. /**
  1994. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1995. * @param right defines the second operand
  1996. * @param result defines the Color4 object where to store the result
  1997. * @returns the current Color4 object
  1998. */
  1999. Color4.prototype.subtractToRef = function (right, result) {
  2000. result.r = this.r - right.r;
  2001. result.g = this.g - right.g;
  2002. result.b = this.b - right.b;
  2003. result.a = this.a - right.a;
  2004. return this;
  2005. };
  2006. /**
  2007. * Creates a new Color4 with the current Color4 values multiplied by scale
  2008. * @param scale defines the scaling factor to apply
  2009. * @returns a new Color4 object
  2010. */
  2011. Color4.prototype.scale = function (scale) {
  2012. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2013. };
  2014. /**
  2015. * Multiplies the current Color4 values by scale and stores the result in "result"
  2016. * @param scale defines the scaling factor to apply
  2017. * @param result defines the Color4 object where to store the result
  2018. * @returns the current unmodified Color4
  2019. */
  2020. Color4.prototype.scaleToRef = function (scale, result) {
  2021. result.r = this.r * scale;
  2022. result.g = this.g * scale;
  2023. result.b = this.b * scale;
  2024. result.a = this.a * scale;
  2025. return this;
  2026. };
  2027. /**
  2028. * Scale the current Color4 values by a factor and add the result to a given Color4
  2029. * @param scale defines the scale factor
  2030. * @param result defines the Color4 object where to store the result
  2031. * @returns the unmodified current Color4
  2032. */
  2033. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2034. result.r += this.r * scale;
  2035. result.g += this.g * scale;
  2036. result.b += this.b * scale;
  2037. result.a += this.a * scale;
  2038. return this;
  2039. };
  2040. /**
  2041. * Clamps the rgb values by the min and max values and stores the result into "result"
  2042. * @param min defines minimum clamping value (default is 0)
  2043. * @param max defines maximum clamping value (default is 1)
  2044. * @param result defines color to store the result into.
  2045. * @returns the cuurent Color4
  2046. */
  2047. Color4.prototype.clampToRef = function (min, max, result) {
  2048. if (min === void 0) { min = 0; }
  2049. if (max === void 0) { max = 1; }
  2050. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2051. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2052. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2053. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2054. return this;
  2055. };
  2056. /**
  2057. * Multipy an Color4 value by another and return a new Color4 object
  2058. * @param color defines the Color4 value to multiply by
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.prototype.multiply = function (color) {
  2062. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2063. };
  2064. /**
  2065. * Multipy a Color4 value by another and push the result in a reference value
  2066. * @param color defines the Color4 value to multiply by
  2067. * @param result defines the Color4 to fill the result in
  2068. * @returns the result Color4
  2069. */
  2070. Color4.prototype.multiplyToRef = function (color, result) {
  2071. result.r = this.r * color.r;
  2072. result.g = this.g * color.g;
  2073. result.b = this.b * color.b;
  2074. result.a = this.a * color.a;
  2075. return result;
  2076. };
  2077. /**
  2078. * Creates a string with the Color4 current values
  2079. * @returns the string representation of the Color4 object
  2080. */
  2081. Color4.prototype.toString = function () {
  2082. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2083. };
  2084. /**
  2085. * Returns the string "Color4"
  2086. * @returns "Color4"
  2087. */
  2088. Color4.prototype.getClassName = function () {
  2089. return "Color4";
  2090. };
  2091. /**
  2092. * Compute the Color4 hash code
  2093. * @returns an unique number that can be used to hash Color4 objects
  2094. */
  2095. Color4.prototype.getHashCode = function () {
  2096. var hash = this.r || 0;
  2097. hash = (hash * 397) ^ (this.g || 0);
  2098. hash = (hash * 397) ^ (this.b || 0);
  2099. hash = (hash * 397) ^ (this.a || 0);
  2100. return hash;
  2101. };
  2102. /**
  2103. * Creates a new Color4 copied from the current one
  2104. * @returns a new Color4 object
  2105. */
  2106. Color4.prototype.clone = function () {
  2107. return new Color4(this.r, this.g, this.b, this.a);
  2108. };
  2109. /**
  2110. * Copies the given Color4 values into the current one
  2111. * @param source defines the source Color4 object
  2112. * @returns the current updated Color4 object
  2113. */
  2114. Color4.prototype.copyFrom = function (source) {
  2115. this.r = source.r;
  2116. this.g = source.g;
  2117. this.b = source.b;
  2118. this.a = source.a;
  2119. return this;
  2120. };
  2121. /**
  2122. * Copies the given float values into the current one
  2123. * @param r defines the red component to read from
  2124. * @param g defines the green component to read from
  2125. * @param b defines the blue component to read from
  2126. * @param a defines the alpha component to read from
  2127. * @returns the current updated Color4 object
  2128. */
  2129. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2130. this.r = r;
  2131. this.g = g;
  2132. this.b = b;
  2133. this.a = a;
  2134. return this;
  2135. };
  2136. /**
  2137. * Copies the given float values into the current one
  2138. * @param r defines the red component to read from
  2139. * @param g defines the green component to read from
  2140. * @param b defines the blue component to read from
  2141. * @param a defines the alpha component to read from
  2142. * @returns the current updated Color4 object
  2143. */
  2144. Color4.prototype.set = function (r, g, b, a) {
  2145. return this.copyFromFloats(r, g, b, a);
  2146. };
  2147. /**
  2148. * Compute the Color4 hexadecimal code as a string
  2149. * @returns a string containing the hexadecimal representation of the Color4 object
  2150. */
  2151. Color4.prototype.toHexString = function () {
  2152. var intR = (this.r * 255) | 0;
  2153. var intG = (this.g * 255) | 0;
  2154. var intB = (this.b * 255) | 0;
  2155. var intA = (this.a * 255) | 0;
  2156. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2157. };
  2158. /**
  2159. * Computes a new Color4 converted from the current one to linear space
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.prototype.toLinearSpace = function () {
  2163. var convertedColor = new Color4();
  2164. this.toLinearSpaceToRef(convertedColor);
  2165. return convertedColor;
  2166. };
  2167. /**
  2168. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2169. * @param convertedColor defines the Color4 object where to store the linear space version
  2170. * @returns the unmodified Color4
  2171. */
  2172. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2173. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2174. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2175. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2176. convertedColor.a = this.a;
  2177. return this;
  2178. };
  2179. /**
  2180. * Computes a new Color4 converted from the current one to gamma space
  2181. * @returns a new Color4 object
  2182. */
  2183. Color4.prototype.toGammaSpace = function () {
  2184. var convertedColor = new Color4();
  2185. this.toGammaSpaceToRef(convertedColor);
  2186. return convertedColor;
  2187. };
  2188. /**
  2189. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2190. * @param convertedColor defines the Color4 object where to store the gamma space version
  2191. * @returns the unmodified Color4
  2192. */
  2193. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2194. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2195. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2196. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2197. convertedColor.a = this.a;
  2198. return this;
  2199. };
  2200. // Statics
  2201. /**
  2202. * Creates a new Color4 from the string containing valid hexadecimal values
  2203. * @param hex defines a string containing valid hexadecimal values
  2204. * @returns a new Color4 object
  2205. */
  2206. Color4.FromHexString = function (hex) {
  2207. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2208. return new Color4(0.0, 0.0, 0.0, 0.0);
  2209. }
  2210. var r = parseInt(hex.substring(1, 3), 16);
  2211. var g = parseInt(hex.substring(3, 5), 16);
  2212. var b = parseInt(hex.substring(5, 7), 16);
  2213. var a = parseInt(hex.substring(7, 9), 16);
  2214. return Color4.FromInts(r, g, b, a);
  2215. };
  2216. /**
  2217. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2218. * @param left defines the start value
  2219. * @param right defines the end value
  2220. * @param amount defines the gradient factor
  2221. * @returns a new Color4 object
  2222. */
  2223. Color4.Lerp = function (left, right, amount) {
  2224. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2225. Color4.LerpToRef(left, right, amount, result);
  2226. return result;
  2227. };
  2228. /**
  2229. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2230. * @param left defines the start value
  2231. * @param right defines the end value
  2232. * @param amount defines the gradient factor
  2233. * @param result defines the Color4 object where to store data
  2234. */
  2235. Color4.LerpToRef = function (left, right, amount, result) {
  2236. result.r = left.r + (right.r - left.r) * amount;
  2237. result.g = left.g + (right.g - left.g) * amount;
  2238. result.b = left.b + (right.b - left.b) * amount;
  2239. result.a = left.a + (right.a - left.a) * amount;
  2240. };
  2241. /**
  2242. * Creates a new Color4 from a Color3 and an alpha value
  2243. * @param color3 defines the source Color3 to read from
  2244. * @param alpha defines the alpha component (1.0 by default)
  2245. * @returns a new Color4 object
  2246. */
  2247. Color4.FromColor3 = function (color3, alpha) {
  2248. if (alpha === void 0) { alpha = 1.0; }
  2249. return new Color4(color3.r, color3.g, color3.b, alpha);
  2250. };
  2251. /**
  2252. * Creates a new Color4 from the starting index element of the given array
  2253. * @param array defines the source array to read from
  2254. * @param offset defines the offset in the source array
  2255. * @returns a new Color4 object
  2256. */
  2257. Color4.FromArray = function (array, offset) {
  2258. if (offset === void 0) { offset = 0; }
  2259. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2260. };
  2261. /**
  2262. * Creates a new Color3 from integer values (< 256)
  2263. * @param r defines the red component to read from (value between 0 and 255)
  2264. * @param g defines the green component to read from (value between 0 and 255)
  2265. * @param b defines the blue component to read from (value between 0 and 255)
  2266. * @param a defines the alpha component to read from (value between 0 and 255)
  2267. * @returns a new Color3 object
  2268. */
  2269. Color4.FromInts = function (r, g, b, a) {
  2270. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2271. };
  2272. /**
  2273. * Check the content of a given array and convert it to an array containing RGBA data
  2274. * If the original array was already containing count * 4 values then it is returned directly
  2275. * @param colors defines the array to check
  2276. * @param count defines the number of RGBA data to expect
  2277. * @returns an array containing count * 4 values (RGBA)
  2278. */
  2279. Color4.CheckColors4 = function (colors, count) {
  2280. // Check if color3 was used
  2281. if (colors.length === count * 3) {
  2282. var colors4 = [];
  2283. for (var index = 0; index < colors.length; index += 3) {
  2284. var newIndex = (index / 3) * 4;
  2285. colors4[newIndex] = colors[index];
  2286. colors4[newIndex + 1] = colors[index + 1];
  2287. colors4[newIndex + 2] = colors[index + 2];
  2288. colors4[newIndex + 3] = 1.0;
  2289. }
  2290. return colors4;
  2291. }
  2292. return colors;
  2293. };
  2294. return Color4;
  2295. }());
  2296. BABYLON.Color4 = Color4;
  2297. /**
  2298. * Class representing a vector containing 2 coordinates
  2299. */
  2300. var Vector2 = /** @class */ (function () {
  2301. /**
  2302. * Creates a new Vector2 from the given x and y coordinates
  2303. * @param x defines the first coordinate
  2304. * @param y defines the second coordinate
  2305. */
  2306. function Vector2(
  2307. /** defines the first coordinate */
  2308. x,
  2309. /** defines the second coordinate */
  2310. y) {
  2311. if (x === void 0) { x = 0; }
  2312. if (y === void 0) { y = 0; }
  2313. this.x = x;
  2314. this.y = y;
  2315. }
  2316. /**
  2317. * Gets a string with the Vector2 coordinates
  2318. * @returns a string with the Vector2 coordinates
  2319. */
  2320. Vector2.prototype.toString = function () {
  2321. return "{X: " + this.x + " Y:" + this.y + "}";
  2322. };
  2323. /**
  2324. * Gets class name
  2325. * @returns the string "Vector2"
  2326. */
  2327. Vector2.prototype.getClassName = function () {
  2328. return "Vector2";
  2329. };
  2330. /**
  2331. * Gets current vector hash code
  2332. * @returns the Vector2 hash code as a number
  2333. */
  2334. Vector2.prototype.getHashCode = function () {
  2335. var hash = this.x || 0;
  2336. hash = (hash * 397) ^ (this.y || 0);
  2337. return hash;
  2338. };
  2339. // Operators
  2340. /**
  2341. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2342. * @param array defines the source array
  2343. * @param index defines the offset in source array
  2344. * @returns the current Vector2
  2345. */
  2346. Vector2.prototype.toArray = function (array, index) {
  2347. if (index === void 0) { index = 0; }
  2348. array[index] = this.x;
  2349. array[index + 1] = this.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Copy the current vector to an array
  2354. * @returns a new array with 2 elements: the Vector2 coordinates.
  2355. */
  2356. Vector2.prototype.asArray = function () {
  2357. var result = new Array();
  2358. this.toArray(result, 0);
  2359. return result;
  2360. };
  2361. /**
  2362. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2363. * @param source defines the source Vector2
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.copyFrom = function (source) {
  2367. this.x = source.x;
  2368. this.y = source.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Sets the Vector2 coordinates with the given floats
  2373. * @param x defines the first coordinate
  2374. * @param y defines the second coordinate
  2375. * @returns the current updated Vector2
  2376. */
  2377. Vector2.prototype.copyFromFloats = function (x, y) {
  2378. this.x = x;
  2379. this.y = y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Sets the Vector2 coordinates with the given floats
  2384. * @param x defines the first coordinate
  2385. * @param y defines the second coordinate
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.set = function (x, y) {
  2389. return this.copyFromFloats(x, y);
  2390. };
  2391. /**
  2392. * Add another vector with the current one
  2393. * @param otherVector defines the other vector
  2394. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2395. */
  2396. Vector2.prototype.add = function (otherVector) {
  2397. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2398. };
  2399. /**
  2400. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @param result defines the target vector
  2403. * @returns the unmodified current Vector2
  2404. */
  2405. Vector2.prototype.addToRef = function (otherVector, result) {
  2406. result.x = this.x + otherVector.x;
  2407. result.y = this.y + otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2412. * @param otherVector defines the other vector
  2413. * @returns the current updated Vector2
  2414. */
  2415. Vector2.prototype.addInPlace = function (otherVector) {
  2416. this.x += otherVector.x;
  2417. this.y += otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.addVector3 = function (otherVector) {
  2426. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2427. };
  2428. /**
  2429. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2430. * @param otherVector defines the other vector
  2431. * @returns a new Vector2
  2432. */
  2433. Vector2.prototype.subtract = function (otherVector) {
  2434. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2435. };
  2436. /**
  2437. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2438. * @param otherVector defines the other vector
  2439. * @param result defines the target vector
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2443. result.x = this.x - otherVector.x;
  2444. result.y = this.y - otherVector.y;
  2445. return this;
  2446. };
  2447. /**
  2448. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2449. * @param otherVector defines the other vector
  2450. * @returns the current updated Vector2
  2451. */
  2452. Vector2.prototype.subtractInPlace = function (otherVector) {
  2453. this.x -= otherVector.x;
  2454. this.y -= otherVector.y;
  2455. return this;
  2456. };
  2457. /**
  2458. * Multiplies in place the current Vector2 coordinates by the given ones
  2459. * @param otherVector defines the other vector
  2460. * @returns the current updated Vector2
  2461. */
  2462. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2463. this.x *= otherVector.x;
  2464. this.y *= otherVector.y;
  2465. return this;
  2466. };
  2467. /**
  2468. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2469. * @param otherVector defines the other vector
  2470. * @returns a new Vector2
  2471. */
  2472. Vector2.prototype.multiply = function (otherVector) {
  2473. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2474. };
  2475. /**
  2476. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2477. * @param otherVector defines the other vector
  2478. * @param result defines the target vector
  2479. * @returns the unmodified current Vector2
  2480. */
  2481. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2482. result.x = this.x * otherVector.x;
  2483. result.y = this.y * otherVector.y;
  2484. return this;
  2485. };
  2486. /**
  2487. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2488. * @param x defines the first coordinate
  2489. * @param y defines the second coordinate
  2490. * @returns a new Vector2
  2491. */
  2492. Vector2.prototype.multiplyByFloats = function (x, y) {
  2493. return new Vector2(this.x * x, this.y * y);
  2494. };
  2495. /**
  2496. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2497. * @param otherVector defines the other vector
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.divide = function (otherVector) {
  2501. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2502. };
  2503. /**
  2504. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2505. * @param otherVector defines the other vector
  2506. * @param result defines the target vector
  2507. * @returns the unmodified current Vector2
  2508. */
  2509. Vector2.prototype.divideToRef = function (otherVector, result) {
  2510. result.x = this.x / otherVector.x;
  2511. result.y = this.y / otherVector.y;
  2512. return this;
  2513. };
  2514. /**
  2515. * Divides the current Vector2 coordinates by the given ones
  2516. * @param otherVector defines the other vector
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.divideInPlace = function (otherVector) {
  2520. return this.divideToRef(otherVector, this);
  2521. };
  2522. /**
  2523. * Gets a new Vector2 with current Vector2 negated coordinates
  2524. * @returns a new Vector2
  2525. */
  2526. Vector2.prototype.negate = function () {
  2527. return new Vector2(-this.x, -this.y);
  2528. };
  2529. /**
  2530. * Multiply the Vector2 coordinates by scale
  2531. * @param scale defines the scaling factor
  2532. * @returns the current updated Vector2
  2533. */
  2534. Vector2.prototype.scaleInPlace = function (scale) {
  2535. this.x *= scale;
  2536. this.y *= scale;
  2537. return this;
  2538. };
  2539. /**
  2540. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2541. * @param scale defines the scaling factor
  2542. * @returns a new Vector2
  2543. */
  2544. Vector2.prototype.scale = function (scale) {
  2545. var result = new Vector2(0, 0);
  2546. this.scaleToRef(scale, result);
  2547. return result;
  2548. };
  2549. /**
  2550. * Scale the current Vector2 values by a factor to a given Vector2
  2551. * @param scale defines the scale factor
  2552. * @param result defines the Vector2 object where to store the result
  2553. * @returns the unmodified current Vector2
  2554. */
  2555. Vector2.prototype.scaleToRef = function (scale, result) {
  2556. result.x = this.x * scale;
  2557. result.y = this.y * scale;
  2558. return this;
  2559. };
  2560. /**
  2561. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2562. * @param scale defines the scale factor
  2563. * @param result defines the Vector2 object where to store the result
  2564. * @returns the unmodified current Vector2
  2565. */
  2566. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2567. result.x += this.x * scale;
  2568. result.y += this.y * scale;
  2569. return this;
  2570. };
  2571. /**
  2572. * Gets a boolean if two vectors are equals
  2573. * @param otherVector defines the other vector
  2574. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2575. */
  2576. Vector2.prototype.equals = function (otherVector) {
  2577. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2578. };
  2579. /**
  2580. * Gets a boolean if two vectors are equals (using an epsilon value)
  2581. * @param otherVector defines the other vector
  2582. * @param epsilon defines the minimal distance to consider equality
  2583. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2584. */
  2585. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2586. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2587. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2588. };
  2589. /**
  2590. * Gets a new Vector2 from current Vector2 floored values
  2591. * @returns a new Vector2
  2592. */
  2593. Vector2.prototype.floor = function () {
  2594. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2595. };
  2596. /**
  2597. * Gets a new Vector2 from current Vector2 floored values
  2598. * @returns a new Vector2
  2599. */
  2600. Vector2.prototype.fract = function () {
  2601. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2602. };
  2603. // Properties
  2604. /**
  2605. * Gets the length of the vector
  2606. * @returns the vector length (float)
  2607. */
  2608. Vector2.prototype.length = function () {
  2609. return Math.sqrt(this.x * this.x + this.y * this.y);
  2610. };
  2611. /**
  2612. * Gets the vector squared length
  2613. * @returns the vector squared length (float)
  2614. */
  2615. Vector2.prototype.lengthSquared = function () {
  2616. return (this.x * this.x + this.y * this.y);
  2617. };
  2618. // Methods
  2619. /**
  2620. * Normalize the vector
  2621. * @returns the current updated Vector2
  2622. */
  2623. Vector2.prototype.normalize = function () {
  2624. var len = this.length();
  2625. if (len === 0)
  2626. return this;
  2627. var num = 1.0 / len;
  2628. this.x *= num;
  2629. this.y *= num;
  2630. return this;
  2631. };
  2632. /**
  2633. * Gets a new Vector2 copied from the Vector2
  2634. * @returns a new Vector2
  2635. */
  2636. Vector2.prototype.clone = function () {
  2637. return new Vector2(this.x, this.y);
  2638. };
  2639. // Statics
  2640. /**
  2641. * Gets a new Vector2(0, 0)
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Zero = function () {
  2645. return new Vector2(0, 0);
  2646. };
  2647. /**
  2648. * Gets a new Vector2(1, 1)
  2649. * @returns a new Vector2
  2650. */
  2651. Vector2.One = function () {
  2652. return new Vector2(1, 1);
  2653. };
  2654. /**
  2655. * Gets a new Vector2 set from the given index element of the given array
  2656. * @param array defines the data source
  2657. * @param offset defines the offset in the data source
  2658. * @returns a new Vector2
  2659. */
  2660. Vector2.FromArray = function (array, offset) {
  2661. if (offset === void 0) { offset = 0; }
  2662. return new Vector2(array[offset], array[offset + 1]);
  2663. };
  2664. /**
  2665. * Sets "result" from the given index element of the given array
  2666. * @param array defines the data source
  2667. * @param offset defines the offset in the data source
  2668. * @param result defines the target vector
  2669. */
  2670. Vector2.FromArrayToRef = function (array, offset, result) {
  2671. result.x = array[offset];
  2672. result.y = array[offset + 1];
  2673. };
  2674. /**
  2675. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2676. * @param value1 defines 1st point of control
  2677. * @param value2 defines 2nd point of control
  2678. * @param value3 defines 3rd point of control
  2679. * @param value4 defines 4th point of control
  2680. * @param amount defines the interpolation factor
  2681. * @returns a new Vector2
  2682. */
  2683. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2684. var squared = amount * amount;
  2685. var cubed = amount * squared;
  2686. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2687. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2688. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2689. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2690. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2691. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2692. return new Vector2(x, y);
  2693. };
  2694. /**
  2695. * 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".
  2696. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2697. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2698. * @param value defines the value to clamp
  2699. * @param min defines the lower limit
  2700. * @param max defines the upper limit
  2701. * @returns a new Vector2
  2702. */
  2703. Vector2.Clamp = function (value, min, max) {
  2704. var x = value.x;
  2705. x = (x > max.x) ? max.x : x;
  2706. x = (x < min.x) ? min.x : x;
  2707. var y = value.y;
  2708. y = (y > max.y) ? max.y : y;
  2709. y = (y < min.y) ? min.y : y;
  2710. return new Vector2(x, y);
  2711. };
  2712. /**
  2713. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2714. * @param value1 defines the 1st control point
  2715. * @param tangent1 defines the outgoing tangent
  2716. * @param value2 defines the 2nd control point
  2717. * @param tangent2 defines the incoming tangent
  2718. * @param amount defines the interpolation factor
  2719. * @returns a new Vector2
  2720. */
  2721. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2722. var squared = amount * amount;
  2723. var cubed = amount * squared;
  2724. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2725. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2726. var part3 = (cubed - (2.0 * squared)) + amount;
  2727. var part4 = cubed - squared;
  2728. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2729. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2730. return new Vector2(x, y);
  2731. };
  2732. /**
  2733. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2734. * @param start defines the start vector
  2735. * @param end defines the end vector
  2736. * @param amount defines the interpolation factor
  2737. * @returns a new Vector2
  2738. */
  2739. Vector2.Lerp = function (start, end, amount) {
  2740. var x = start.x + ((end.x - start.x) * amount);
  2741. var y = start.y + ((end.y - start.y) * amount);
  2742. return new Vector2(x, y);
  2743. };
  2744. /**
  2745. * Gets the dot product of the vector "left" and the vector "right"
  2746. * @param left defines first vector
  2747. * @param right defines second vector
  2748. * @returns the dot product (float)
  2749. */
  2750. Vector2.Dot = function (left, right) {
  2751. return left.x * right.x + left.y * right.y;
  2752. };
  2753. /**
  2754. * Returns a new Vector2 equal to the normalized given vector
  2755. * @param vector defines the vector to normalize
  2756. * @returns a new Vector2
  2757. */
  2758. Vector2.Normalize = function (vector) {
  2759. var newVector = vector.clone();
  2760. newVector.normalize();
  2761. return newVector;
  2762. };
  2763. /**
  2764. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2765. * @param left defines 1st vector
  2766. * @param right defines 2nd vector
  2767. * @returns a new Vector2
  2768. */
  2769. Vector2.Minimize = function (left, right) {
  2770. var x = (left.x < right.x) ? left.x : right.x;
  2771. var y = (left.y < right.y) ? left.y : right.y;
  2772. return new Vector2(x, y);
  2773. };
  2774. /**
  2775. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2776. * @param left defines 1st vector
  2777. * @param right defines 2nd vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Maximize = function (left, right) {
  2781. var x = (left.x > right.x) ? left.x : right.x;
  2782. var y = (left.y > right.y) ? left.y : right.y;
  2783. return new Vector2(x, y);
  2784. };
  2785. /**
  2786. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2787. * @param vector defines the vector to transform
  2788. * @param transformation defines the matrix to apply
  2789. * @returns a new Vector2
  2790. */
  2791. Vector2.Transform = function (vector, transformation) {
  2792. var r = Vector2.Zero();
  2793. Vector2.TransformToRef(vector, transformation, r);
  2794. return r;
  2795. };
  2796. /**
  2797. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2798. * @param vector defines the vector to transform
  2799. * @param transformation defines the matrix to apply
  2800. * @param result defines the target vector
  2801. */
  2802. Vector2.TransformToRef = function (vector, transformation, result) {
  2803. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2804. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2805. result.x = x;
  2806. result.y = y;
  2807. };
  2808. /**
  2809. * Determines if a given vector is included in a triangle
  2810. * @param p defines the vector to test
  2811. * @param p0 defines 1st triangle point
  2812. * @param p1 defines 2nd triangle point
  2813. * @param p2 defines 3rd triangle point
  2814. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2815. */
  2816. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2817. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2818. var sign = a < 0 ? -1 : 1;
  2819. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2820. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2821. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2822. };
  2823. /**
  2824. * Gets the distance between the vectors "value1" and "value2"
  2825. * @param value1 defines first vector
  2826. * @param value2 defines second vector
  2827. * @returns the distance between vectors
  2828. */
  2829. Vector2.Distance = function (value1, value2) {
  2830. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2831. };
  2832. /**
  2833. * Returns the squared distance between the vectors "value1" and "value2"
  2834. * @param value1 defines first vector
  2835. * @param value2 defines second vector
  2836. * @returns the squared distance between vectors
  2837. */
  2838. Vector2.DistanceSquared = function (value1, value2) {
  2839. var x = value1.x - value2.x;
  2840. var y = value1.y - value2.y;
  2841. return (x * x) + (y * y);
  2842. };
  2843. /**
  2844. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2845. * @param value1 defines first vector
  2846. * @param value2 defines second vector
  2847. * @returns a new Vector2
  2848. */
  2849. Vector2.Center = function (value1, value2) {
  2850. var center = value1.add(value2);
  2851. center.scaleInPlace(0.5);
  2852. return center;
  2853. };
  2854. /**
  2855. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2856. * @param p defines the middle point
  2857. * @param segA defines one point of the segment
  2858. * @param segB defines the other point of the segment
  2859. * @returns the shortest distance
  2860. */
  2861. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2862. var l2 = Vector2.DistanceSquared(segA, segB);
  2863. if (l2 === 0.0) {
  2864. return Vector2.Distance(p, segA);
  2865. }
  2866. var v = segB.subtract(segA);
  2867. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2868. var proj = segA.add(v.multiplyByFloats(t, t));
  2869. return Vector2.Distance(p, proj);
  2870. };
  2871. return Vector2;
  2872. }());
  2873. BABYLON.Vector2 = Vector2;
  2874. /**
  2875. * Classed used to store (x,y,z) vector representation
  2876. * A Vector3 is the main object used in 3D geometry
  2877. * It can represent etiher the coordinates of a point the space, either a direction
  2878. * Reminder: Babylon.js uses a left handed forward facing system
  2879. */
  2880. var Vector3 = /** @class */ (function () {
  2881. /**
  2882. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2883. * @param x defines the first coordinates (on X axis)
  2884. * @param y defines the second coordinates (on Y axis)
  2885. * @param z defines the third coordinates (on Z axis)
  2886. */
  2887. function Vector3(
  2888. /**
  2889. * Defines the first coordinates (on X axis)
  2890. */
  2891. x,
  2892. /**
  2893. * Defines the second coordinates (on Y axis)
  2894. */
  2895. y,
  2896. /**
  2897. * Defines the third coordinates (on Z axis)
  2898. */
  2899. z) {
  2900. if (x === void 0) { x = 0; }
  2901. if (y === void 0) { y = 0; }
  2902. if (z === void 0) { z = 0; }
  2903. this.x = x;
  2904. this.y = y;
  2905. this.z = z;
  2906. }
  2907. /**
  2908. * Creates a string representation of the Vector3
  2909. * @returns a string with the Vector3 coordinates.
  2910. */
  2911. Vector3.prototype.toString = function () {
  2912. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2913. };
  2914. /**
  2915. * Gets the class name
  2916. * @returns the string "Vector3"
  2917. */
  2918. Vector3.prototype.getClassName = function () {
  2919. return "Vector3";
  2920. };
  2921. /**
  2922. * Creates the Vector3 hash code
  2923. * @returns a number which tends to be unique between Vector3 instances
  2924. */
  2925. Vector3.prototype.getHashCode = function () {
  2926. var hash = this.x || 0;
  2927. hash = (hash * 397) ^ (this.y || 0);
  2928. hash = (hash * 397) ^ (this.z || 0);
  2929. return hash;
  2930. };
  2931. // Operators
  2932. /**
  2933. * Creates an array containing three elements : the coordinates of the Vector3
  2934. * @returns a new array of numbers
  2935. */
  2936. Vector3.prototype.asArray = function () {
  2937. var result = [];
  2938. this.toArray(result, 0);
  2939. return result;
  2940. };
  2941. /**
  2942. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2943. * @param array defines the destination array
  2944. * @param index defines the offset in the destination array
  2945. * @returns the current Vector3
  2946. */
  2947. Vector3.prototype.toArray = function (array, index) {
  2948. if (index === void 0) { index = 0; }
  2949. array[index] = this.x;
  2950. array[index + 1] = this.y;
  2951. array[index + 2] = this.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2956. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2957. */
  2958. Vector3.prototype.toQuaternion = function () {
  2959. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2960. };
  2961. /**
  2962. * Adds the given vector to the current Vector3
  2963. * @param otherVector defines the second operand
  2964. * @returns the current updated Vector3
  2965. */
  2966. Vector3.prototype.addInPlace = function (otherVector) {
  2967. this.x += otherVector.x;
  2968. this.y += otherVector.y;
  2969. this.z += otherVector.z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2974. * @param otherVector defines the second operand
  2975. * @returns the resulting Vector3
  2976. */
  2977. Vector3.prototype.add = function (otherVector) {
  2978. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2979. };
  2980. /**
  2981. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2982. * @param otherVector defines the second operand
  2983. * @param result defines the Vector3 object where to store the result
  2984. * @returns the current Vector3
  2985. */
  2986. Vector3.prototype.addToRef = function (otherVector, result) {
  2987. result.x = this.x + otherVector.x;
  2988. result.y = this.y + otherVector.y;
  2989. result.z = this.z + otherVector.z;
  2990. return this;
  2991. };
  2992. /**
  2993. * Subtract the given vector from the current Vector3
  2994. * @param otherVector defines the second operand
  2995. * @returns the current updated Vector3
  2996. */
  2997. Vector3.prototype.subtractInPlace = function (otherVector) {
  2998. this.x -= otherVector.x;
  2999. this.y -= otherVector.y;
  3000. this.z -= otherVector.z;
  3001. return this;
  3002. };
  3003. /**
  3004. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  3005. * @param otherVector defines the second operand
  3006. * @returns the resulting Vector3
  3007. */
  3008. Vector3.prototype.subtract = function (otherVector) {
  3009. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  3010. };
  3011. /**
  3012. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  3013. * @param otherVector defines the second operand
  3014. * @param result defines the Vector3 object where to store the result
  3015. * @returns the current Vector3
  3016. */
  3017. Vector3.prototype.subtractToRef = function (otherVector, result) {
  3018. result.x = this.x - otherVector.x;
  3019. result.y = this.y - otherVector.y;
  3020. result.z = this.z - otherVector.z;
  3021. return this;
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  3025. * @param x defines the x coordinate of the operand
  3026. * @param y defines the y coordinate of the operand
  3027. * @param z defines the z coordinate of the operand
  3028. * @returns the resulting Vector3
  3029. */
  3030. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3031. return new Vector3(this.x - x, this.y - y, this.z - z);
  3032. };
  3033. /**
  3034. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3035. * @param x defines the x coordinate of the operand
  3036. * @param y defines the y coordinate of the operand
  3037. * @param z defines the z coordinate of the operand
  3038. * @param result defines the Vector3 object where to store the result
  3039. * @returns the current Vector3
  3040. */
  3041. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3042. result.x = this.x - x;
  3043. result.y = this.y - y;
  3044. result.z = this.z - z;
  3045. return this;
  3046. };
  3047. /**
  3048. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3049. * @returns a new Vector3
  3050. */
  3051. Vector3.prototype.negate = function () {
  3052. return new Vector3(-this.x, -this.y, -this.z);
  3053. };
  3054. /**
  3055. * Multiplies the Vector3 coordinates by the float "scale"
  3056. * @param scale defines the multiplier factor
  3057. * @returns the current updated Vector3
  3058. */
  3059. Vector3.prototype.scaleInPlace = function (scale) {
  3060. this.x *= scale;
  3061. this.y *= scale;
  3062. this.z *= scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3067. * @param scale defines the multiplier factor
  3068. * @returns a new Vector3
  3069. */
  3070. Vector3.prototype.scale = function (scale) {
  3071. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3072. };
  3073. /**
  3074. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3075. * @param scale defines the multiplier factor
  3076. * @param result defines the Vector3 object where to store the result
  3077. * @returns the current Vector3
  3078. */
  3079. Vector3.prototype.scaleToRef = function (scale, result) {
  3080. result.x = this.x * scale;
  3081. result.y = this.y * scale;
  3082. result.z = this.z * scale;
  3083. return this;
  3084. };
  3085. /**
  3086. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3087. * @param scale defines the scale factor
  3088. * @param result defines the Vector3 object where to store the result
  3089. * @returns the unmodified current Vector3
  3090. */
  3091. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3092. result.x += this.x * scale;
  3093. result.y += this.y * scale;
  3094. result.z += this.z * scale;
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3099. * @param otherVector defines the second operand
  3100. * @returns true if both vectors are equals
  3101. */
  3102. Vector3.prototype.equals = function (otherVector) {
  3103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3104. };
  3105. /**
  3106. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3107. * @param otherVector defines the second operand
  3108. * @param epsilon defines the minimal distance to define values as equals
  3109. * @returns true if both vectors are distant less than epsilon
  3110. */
  3111. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3112. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3113. 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);
  3114. };
  3115. /**
  3116. * Returns true if the current Vector3 coordinates equals the given floats
  3117. * @param x defines the x coordinate of the operand
  3118. * @param y defines the y coordinate of the operand
  3119. * @param z defines the z coordinate of the operand
  3120. * @returns true if both vectors are equals
  3121. */
  3122. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3123. return this.x === x && this.y === y && this.z === z;
  3124. };
  3125. /**
  3126. * Multiplies the current Vector3 coordinates by the given ones
  3127. * @param otherVector defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3131. this.x *= otherVector.x;
  3132. this.y *= otherVector.y;
  3133. this.z *= otherVector.z;
  3134. return this;
  3135. };
  3136. /**
  3137. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3138. * @param otherVector defines the second operand
  3139. * @returns the new Vector3
  3140. */
  3141. Vector3.prototype.multiply = function (otherVector) {
  3142. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3143. };
  3144. /**
  3145. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3146. * @param otherVector defines the second operand
  3147. * @param result defines the Vector3 object where to store the result
  3148. * @returns the current Vector3
  3149. */
  3150. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3151. result.x = this.x * otherVector.x;
  3152. result.y = this.y * otherVector.y;
  3153. result.z = this.z * otherVector.z;
  3154. return this;
  3155. };
  3156. /**
  3157. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3158. * @param x defines the x coordinate of the operand
  3159. * @param y defines the y coordinate of the operand
  3160. * @param z defines the z coordinate of the operand
  3161. * @returns the new Vector3
  3162. */
  3163. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3164. return new Vector3(this.x * x, this.y * y, this.z * z);
  3165. };
  3166. /**
  3167. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3168. * @param otherVector defines the second operand
  3169. * @returns the new Vector3
  3170. */
  3171. Vector3.prototype.divide = function (otherVector) {
  3172. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3173. };
  3174. /**
  3175. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3176. * @param otherVector defines the second operand
  3177. * @param result defines the Vector3 object where to store the result
  3178. * @returns the current Vector3
  3179. */
  3180. Vector3.prototype.divideToRef = function (otherVector, result) {
  3181. result.x = this.x / otherVector.x;
  3182. result.y = this.y / otherVector.y;
  3183. result.z = this.z / otherVector.z;
  3184. return this;
  3185. };
  3186. /**
  3187. * Divides the current Vector3 coordinates by the given ones.
  3188. * @param otherVector defines the second operand
  3189. * @returns the current updated Vector3
  3190. */
  3191. Vector3.prototype.divideInPlace = function (otherVector) {
  3192. return this.divideToRef(otherVector, this);
  3193. };
  3194. /**
  3195. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3196. * @param other defines the second operand
  3197. * @returns the current updated Vector3
  3198. */
  3199. Vector3.prototype.minimizeInPlace = function (other) {
  3200. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3201. };
  3202. /**
  3203. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3204. * @param other defines the second operand
  3205. * @returns the current updated Vector3
  3206. */
  3207. Vector3.prototype.maximizeInPlace = function (other) {
  3208. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3209. };
  3210. /**
  3211. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3212. * @param x defines the x coordinate of the operand
  3213. * @param y defines the y coordinate of the operand
  3214. * @param z defines the z coordinate of the operand
  3215. * @returns the current updated Vector3
  3216. */
  3217. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3218. this.x = Math.min(this.x, x);
  3219. this.y = Math.min(this.y, y);
  3220. this.z = Math.min(this.z, z);
  3221. return this;
  3222. };
  3223. /**
  3224. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3225. * @param x defines the x coordinate of the operand
  3226. * @param y defines the y coordinate of the operand
  3227. * @param z defines the z coordinate of the operand
  3228. * @returns the current updated Vector3
  3229. */
  3230. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3231. this.x = Math.max(this.x, x);
  3232. this.y = Math.max(this.y, y);
  3233. this.z = Math.max(this.z, z);
  3234. return this;
  3235. };
  3236. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3237. /**
  3238. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3239. */
  3240. get: function () {
  3241. var absX = Math.abs(this.x);
  3242. var absY = Math.abs(this.y);
  3243. if (absX !== absY) {
  3244. return true;
  3245. }
  3246. var absZ = Math.abs(this.z);
  3247. if (absX !== absZ) {
  3248. return true;
  3249. }
  3250. if (absY !== absZ) {
  3251. return true;
  3252. }
  3253. return false;
  3254. },
  3255. enumerable: true,
  3256. configurable: true
  3257. });
  3258. /**
  3259. * Gets a new Vector3 from current Vector3 floored values
  3260. * @returns a new Vector3
  3261. */
  3262. Vector3.prototype.floor = function () {
  3263. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3264. };
  3265. /**
  3266. * Gets a new Vector3 from current Vector3 floored values
  3267. * @returns a new Vector3
  3268. */
  3269. Vector3.prototype.fract = function () {
  3270. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3271. };
  3272. // Properties
  3273. /**
  3274. * Gets the length of the Vector3
  3275. * @returns the length of the Vecto3
  3276. */
  3277. Vector3.prototype.length = function () {
  3278. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3279. };
  3280. /**
  3281. * Gets the squared length of the Vector3
  3282. * @returns squared length of the Vector3
  3283. */
  3284. Vector3.prototype.lengthSquared = function () {
  3285. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3286. };
  3287. /**
  3288. * Normalize the current Vector3.
  3289. * Please note that this is an in place operation.
  3290. * @returns the current updated Vector3
  3291. */
  3292. Vector3.prototype.normalize = function () {
  3293. var len = this.length();
  3294. if (len === 0 || len === 1.0)
  3295. return this;
  3296. var num = 1.0 / len;
  3297. this.x *= num;
  3298. this.y *= num;
  3299. this.z *= num;
  3300. return this;
  3301. };
  3302. /**
  3303. * Normalize the current Vector3 to a new vector
  3304. * @returns the new Vector3
  3305. */
  3306. Vector3.prototype.normalizeToNew = function () {
  3307. var normalized = new Vector3(0, 0, 0);
  3308. this.normalizeToRef(normalized);
  3309. return normalized;
  3310. };
  3311. /**
  3312. * Normalize the current Vector3 to the reference
  3313. * @param reference define the Vector3 to update
  3314. * @returns the updated Vector3
  3315. */
  3316. Vector3.prototype.normalizeToRef = function (reference) {
  3317. var len = this.length();
  3318. if (len === 0 || len === 1.0) {
  3319. reference.set(this.x, this.y, this.z);
  3320. return reference;
  3321. }
  3322. var scale = 1.0 / len;
  3323. this.scaleToRef(scale, reference);
  3324. return reference;
  3325. };
  3326. /**
  3327. * Creates a new Vector3 copied from the current Vector3
  3328. * @returns the new Vector3
  3329. */
  3330. Vector3.prototype.clone = function () {
  3331. return new Vector3(this.x, this.y, this.z);
  3332. };
  3333. /**
  3334. * Copies the given vector coordinates to the current Vector3 ones
  3335. * @param source defines the source Vector3
  3336. * @returns the current updated Vector3
  3337. */
  3338. Vector3.prototype.copyFrom = function (source) {
  3339. this.x = source.x;
  3340. this.y = source.y;
  3341. this.z = source.z;
  3342. return this;
  3343. };
  3344. /**
  3345. * Copies the given floats to the current Vector3 coordinates
  3346. * @param x defines the x coordinate of the operand
  3347. * @param y defines the y coordinate of the operand
  3348. * @param z defines the z coordinate of the operand
  3349. * @returns the current updated Vector3
  3350. */
  3351. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3352. this.x = x;
  3353. this.y = y;
  3354. this.z = z;
  3355. return this;
  3356. };
  3357. /**
  3358. * Copies the given floats to the current Vector3 coordinates
  3359. * @param x defines the x coordinate of the operand
  3360. * @param y defines the y coordinate of the operand
  3361. * @param z defines the z coordinate of the operand
  3362. * @returns the current updated Vector3
  3363. */
  3364. Vector3.prototype.set = function (x, y, z) {
  3365. return this.copyFromFloats(x, y, z);
  3366. };
  3367. // Statics
  3368. /**
  3369. * Get the clip factor between two vectors
  3370. * @param vector0 defines the first operand
  3371. * @param vector1 defines the second operand
  3372. * @param axis defines the axis to use
  3373. * @param size defines the size along the axis
  3374. * @returns the clip factor
  3375. */
  3376. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3377. var d0 = Vector3.Dot(vector0, axis) - size;
  3378. var d1 = Vector3.Dot(vector1, axis) - size;
  3379. var s = d0 / (d0 - d1);
  3380. return s;
  3381. };
  3382. /**
  3383. * Get angle between two vectors
  3384. * @param vector0 angle between vector0 and vector1
  3385. * @param vector1 angle between vector0 and vector1
  3386. * @param normal direction of the normal
  3387. * @return the angle between vector0 and vector1
  3388. */
  3389. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3390. var v0 = vector0.clone().normalize();
  3391. var v1 = vector1.clone().normalize();
  3392. var dot = Vector3.Dot(v0, v1);
  3393. var n = Vector3.Cross(v0, v1);
  3394. if (Vector3.Dot(n, normal) > 0) {
  3395. return Math.acos(dot);
  3396. }
  3397. return -Math.acos(dot);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set from the index "offset" of the given array
  3401. * @param array defines the source array
  3402. * @param offset defines the offset in the source array
  3403. * @returns the new Vector3
  3404. */
  3405. Vector3.FromArray = function (array, offset) {
  3406. if (!offset) {
  3407. offset = 0;
  3408. }
  3409. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3410. };
  3411. /**
  3412. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3413. * This function is deprecated. Use FromArray instead
  3414. * @param array defines the source array
  3415. * @param offset defines the offset in the source array
  3416. * @returns the new Vector3
  3417. */
  3418. Vector3.FromFloatArray = function (array, offset) {
  3419. return Vector3.FromArray(array, offset);
  3420. };
  3421. /**
  3422. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3423. * @param array defines the source array
  3424. * @param offset defines the offset in the source array
  3425. * @param result defines the Vector3 where to store the result
  3426. */
  3427. Vector3.FromArrayToRef = function (array, offset, result) {
  3428. result.x = array[offset];
  3429. result.y = array[offset + 1];
  3430. result.z = array[offset + 2];
  3431. };
  3432. /**
  3433. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3434. * This function is deprecated. Use FromArrayToRef instead.
  3435. * @param array defines the source array
  3436. * @param offset defines the offset in the source array
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3440. return Vector3.FromArrayToRef(array, offset, result);
  3441. };
  3442. /**
  3443. * Sets the given vector "result" with the given floats.
  3444. * @param x defines the x coordinate of the source
  3445. * @param y defines the y coordinate of the source
  3446. * @param z defines the z coordinate of the source
  3447. * @param result defines the Vector3 where to store the result
  3448. */
  3449. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3450. result.x = x;
  3451. result.y = y;
  3452. result.z = z;
  3453. };
  3454. /**
  3455. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3456. * @returns a new empty Vector3
  3457. */
  3458. Vector3.Zero = function () {
  3459. return new Vector3(0.0, 0.0, 0.0);
  3460. };
  3461. /**
  3462. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3463. * @returns a new unit Vector3
  3464. */
  3465. Vector3.One = function () {
  3466. return new Vector3(1.0, 1.0, 1.0);
  3467. };
  3468. /**
  3469. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3470. * @returns a new up Vector3
  3471. */
  3472. Vector3.Up = function () {
  3473. return new Vector3(0.0, 1.0, 0.0);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3477. * @returns a new down Vector3
  3478. */
  3479. Vector3.Down = function () {
  3480. return new Vector3(0.0, -1.0, 0.0);
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3484. * @returns a new forward Vector3
  3485. */
  3486. Vector3.Forward = function () {
  3487. return new Vector3(0.0, 0.0, 1.0);
  3488. };
  3489. /**
  3490. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3491. * @returns a new forward Vector3
  3492. */
  3493. Vector3.Backward = function () {
  3494. return new Vector3(0.0, 0.0, -1.0);
  3495. };
  3496. /**
  3497. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3498. * @returns a new right Vector3
  3499. */
  3500. Vector3.Right = function () {
  3501. return new Vector3(1.0, 0.0, 0.0);
  3502. };
  3503. /**
  3504. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3505. * @returns a new left Vector3
  3506. */
  3507. Vector3.Left = function () {
  3508. return new Vector3(-1.0, 0.0, 0.0);
  3509. };
  3510. /**
  3511. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3512. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3513. * @param vector defines the Vector3 to transform
  3514. * @param transformation defines the transformation matrix
  3515. * @returns the transformed Vector3
  3516. */
  3517. Vector3.TransformCoordinates = function (vector, transformation) {
  3518. var result = Vector3.Zero();
  3519. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3520. return result;
  3521. };
  3522. /**
  3523. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3524. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3525. * @param vector defines the Vector3 to transform
  3526. * @param transformation defines the transformation matrix
  3527. * @param result defines the Vector3 where to store the result
  3528. */
  3529. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3530. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3531. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3532. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3533. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3534. result.x = x / w;
  3535. result.y = y / w;
  3536. result.z = z / w;
  3537. };
  3538. /**
  3539. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3540. * This method computes tranformed coordinates only, not transformed direction vectors
  3541. * @param x define the x coordinate of the source vector
  3542. * @param y define the y coordinate of the source vector
  3543. * @param z define the z coordinate of the source vector
  3544. * @param transformation defines the transformation matrix
  3545. * @param result defines the Vector3 where to store the result
  3546. */
  3547. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3548. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3549. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3550. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3551. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3552. result.x = rx / rw;
  3553. result.y = ry / rw;
  3554. result.z = rz / rw;
  3555. };
  3556. /**
  3557. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3558. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3559. * @param vector defines the Vector3 to transform
  3560. * @param transformation defines the transformation matrix
  3561. * @returns the new Vector3
  3562. */
  3563. Vector3.TransformNormal = function (vector, transformation) {
  3564. var result = Vector3.Zero();
  3565. Vector3.TransformNormalToRef(vector, transformation, result);
  3566. return result;
  3567. };
  3568. /**
  3569. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3570. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3571. * @param vector defines the Vector3 to transform
  3572. * @param transformation defines the transformation matrix
  3573. * @param result defines the Vector3 where to store the result
  3574. */
  3575. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3576. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3577. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3578. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3579. result.x = x;
  3580. result.y = y;
  3581. result.z = z;
  3582. };
  3583. /**
  3584. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3585. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3586. * @param x define the x coordinate of the source vector
  3587. * @param y define the y coordinate of the source vector
  3588. * @param z define the z coordinate of the source vector
  3589. * @param transformation defines the transformation matrix
  3590. * @param result defines the Vector3 where to store the result
  3591. */
  3592. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3593. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3594. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3595. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3596. };
  3597. /**
  3598. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3599. * @param value1 defines the first control point
  3600. * @param value2 defines the second control point
  3601. * @param value3 defines the third control point
  3602. * @param value4 defines the fourth control point
  3603. * @param amount defines the amount on the spline to use
  3604. * @returns the new Vector3
  3605. */
  3606. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3607. var squared = amount * amount;
  3608. var cubed = amount * squared;
  3609. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3610. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3611. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3612. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3613. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3614. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3615. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3616. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3617. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3618. return new Vector3(x, y, z);
  3619. };
  3620. /**
  3621. * 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"
  3622. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3623. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3624. * @param value defines the current value
  3625. * @param min defines the lower range value
  3626. * @param max defines the upper range value
  3627. * @returns the new Vector3
  3628. */
  3629. Vector3.Clamp = function (value, min, max) {
  3630. var x = value.x;
  3631. x = (x > max.x) ? max.x : x;
  3632. x = (x < min.x) ? min.x : x;
  3633. var y = value.y;
  3634. y = (y > max.y) ? max.y : y;
  3635. y = (y < min.y) ? min.y : y;
  3636. var z = value.z;
  3637. z = (z > max.z) ? max.z : z;
  3638. z = (z < min.z) ? min.z : z;
  3639. return new Vector3(x, y, z);
  3640. };
  3641. /**
  3642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3643. * @param value1 defines the first control point
  3644. * @param tangent1 defines the first tangent vector
  3645. * @param value2 defines the second control point
  3646. * @param tangent2 defines the second tangent vector
  3647. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3648. * @returns the new Vector3
  3649. */
  3650. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3651. var squared = amount * amount;
  3652. var cubed = amount * squared;
  3653. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3654. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3655. var part3 = (cubed - (2.0 * squared)) + amount;
  3656. var part4 = cubed - squared;
  3657. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3658. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3659. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3660. return new Vector3(x, y, z);
  3661. };
  3662. /**
  3663. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3664. * @param start defines the start value
  3665. * @param end defines the end value
  3666. * @param amount max defines amount between both (between 0 and 1)
  3667. * @returns the new Vector3
  3668. */
  3669. Vector3.Lerp = function (start, end, amount) {
  3670. var result = new Vector3(0, 0, 0);
  3671. Vector3.LerpToRef(start, end, amount, result);
  3672. return result;
  3673. };
  3674. /**
  3675. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3676. * @param start defines the start value
  3677. * @param end defines the end value
  3678. * @param amount max defines amount between both (between 0 and 1)
  3679. * @param result defines the Vector3 where to store the result
  3680. */
  3681. Vector3.LerpToRef = function (start, end, amount, result) {
  3682. result.x = start.x + ((end.x - start.x) * amount);
  3683. result.y = start.y + ((end.y - start.y) * amount);
  3684. result.z = start.z + ((end.z - start.z) * amount);
  3685. };
  3686. /**
  3687. * Returns the dot product (float) between the vectors "left" and "right"
  3688. * @param left defines the left operand
  3689. * @param right defines the right operand
  3690. * @returns the dot product
  3691. */
  3692. Vector3.Dot = function (left, right) {
  3693. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3694. };
  3695. /**
  3696. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3697. * The cross product is then orthogonal to both "left" and "right"
  3698. * @param left defines the left operand
  3699. * @param right defines the right operand
  3700. * @returns the cross product
  3701. */
  3702. Vector3.Cross = function (left, right) {
  3703. var result = Vector3.Zero();
  3704. Vector3.CrossToRef(left, right, result);
  3705. return result;
  3706. };
  3707. /**
  3708. * Sets the given vector "result" with the cross product of "left" and "right"
  3709. * The cross product is then orthogonal to both "left" and "right"
  3710. * @param left defines the left operand
  3711. * @param right defines the right operand
  3712. * @param result defines the Vector3 where to store the result
  3713. */
  3714. Vector3.CrossToRef = function (left, right, result) {
  3715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3718. result.copyFrom(MathTmp.Vector3[0]);
  3719. };
  3720. /**
  3721. * Returns a new Vector3 as the normalization of the given vector
  3722. * @param vector defines the Vector3 to normalize
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Normalize = function (vector) {
  3726. var result = Vector3.Zero();
  3727. Vector3.NormalizeToRef(vector, result);
  3728. return result;
  3729. };
  3730. /**
  3731. * Sets the given vector "result" with the normalization of the given first vector
  3732. * @param vector defines the Vector3 to normalize
  3733. * @param result defines the Vector3 where to store the result
  3734. */
  3735. Vector3.NormalizeToRef = function (vector, result) {
  3736. result.copyFrom(vector);
  3737. result.normalize();
  3738. };
  3739. /**
  3740. * Project a Vector3 onto screen space
  3741. * @param vector defines the Vector3 to project
  3742. * @param world defines the world matrix to use
  3743. * @param transform defines the transform (view x projection) matrix to use
  3744. * @param viewport defines the screen viewport to use
  3745. * @returns the new Vector3
  3746. */
  3747. Vector3.Project = function (vector, world, transform, viewport) {
  3748. var cw = viewport.width;
  3749. var ch = viewport.height;
  3750. var cx = viewport.x;
  3751. var cy = viewport.y;
  3752. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3753. 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);
  3754. var matrix = MathTmp.Matrix[0];
  3755. world.multiplyToRef(transform, matrix);
  3756. matrix.multiplyToRef(viewportMatrix, matrix);
  3757. return Vector3.TransformCoordinates(vector, matrix);
  3758. };
  3759. /**
  3760. * Unproject from screen space to object space
  3761. * @param source defines the screen space Vector3 to use
  3762. * @param viewportWidth defines the current width of the viewport
  3763. * @param viewportHeight defines the current height of the viewport
  3764. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3765. * @param transform defines the transform (view x projection) matrix to use
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3769. var matrix = MathTmp.Matrix[0];
  3770. world.multiplyToRef(transform, matrix);
  3771. matrix.invert();
  3772. source.x = source.x / viewportWidth * 2 - 1;
  3773. source.y = -(source.y / viewportHeight * 2 - 1);
  3774. var vector = Vector3.TransformCoordinates(source, matrix);
  3775. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3776. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3777. vector = vector.scale(1.0 / num);
  3778. }
  3779. return vector;
  3780. };
  3781. /**
  3782. * Unproject from screen space to object space
  3783. * @param source defines the screen space Vector3 to use
  3784. * @param viewportWidth defines the current width of the viewport
  3785. * @param viewportHeight defines the current height of the viewport
  3786. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3787. * @param view defines the view matrix to use
  3788. * @param projection defines the projection matrix to use
  3789. * @returns the new Vector3
  3790. */
  3791. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3792. var result = Vector3.Zero();
  3793. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3794. return result;
  3795. };
  3796. /**
  3797. * Unproject from screen space to object space
  3798. * @param source defines the screen space Vector3 to use
  3799. * @param viewportWidth defines the current width of the viewport
  3800. * @param viewportHeight defines the current height of the viewport
  3801. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3802. * @param view defines the view matrix to use
  3803. * @param projection defines the projection matrix to use
  3804. * @param result defines the Vector3 where to store the result
  3805. */
  3806. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3807. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3808. };
  3809. /**
  3810. * Unproject from screen space to object space
  3811. * @param sourceX defines the screen space x coordinate to use
  3812. * @param sourceY defines the screen space y coordinate to use
  3813. * @param sourceZ defines the screen space z coordinate to use
  3814. * @param viewportWidth defines the current width of the viewport
  3815. * @param viewportHeight defines the current height of the viewport
  3816. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3817. * @param view defines the view matrix to use
  3818. * @param projection defines the projection matrix to use
  3819. * @param result defines the Vector3 where to store the result
  3820. */
  3821. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3822. var matrix = MathTmp.Matrix[0];
  3823. world.multiplyToRef(view, matrix);
  3824. matrix.multiplyToRef(projection, matrix);
  3825. matrix.invert();
  3826. var screenSource = MathTmp.Vector3[0];
  3827. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3828. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3829. screenSource.z = 2 * sourceZ - 1.0;
  3830. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3831. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3832. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3833. result.scaleInPlace(1.0 / num);
  3834. }
  3835. };
  3836. /**
  3837. * Gets the minimal coordinate values between two Vector3
  3838. * @param left defines the first operand
  3839. * @param right defines the second operand
  3840. * @returns the new Vector3
  3841. */
  3842. Vector3.Minimize = function (left, right) {
  3843. var min = left.clone();
  3844. min.minimizeInPlace(right);
  3845. return min;
  3846. };
  3847. /**
  3848. * Gets the maximal coordinate values between two Vector3
  3849. * @param left defines the first operand
  3850. * @param right defines the second operand
  3851. * @returns the new Vector3
  3852. */
  3853. Vector3.Maximize = function (left, right) {
  3854. var max = left.clone();
  3855. max.maximizeInPlace(right);
  3856. return max;
  3857. };
  3858. /**
  3859. * Returns the distance between the vectors "value1" and "value2"
  3860. * @param value1 defines the first operand
  3861. * @param value2 defines the second operand
  3862. * @returns the distance
  3863. */
  3864. Vector3.Distance = function (value1, value2) {
  3865. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3866. };
  3867. /**
  3868. * Returns the squared distance between the vectors "value1" and "value2"
  3869. * @param value1 defines the first operand
  3870. * @param value2 defines the second operand
  3871. * @returns the squared distance
  3872. */
  3873. Vector3.DistanceSquared = function (value1, value2) {
  3874. var x = value1.x - value2.x;
  3875. var y = value1.y - value2.y;
  3876. var z = value1.z - value2.z;
  3877. return (x * x) + (y * y) + (z * z);
  3878. };
  3879. /**
  3880. * Returns a new Vector3 located at the center between "value1" and "value2"
  3881. * @param value1 defines the first operand
  3882. * @param value2 defines the second operand
  3883. * @returns the new Vector3
  3884. */
  3885. Vector3.Center = function (value1, value2) {
  3886. var center = value1.add(value2);
  3887. center.scaleInPlace(0.5);
  3888. return center;
  3889. };
  3890. /**
  3891. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3892. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3893. * to something in order to rotate it from its local system to the given target system
  3894. * Note: axis1, axis2 and axis3 are normalized during this operation
  3895. * @param axis1 defines the first axis
  3896. * @param axis2 defines the second axis
  3897. * @param axis3 defines the third axis
  3898. * @returns a new Vector3
  3899. */
  3900. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3901. var rotation = Vector3.Zero();
  3902. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3903. return rotation;
  3904. };
  3905. /**
  3906. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3907. * @param axis1 defines the first axis
  3908. * @param axis2 defines the second axis
  3909. * @param axis3 defines the third axis
  3910. * @param ref defines the Vector3 where to store the result
  3911. */
  3912. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3913. var quat = MathTmp.Quaternion[0];
  3914. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3915. quat.toEulerAnglesToRef(ref);
  3916. };
  3917. return Vector3;
  3918. }());
  3919. BABYLON.Vector3 = Vector3;
  3920. /**
  3921. * Vector4 class created for EulerAngle class conversion to Quaternion
  3922. */
  3923. var Vector4 = /** @class */ (function () {
  3924. /**
  3925. * Creates a Vector4 object from the given floats.
  3926. * @param x x value of the vector
  3927. * @param y y value of the vector
  3928. * @param z z value of the vector
  3929. * @param w w value of the vector
  3930. */
  3931. function Vector4(
  3932. /** x value of the vector */
  3933. x,
  3934. /** y value of the vector */
  3935. y,
  3936. /** z value of the vector */
  3937. z,
  3938. /** w value of the vector */
  3939. w) {
  3940. this.x = x;
  3941. this.y = y;
  3942. this.z = z;
  3943. this.w = w;
  3944. }
  3945. /**
  3946. * Returns the string with the Vector4 coordinates.
  3947. * @returns a string containing all the vector values
  3948. */
  3949. Vector4.prototype.toString = function () {
  3950. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3951. };
  3952. /**
  3953. * Returns the string "Vector4".
  3954. * @returns "Vector4"
  3955. */
  3956. Vector4.prototype.getClassName = function () {
  3957. return "Vector4";
  3958. };
  3959. /**
  3960. * Returns the Vector4 hash code.
  3961. * @returns a unique hash code
  3962. */
  3963. Vector4.prototype.getHashCode = function () {
  3964. var hash = this.x || 0;
  3965. hash = (hash * 397) ^ (this.y || 0);
  3966. hash = (hash * 397) ^ (this.z || 0);
  3967. hash = (hash * 397) ^ (this.w || 0);
  3968. return hash;
  3969. };
  3970. // Operators
  3971. /**
  3972. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3973. * @returns the resulting array
  3974. */
  3975. Vector4.prototype.asArray = function () {
  3976. var result = new Array();
  3977. this.toArray(result, 0);
  3978. return result;
  3979. };
  3980. /**
  3981. * Populates the given array from the given index with the Vector4 coordinates.
  3982. * @param array array to populate
  3983. * @param index index of the array to start at (default: 0)
  3984. * @returns the Vector4.
  3985. */
  3986. Vector4.prototype.toArray = function (array, index) {
  3987. if (index === undefined) {
  3988. index = 0;
  3989. }
  3990. array[index] = this.x;
  3991. array[index + 1] = this.y;
  3992. array[index + 2] = this.z;
  3993. array[index + 3] = this.w;
  3994. return this;
  3995. };
  3996. /**
  3997. * Adds the given vector to the current Vector4.
  3998. * @param otherVector the vector to add
  3999. * @returns the updated Vector4.
  4000. */
  4001. Vector4.prototype.addInPlace = function (otherVector) {
  4002. this.x += otherVector.x;
  4003. this.y += otherVector.y;
  4004. this.z += otherVector.z;
  4005. this.w += otherVector.w;
  4006. return this;
  4007. };
  4008. /**
  4009. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  4010. * @param otherVector the vector to add
  4011. * @returns the resulting vector
  4012. */
  4013. Vector4.prototype.add = function (otherVector) {
  4014. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  4015. };
  4016. /**
  4017. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  4018. * @param otherVector the vector to add
  4019. * @param result the vector to store the result
  4020. * @returns the current Vector4.
  4021. */
  4022. Vector4.prototype.addToRef = function (otherVector, result) {
  4023. result.x = this.x + otherVector.x;
  4024. result.y = this.y + otherVector.y;
  4025. result.z = this.z + otherVector.z;
  4026. result.w = this.w + otherVector.w;
  4027. return this;
  4028. };
  4029. /**
  4030. * Subtract in place the given vector from the current Vector4.
  4031. * @param otherVector the vector to subtract
  4032. * @returns the updated Vector4.
  4033. */
  4034. Vector4.prototype.subtractInPlace = function (otherVector) {
  4035. this.x -= otherVector.x;
  4036. this.y -= otherVector.y;
  4037. this.z -= otherVector.z;
  4038. this.w -= otherVector.w;
  4039. return this;
  4040. };
  4041. /**
  4042. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4043. * @param otherVector the vector to add
  4044. * @returns the new vector with the result
  4045. */
  4046. Vector4.prototype.subtract = function (otherVector) {
  4047. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4048. };
  4049. /**
  4050. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4051. * @param otherVector the vector to subtract
  4052. * @param result the vector to store the result
  4053. * @returns the current Vector4.
  4054. */
  4055. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4056. result.x = this.x - otherVector.x;
  4057. result.y = this.y - otherVector.y;
  4058. result.z = this.z - otherVector.z;
  4059. result.w = this.w - otherVector.w;
  4060. return this;
  4061. };
  4062. /**
  4063. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4064. */
  4065. /**
  4066. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4067. * @param x value to subtract
  4068. * @param y value to subtract
  4069. * @param z value to subtract
  4070. * @param w value to subtract
  4071. * @returns new vector containing the result
  4072. */
  4073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4075. };
  4076. /**
  4077. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4078. * @param x value to subtract
  4079. * @param y value to subtract
  4080. * @param z value to subtract
  4081. * @param w value to subtract
  4082. * @param result the vector to store the result in
  4083. * @returns the current Vector4.
  4084. */
  4085. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4086. result.x = this.x - x;
  4087. result.y = this.y - y;
  4088. result.z = this.z - z;
  4089. result.w = this.w - w;
  4090. return this;
  4091. };
  4092. /**
  4093. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4094. * @returns a new vector with the negated values
  4095. */
  4096. Vector4.prototype.negate = function () {
  4097. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4098. };
  4099. /**
  4100. * Multiplies the current Vector4 coordinates by scale (float).
  4101. * @param scale the number to scale with
  4102. * @returns the updated Vector4.
  4103. */
  4104. Vector4.prototype.scaleInPlace = function (scale) {
  4105. this.x *= scale;
  4106. this.y *= scale;
  4107. this.z *= scale;
  4108. this.w *= scale;
  4109. return this;
  4110. };
  4111. /**
  4112. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4113. * @param scale the number to scale with
  4114. * @returns a new vector with the result
  4115. */
  4116. Vector4.prototype.scale = function (scale) {
  4117. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4118. };
  4119. /**
  4120. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4121. * @param scale the number to scale with
  4122. * @param result a vector to store the result in
  4123. * @returns the current Vector4.
  4124. */
  4125. Vector4.prototype.scaleToRef = function (scale, result) {
  4126. result.x = this.x * scale;
  4127. result.y = this.y * scale;
  4128. result.z = this.z * scale;
  4129. result.w = this.w * scale;
  4130. return this;
  4131. };
  4132. /**
  4133. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4134. * @param scale defines the scale factor
  4135. * @param result defines the Vector4 object where to store the result
  4136. * @returns the unmodified current Vector4
  4137. */
  4138. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4139. result.x += this.x * scale;
  4140. result.y += this.y * scale;
  4141. result.z += this.z * scale;
  4142. result.w += this.w * scale;
  4143. return this;
  4144. };
  4145. /**
  4146. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4147. * @param otherVector the vector to compare against
  4148. * @returns true if they are equal
  4149. */
  4150. Vector4.prototype.equals = function (otherVector) {
  4151. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4152. };
  4153. /**
  4154. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4155. * @param otherVector vector to compare against
  4156. * @param epsilon (Default: very small number)
  4157. * @returns true if they are equal
  4158. */
  4159. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4160. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4161. return otherVector
  4162. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4163. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4164. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4165. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4166. };
  4167. /**
  4168. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4169. * @param x x value to compare against
  4170. * @param y y value to compare against
  4171. * @param z z value to compare against
  4172. * @param w w value to compare against
  4173. * @returns true if equal
  4174. */
  4175. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4176. return this.x === x && this.y === y && this.z === z && this.w === w;
  4177. };
  4178. /**
  4179. * Multiplies in place the current Vector4 by the given one.
  4180. * @param otherVector vector to multiple with
  4181. * @returns the updated Vector4.
  4182. */
  4183. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4184. this.x *= otherVector.x;
  4185. this.y *= otherVector.y;
  4186. this.z *= otherVector.z;
  4187. this.w *= otherVector.w;
  4188. return this;
  4189. };
  4190. /**
  4191. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4192. * @param otherVector vector to multiple with
  4193. * @returns resulting new vector
  4194. */
  4195. Vector4.prototype.multiply = function (otherVector) {
  4196. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4197. };
  4198. /**
  4199. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4200. * @param otherVector vector to multiple with
  4201. * @param result vector to store the result
  4202. * @returns the current Vector4.
  4203. */
  4204. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4205. result.x = this.x * otherVector.x;
  4206. result.y = this.y * otherVector.y;
  4207. result.z = this.z * otherVector.z;
  4208. result.w = this.w * otherVector.w;
  4209. return this;
  4210. };
  4211. /**
  4212. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4213. * @param x x value multiply with
  4214. * @param y y value multiply with
  4215. * @param z z value multiply with
  4216. * @param w w value multiply with
  4217. * @returns resulting new vector
  4218. */
  4219. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4220. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4221. };
  4222. /**
  4223. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4224. * @param otherVector vector to devide with
  4225. * @returns resulting new vector
  4226. */
  4227. Vector4.prototype.divide = function (otherVector) {
  4228. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4229. };
  4230. /**
  4231. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4232. * @param otherVector vector to devide with
  4233. * @param result vector to store the result
  4234. * @returns the current Vector4.
  4235. */
  4236. Vector4.prototype.divideToRef = function (otherVector, result) {
  4237. result.x = this.x / otherVector.x;
  4238. result.y = this.y / otherVector.y;
  4239. result.z = this.z / otherVector.z;
  4240. result.w = this.w / otherVector.w;
  4241. return this;
  4242. };
  4243. /**
  4244. * Divides the current Vector3 coordinates by the given ones.
  4245. * @param otherVector vector to devide with
  4246. * @returns the updated Vector3.
  4247. */
  4248. Vector4.prototype.divideInPlace = function (otherVector) {
  4249. return this.divideToRef(otherVector, this);
  4250. };
  4251. /**
  4252. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4253. * @param other defines the second operand
  4254. * @returns the current updated Vector4
  4255. */
  4256. Vector4.prototype.minimizeInPlace = function (other) {
  4257. if (other.x < this.x)
  4258. this.x = other.x;
  4259. if (other.y < this.y)
  4260. this.y = other.y;
  4261. if (other.z < this.z)
  4262. this.z = other.z;
  4263. if (other.w < this.w)
  4264. this.w = other.w;
  4265. return this;
  4266. };
  4267. /**
  4268. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4269. * @param other defines the second operand
  4270. * @returns the current updated Vector4
  4271. */
  4272. Vector4.prototype.maximizeInPlace = function (other) {
  4273. if (other.x > this.x)
  4274. this.x = other.x;
  4275. if (other.y > this.y)
  4276. this.y = other.y;
  4277. if (other.z > this.z)
  4278. this.z = other.z;
  4279. if (other.w > this.w)
  4280. this.w = other.w;
  4281. return this;
  4282. };
  4283. /**
  4284. * Gets a new Vector4 from current Vector4 floored values
  4285. * @returns a new Vector4
  4286. */
  4287. Vector4.prototype.floor = function () {
  4288. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4289. };
  4290. /**
  4291. * Gets a new Vector4 from current Vector3 floored values
  4292. * @returns a new Vector4
  4293. */
  4294. Vector4.prototype.fract = function () {
  4295. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4296. };
  4297. // Properties
  4298. /**
  4299. * Returns the Vector4 length (float).
  4300. * @returns the length
  4301. */
  4302. Vector4.prototype.length = function () {
  4303. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4304. };
  4305. /**
  4306. * Returns the Vector4 squared length (float).
  4307. * @returns the length squared
  4308. */
  4309. Vector4.prototype.lengthSquared = function () {
  4310. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4311. };
  4312. // Methods
  4313. /**
  4314. * Normalizes in place the Vector4.
  4315. * @returns the updated Vector4.
  4316. */
  4317. Vector4.prototype.normalize = function () {
  4318. var len = this.length();
  4319. if (len === 0)
  4320. return this;
  4321. var num = 1.0 / len;
  4322. this.x *= num;
  4323. this.y *= num;
  4324. this.z *= num;
  4325. this.w *= num;
  4326. return this;
  4327. };
  4328. /**
  4329. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4330. * @returns this converted to a new vector3
  4331. */
  4332. Vector4.prototype.toVector3 = function () {
  4333. return new Vector3(this.x, this.y, this.z);
  4334. };
  4335. /**
  4336. * Returns a new Vector4 copied from the current one.
  4337. * @returns the new cloned vector
  4338. */
  4339. Vector4.prototype.clone = function () {
  4340. return new Vector4(this.x, this.y, this.z, this.w);
  4341. };
  4342. /**
  4343. * Updates the current Vector4 with the given one coordinates.
  4344. * @param source the source vector to copy from
  4345. * @returns the updated Vector4.
  4346. */
  4347. Vector4.prototype.copyFrom = function (source) {
  4348. this.x = source.x;
  4349. this.y = source.y;
  4350. this.z = source.z;
  4351. this.w = source.w;
  4352. return this;
  4353. };
  4354. /**
  4355. * Updates the current Vector4 coordinates with the given floats.
  4356. * @param x float to copy from
  4357. * @param y float to copy from
  4358. * @param z float to copy from
  4359. * @param w float to copy from
  4360. * @returns the updated Vector4.
  4361. */
  4362. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4363. this.x = x;
  4364. this.y = y;
  4365. this.z = z;
  4366. this.w = w;
  4367. return this;
  4368. };
  4369. /**
  4370. * Updates the current Vector4 coordinates with the given floats.
  4371. * @param x float to set from
  4372. * @param y float to set from
  4373. * @param z float to set from
  4374. * @param w float to set from
  4375. * @returns the updated Vector4.
  4376. */
  4377. Vector4.prototype.set = function (x, y, z, w) {
  4378. return this.copyFromFloats(x, y, z, w);
  4379. };
  4380. // Statics
  4381. /**
  4382. * Returns a new Vector4 set from the starting index of the given array.
  4383. * @param array the array to pull values from
  4384. * @param offset the offset into the array to start at
  4385. * @returns the new vector
  4386. */
  4387. Vector4.FromArray = function (array, offset) {
  4388. if (!offset) {
  4389. offset = 0;
  4390. }
  4391. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4392. };
  4393. /**
  4394. * Updates the given vector "result" from the starting index of the given array.
  4395. * @param array the array to pull values from
  4396. * @param offset the offset into the array to start at
  4397. * @param result the vector to store the result in
  4398. */
  4399. Vector4.FromArrayToRef = function (array, offset, result) {
  4400. result.x = array[offset];
  4401. result.y = array[offset + 1];
  4402. result.z = array[offset + 2];
  4403. result.w = array[offset + 3];
  4404. };
  4405. /**
  4406. * Updates the given vector "result" from the starting index of the given Float32Array.
  4407. * @param array the array to pull values from
  4408. * @param offset the offset into the array to start at
  4409. * @param result the vector to store the result in
  4410. */
  4411. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4412. Vector4.FromArrayToRef(array, offset, result);
  4413. };
  4414. /**
  4415. * Updates the given vector "result" coordinates from the given floats.
  4416. * @param x float to set from
  4417. * @param y float to set from
  4418. * @param z float to set from
  4419. * @param w float to set from
  4420. * @param result the vector to the floats in
  4421. */
  4422. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4423. result.x = x;
  4424. result.y = y;
  4425. result.z = z;
  4426. result.w = w;
  4427. };
  4428. /**
  4429. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4430. * @returns the new vector
  4431. */
  4432. Vector4.Zero = function () {
  4433. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4434. };
  4435. /**
  4436. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4437. * @returns the new vector
  4438. */
  4439. Vector4.One = function () {
  4440. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4441. };
  4442. /**
  4443. * Returns a new normalized Vector4 from the given one.
  4444. * @param vector the vector to normalize
  4445. * @returns the vector
  4446. */
  4447. Vector4.Normalize = function (vector) {
  4448. var result = Vector4.Zero();
  4449. Vector4.NormalizeToRef(vector, result);
  4450. return result;
  4451. };
  4452. /**
  4453. * Updates the given vector "result" from the normalization of the given one.
  4454. * @param vector the vector to normalize
  4455. * @param result the vector to store the result in
  4456. */
  4457. Vector4.NormalizeToRef = function (vector, result) {
  4458. result.copyFrom(vector);
  4459. result.normalize();
  4460. };
  4461. /**
  4462. * Returns a vector with the minimum values from the left and right vectors
  4463. * @param left left vector to minimize
  4464. * @param right right vector to minimize
  4465. * @returns a new vector with the minimum of the left and right vector values
  4466. */
  4467. Vector4.Minimize = function (left, right) {
  4468. var min = left.clone();
  4469. min.minimizeInPlace(right);
  4470. return min;
  4471. };
  4472. /**
  4473. * Returns a vector with the maximum values from the left and right vectors
  4474. * @param left left vector to maximize
  4475. * @param right right vector to maximize
  4476. * @returns a new vector with the maximum of the left and right vector values
  4477. */
  4478. Vector4.Maximize = function (left, right) {
  4479. var max = left.clone();
  4480. max.maximizeInPlace(right);
  4481. return max;
  4482. };
  4483. /**
  4484. * Returns the distance (float) between the vectors "value1" and "value2".
  4485. * @param value1 value to calulate the distance between
  4486. * @param value2 value to calulate the distance between
  4487. * @return the distance between the two vectors
  4488. */
  4489. Vector4.Distance = function (value1, value2) {
  4490. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4491. };
  4492. /**
  4493. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4494. * @param value1 value to calulate the distance between
  4495. * @param value2 value to calulate the distance between
  4496. * @return the distance between the two vectors squared
  4497. */
  4498. Vector4.DistanceSquared = function (value1, value2) {
  4499. var x = value1.x - value2.x;
  4500. var y = value1.y - value2.y;
  4501. var z = value1.z - value2.z;
  4502. var w = value1.w - value2.w;
  4503. return (x * x) + (y * y) + (z * z) + (w * w);
  4504. };
  4505. /**
  4506. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4507. * @param value1 value to calulate the center between
  4508. * @param value2 value to calulate the center between
  4509. * @return the center between the two vectors
  4510. */
  4511. Vector4.Center = function (value1, value2) {
  4512. var center = value1.add(value2);
  4513. center.scaleInPlace(0.5);
  4514. return center;
  4515. };
  4516. /**
  4517. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4518. * This methods computes transformed normalized direction vectors only.
  4519. * @param vector the vector to transform
  4520. * @param transformation the transformation matrix to apply
  4521. * @returns the new vector
  4522. */
  4523. Vector4.TransformNormal = function (vector, transformation) {
  4524. var result = Vector4.Zero();
  4525. Vector4.TransformNormalToRef(vector, transformation, result);
  4526. return result;
  4527. };
  4528. /**
  4529. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4530. * This methods computes transformed normalized direction vectors only.
  4531. * @param vector the vector to transform
  4532. * @param transformation the transformation matrix to apply
  4533. * @param result the vector to store the result in
  4534. */
  4535. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4536. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4537. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4538. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4539. result.x = x;
  4540. result.y = y;
  4541. result.z = z;
  4542. result.w = vector.w;
  4543. };
  4544. /**
  4545. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4546. * This methods computes transformed normalized direction vectors only.
  4547. * @param x value to transform
  4548. * @param y value to transform
  4549. * @param z value to transform
  4550. * @param w value to transform
  4551. * @param transformation the transformation matrix to apply
  4552. * @param result the vector to store the results in
  4553. */
  4554. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4555. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4556. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4557. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4558. result.w = w;
  4559. };
  4560. return Vector4;
  4561. }());
  4562. BABYLON.Vector4 = Vector4;
  4563. /**
  4564. * Size containing widht and height
  4565. */
  4566. var Size = /** @class */ (function () {
  4567. /**
  4568. * Creates a Size object from the given width and height (floats).
  4569. * @param width width of the new size
  4570. * @param height height of the new size
  4571. */
  4572. function Size(width, height) {
  4573. this.width = width;
  4574. this.height = height;
  4575. }
  4576. /**
  4577. * Returns a string with the Size width and height
  4578. * @returns a string with the Size width and height
  4579. */
  4580. Size.prototype.toString = function () {
  4581. return "{W: " + this.width + ", H: " + this.height + "}";
  4582. };
  4583. /**
  4584. * "Size"
  4585. * @returns the string "Size"
  4586. */
  4587. Size.prototype.getClassName = function () {
  4588. return "Size";
  4589. };
  4590. /**
  4591. * Returns the Size hash code.
  4592. * @returns a hash code for a unique width and height
  4593. */
  4594. Size.prototype.getHashCode = function () {
  4595. var hash = this.width || 0;
  4596. hash = (hash * 397) ^ (this.height || 0);
  4597. return hash;
  4598. };
  4599. /**
  4600. * Updates the current size from the given one.
  4601. * @param src the given size
  4602. */
  4603. Size.prototype.copyFrom = function (src) {
  4604. this.width = src.width;
  4605. this.height = src.height;
  4606. };
  4607. /**
  4608. * Updates in place the current Size from the given floats.
  4609. * @param width width of the new size
  4610. * @param height height of the new size
  4611. * @returns the updated Size.
  4612. */
  4613. Size.prototype.copyFromFloats = function (width, height) {
  4614. this.width = width;
  4615. this.height = height;
  4616. return this;
  4617. };
  4618. /**
  4619. * Updates in place the current Size from the given floats.
  4620. * @param width width to set
  4621. * @param height height to set
  4622. * @returns the updated Size.
  4623. */
  4624. Size.prototype.set = function (width, height) {
  4625. return this.copyFromFloats(width, height);
  4626. };
  4627. /**
  4628. * Multiplies the width and height by numbers
  4629. * @param w factor to multiple the width by
  4630. * @param h factor to multiple the height by
  4631. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4632. */
  4633. Size.prototype.multiplyByFloats = function (w, h) {
  4634. return new Size(this.width * w, this.height * h);
  4635. };
  4636. /**
  4637. * Clones the size
  4638. * @returns a new Size copied from the given one.
  4639. */
  4640. Size.prototype.clone = function () {
  4641. return new Size(this.width, this.height);
  4642. };
  4643. /**
  4644. * True if the current Size and the given one width and height are strictly equal.
  4645. * @param other the other size to compare against
  4646. * @returns True if the current Size and the given one width and height are strictly equal.
  4647. */
  4648. Size.prototype.equals = function (other) {
  4649. if (!other) {
  4650. return false;
  4651. }
  4652. return (this.width === other.width) && (this.height === other.height);
  4653. };
  4654. Object.defineProperty(Size.prototype, "surface", {
  4655. /**
  4656. * The surface of the Size : width * height (float).
  4657. */
  4658. get: function () {
  4659. return this.width * this.height;
  4660. },
  4661. enumerable: true,
  4662. configurable: true
  4663. });
  4664. /**
  4665. * Create a new size of zero
  4666. * @returns a new Size set to (0.0, 0.0)
  4667. */
  4668. Size.Zero = function () {
  4669. return new Size(0.0, 0.0);
  4670. };
  4671. /**
  4672. * Sums the width and height of two sizes
  4673. * @param otherSize size to add to this size
  4674. * @returns a new Size set as the addition result of the current Size and the given one.
  4675. */
  4676. Size.prototype.add = function (otherSize) {
  4677. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4678. return r;
  4679. };
  4680. /**
  4681. * Subtracts the width and height of two
  4682. * @param otherSize size to subtract to this size
  4683. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4684. */
  4685. Size.prototype.subtract = function (otherSize) {
  4686. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4687. return r;
  4688. };
  4689. /**
  4690. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4691. * @param start starting size to lerp between
  4692. * @param end end size to lerp between
  4693. * @param amount amount to lerp between the start and end values
  4694. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4695. */
  4696. Size.Lerp = function (start, end, amount) {
  4697. var w = start.width + ((end.width - start.width) * amount);
  4698. var h = start.height + ((end.height - start.height) * amount);
  4699. return new Size(w, h);
  4700. };
  4701. return Size;
  4702. }());
  4703. BABYLON.Size = Size;
  4704. /**
  4705. * Class used to store quaternion data
  4706. * @see https://en.wikipedia.org/wiki/Quaternion
  4707. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4708. */
  4709. var Quaternion = /** @class */ (function () {
  4710. /**
  4711. * Creates a new Quaternion from the given floats
  4712. * @param x defines the first component (0 by default)
  4713. * @param y defines the second component (0 by default)
  4714. * @param z defines the third component (0 by default)
  4715. * @param w defines the fourth component (1.0 by default)
  4716. */
  4717. function Quaternion(
  4718. /** defines the first component (0 by default) */
  4719. x,
  4720. /** defines the second component (0 by default) */
  4721. y,
  4722. /** defines the third component (0 by default) */
  4723. z,
  4724. /** defines the fourth component (1.0 by default) */
  4725. w) {
  4726. if (x === void 0) { x = 0.0; }
  4727. if (y === void 0) { y = 0.0; }
  4728. if (z === void 0) { z = 0.0; }
  4729. if (w === void 0) { w = 1.0; }
  4730. this.x = x;
  4731. this.y = y;
  4732. this.z = z;
  4733. this.w = w;
  4734. }
  4735. /**
  4736. * Gets a string representation for the current quaternion
  4737. * @returns a string with the Quaternion coordinates
  4738. */
  4739. Quaternion.prototype.toString = function () {
  4740. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4741. };
  4742. /**
  4743. * Gets the class name of the quaternion
  4744. * @returns the string "Quaternion"
  4745. */
  4746. Quaternion.prototype.getClassName = function () {
  4747. return "Quaternion";
  4748. };
  4749. /**
  4750. * Gets a hash code for this quaternion
  4751. * @returns the quaternion hash code
  4752. */
  4753. Quaternion.prototype.getHashCode = function () {
  4754. var hash = this.x || 0;
  4755. hash = (hash * 397) ^ (this.y || 0);
  4756. hash = (hash * 397) ^ (this.z || 0);
  4757. hash = (hash * 397) ^ (this.w || 0);
  4758. return hash;
  4759. };
  4760. /**
  4761. * Copy the quaternion to an array
  4762. * @returns a new array populated with 4 elements from the quaternion coordinates
  4763. */
  4764. Quaternion.prototype.asArray = function () {
  4765. return [this.x, this.y, this.z, this.w];
  4766. };
  4767. /**
  4768. * Check if two quaternions are equals
  4769. * @param otherQuaternion defines the second operand
  4770. * @return true if the current quaternion and the given one coordinates are strictly equals
  4771. */
  4772. Quaternion.prototype.equals = function (otherQuaternion) {
  4773. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4774. };
  4775. /**
  4776. * Clone the current quaternion
  4777. * @returns a new quaternion copied from the current one
  4778. */
  4779. Quaternion.prototype.clone = function () {
  4780. return new Quaternion(this.x, this.y, this.z, this.w);
  4781. };
  4782. /**
  4783. * Copy a quaternion to the current one
  4784. * @param other defines the other quaternion
  4785. * @returns the updated current quaternion
  4786. */
  4787. Quaternion.prototype.copyFrom = function (other) {
  4788. this.x = other.x;
  4789. this.y = other.y;
  4790. this.z = other.z;
  4791. this.w = other.w;
  4792. return this;
  4793. };
  4794. /**
  4795. * Updates the current quaternion with the given float coordinates
  4796. * @param x defines the x coordinate
  4797. * @param y defines the y coordinate
  4798. * @param z defines the z coordinate
  4799. * @param w defines the w coordinate
  4800. * @returns the updated current quaternion
  4801. */
  4802. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4803. this.x = x;
  4804. this.y = y;
  4805. this.z = z;
  4806. this.w = w;
  4807. return this;
  4808. };
  4809. /**
  4810. * Updates the current quaternion from the given float coordinates
  4811. * @param x defines the x coordinate
  4812. * @param y defines the y coordinate
  4813. * @param z defines the z coordinate
  4814. * @param w defines the w coordinate
  4815. * @returns the updated current quaternion
  4816. */
  4817. Quaternion.prototype.set = function (x, y, z, w) {
  4818. return this.copyFromFloats(x, y, z, w);
  4819. };
  4820. /**
  4821. * Adds two quaternions
  4822. * @param other defines the second operand
  4823. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4824. */
  4825. Quaternion.prototype.add = function (other) {
  4826. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4827. };
  4828. /**
  4829. * Add a quaternion to the current one
  4830. * @param other defines the quaternion to add
  4831. * @returns the current quaternion
  4832. */
  4833. Quaternion.prototype.addInPlace = function (other) {
  4834. this.x += other.x;
  4835. this.y += other.y;
  4836. this.z += other.z;
  4837. this.w += other.w;
  4838. return this;
  4839. };
  4840. /**
  4841. * Subtract two quaternions
  4842. * @param other defines the second operand
  4843. * @returns a new quaternion as the subtraction result of the given one from the current one
  4844. */
  4845. Quaternion.prototype.subtract = function (other) {
  4846. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4847. };
  4848. /**
  4849. * Multiplies the current quaternion by a scale factor
  4850. * @param value defines the scale factor
  4851. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4852. */
  4853. Quaternion.prototype.scale = function (value) {
  4854. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4855. };
  4856. /**
  4857. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4858. * @param scale defines the scale factor
  4859. * @param result defines the Quaternion object where to store the result
  4860. * @returns the unmodified current quaternion
  4861. */
  4862. Quaternion.prototype.scaleToRef = function (scale, result) {
  4863. result.x = this.x * scale;
  4864. result.y = this.y * scale;
  4865. result.z = this.z * scale;
  4866. result.w = this.w * scale;
  4867. return this;
  4868. };
  4869. /**
  4870. * Multiplies in place the current quaternion by a scale factor
  4871. * @param value defines the scale factor
  4872. * @returns the current modified quaternion
  4873. */
  4874. Quaternion.prototype.scaleInPlace = function (value) {
  4875. this.x *= value;
  4876. this.y *= value;
  4877. this.z *= value;
  4878. this.w *= value;
  4879. return this;
  4880. };
  4881. /**
  4882. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4883. * @param scale defines the scale factor
  4884. * @param result defines the Quaternion object where to store the result
  4885. * @returns the unmodified current quaternion
  4886. */
  4887. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4888. result.x += this.x * scale;
  4889. result.y += this.y * scale;
  4890. result.z += this.z * scale;
  4891. result.w += this.w * scale;
  4892. return this;
  4893. };
  4894. /**
  4895. * Multiplies two quaternions
  4896. * @param q1 defines the second operand
  4897. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4898. */
  4899. Quaternion.prototype.multiply = function (q1) {
  4900. var result = new Quaternion(0, 0, 0, 1.0);
  4901. this.multiplyToRef(q1, result);
  4902. return result;
  4903. };
  4904. /**
  4905. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4906. * @param q1 defines the second operand
  4907. * @param result defines the target quaternion
  4908. * @returns the current quaternion
  4909. */
  4910. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4911. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4912. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4913. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4914. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4915. result.copyFromFloats(x, y, z, w);
  4916. return this;
  4917. };
  4918. /**
  4919. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4920. * @param q1 defines the second operand
  4921. * @returns the currentupdated quaternion
  4922. */
  4923. Quaternion.prototype.multiplyInPlace = function (q1) {
  4924. this.multiplyToRef(q1, this);
  4925. return this;
  4926. };
  4927. /**
  4928. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4929. * @param ref defines the target quaternion
  4930. * @returns the current quaternion
  4931. */
  4932. Quaternion.prototype.conjugateToRef = function (ref) {
  4933. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4934. return this;
  4935. };
  4936. /**
  4937. * Conjugates in place (1-q) the current quaternion
  4938. * @returns the current updated quaternion
  4939. */
  4940. Quaternion.prototype.conjugateInPlace = function () {
  4941. this.x *= -1;
  4942. this.y *= -1;
  4943. this.z *= -1;
  4944. return this;
  4945. };
  4946. /**
  4947. * Conjugates in place (1-q) the current quaternion
  4948. * @returns a new quaternion
  4949. */
  4950. Quaternion.prototype.conjugate = function () {
  4951. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4952. return result;
  4953. };
  4954. /**
  4955. * Gets length of current quaternion
  4956. * @returns the quaternion length (float)
  4957. */
  4958. Quaternion.prototype.length = function () {
  4959. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4960. };
  4961. /**
  4962. * Normalize in place the current quaternion
  4963. * @returns the current updated quaternion
  4964. */
  4965. Quaternion.prototype.normalize = function () {
  4966. var length = 1.0 / this.length();
  4967. this.x *= length;
  4968. this.y *= length;
  4969. this.z *= length;
  4970. this.w *= length;
  4971. return this;
  4972. };
  4973. /**
  4974. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4975. * @param order is a reserved parameter and is ignore for now
  4976. * @returns a new Vector3 containing the Euler angles
  4977. */
  4978. Quaternion.prototype.toEulerAngles = function (order) {
  4979. if (order === void 0) { order = "YZX"; }
  4980. var result = Vector3.Zero();
  4981. this.toEulerAnglesToRef(result, order);
  4982. return result;
  4983. };
  4984. /**
  4985. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4986. * @param result defines the vector which will be filled with the Euler angles
  4987. * @param order is a reserved parameter and is ignore for now
  4988. * @returns the current unchanged quaternion
  4989. */
  4990. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4991. if (order === void 0) { order = "YZX"; }
  4992. var qz = this.z;
  4993. var qx = this.x;
  4994. var qy = this.y;
  4995. var qw = this.w;
  4996. var sqw = qw * qw;
  4997. var sqz = qz * qz;
  4998. var sqx = qx * qx;
  4999. var sqy = qy * qy;
  5000. var zAxisY = qy * qz - qx * qw;
  5001. var limit = .4999999;
  5002. if (zAxisY < -limit) {
  5003. result.y = 2 * Math.atan2(qy, qw);
  5004. result.x = Math.PI / 2;
  5005. result.z = 0;
  5006. }
  5007. else if (zAxisY > limit) {
  5008. result.y = 2 * Math.atan2(qy, qw);
  5009. result.x = -Math.PI / 2;
  5010. result.z = 0;
  5011. }
  5012. else {
  5013. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  5014. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  5015. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  5016. }
  5017. return this;
  5018. };
  5019. /**
  5020. * Updates the given rotation matrix with the current quaternion values
  5021. * @param result defines the target matrix
  5022. * @returns the current unchanged quaternion
  5023. */
  5024. Quaternion.prototype.toRotationMatrix = function (result) {
  5025. var xx = this.x * this.x;
  5026. var yy = this.y * this.y;
  5027. var zz = this.z * this.z;
  5028. var xy = this.x * this.y;
  5029. var zw = this.z * this.w;
  5030. var zx = this.z * this.x;
  5031. var yw = this.y * this.w;
  5032. var yz = this.y * this.z;
  5033. var xw = this.x * this.w;
  5034. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5035. result.m[1] = 2.0 * (xy + zw);
  5036. result.m[2] = 2.0 * (zx - yw);
  5037. result.m[3] = 0;
  5038. result.m[4] = 2.0 * (xy - zw);
  5039. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5040. result.m[6] = 2.0 * (yz + xw);
  5041. result.m[7] = 0;
  5042. result.m[8] = 2.0 * (zx + yw);
  5043. result.m[9] = 2.0 * (yz - xw);
  5044. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5045. result.m[11] = 0;
  5046. result.m[12] = 0;
  5047. result.m[13] = 0;
  5048. result.m[14] = 0;
  5049. result.m[15] = 1.0;
  5050. result._markAsUpdated();
  5051. return this;
  5052. };
  5053. /**
  5054. * Updates the current quaternion from the given rotation matrix values
  5055. * @param matrix defines the source matrix
  5056. * @returns the current updated quaternion
  5057. */
  5058. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5059. Quaternion.FromRotationMatrixToRef(matrix, this);
  5060. return this;
  5061. };
  5062. // Statics
  5063. /**
  5064. * Creates a new quaternion from a rotation matrix
  5065. * @param matrix defines the source matrix
  5066. * @returns a new quaternion created from the given rotation matrix values
  5067. */
  5068. Quaternion.FromRotationMatrix = function (matrix) {
  5069. var result = new Quaternion();
  5070. Quaternion.FromRotationMatrixToRef(matrix, result);
  5071. return result;
  5072. };
  5073. /**
  5074. * Updates the given quaternion with the given rotation matrix values
  5075. * @param matrix defines the source matrix
  5076. * @param result defines the target quaternion
  5077. */
  5078. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5079. var data = matrix.m;
  5080. var m11 = data[0], m12 = data[4], m13 = data[8];
  5081. var m21 = data[1], m22 = data[5], m23 = data[9];
  5082. var m31 = data[2], m32 = data[6], m33 = data[10];
  5083. var trace = m11 + m22 + m33;
  5084. var s;
  5085. if (trace > 0) {
  5086. s = 0.5 / Math.sqrt(trace + 1.0);
  5087. result.w = 0.25 / s;
  5088. result.x = (m32 - m23) * s;
  5089. result.y = (m13 - m31) * s;
  5090. result.z = (m21 - m12) * s;
  5091. }
  5092. else if (m11 > m22 && m11 > m33) {
  5093. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5094. result.w = (m32 - m23) / s;
  5095. result.x = 0.25 * s;
  5096. result.y = (m12 + m21) / s;
  5097. result.z = (m13 + m31) / s;
  5098. }
  5099. else if (m22 > m33) {
  5100. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5101. result.w = (m13 - m31) / s;
  5102. result.x = (m12 + m21) / s;
  5103. result.y = 0.25 * s;
  5104. result.z = (m23 + m32) / s;
  5105. }
  5106. else {
  5107. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5108. result.w = (m21 - m12) / s;
  5109. result.x = (m13 + m31) / s;
  5110. result.y = (m23 + m32) / s;
  5111. result.z = 0.25 * s;
  5112. }
  5113. };
  5114. /**
  5115. * Returns the dot product (float) between the quaternions "left" and "right"
  5116. * @param left defines the left operand
  5117. * @param right defines the right operand
  5118. * @returns the dot product
  5119. */
  5120. Quaternion.Dot = function (left, right) {
  5121. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5122. };
  5123. /**
  5124. * Checks if the two quaternions are close to each other
  5125. * @param quat0 defines the first quaternion to check
  5126. * @param quat1 defines the second quaternion to check
  5127. * @returns true if the two quaternions are close to each other
  5128. */
  5129. Quaternion.AreClose = function (quat0, quat1) {
  5130. var dot = Quaternion.Dot(quat0, quat1);
  5131. return dot >= 0;
  5132. };
  5133. /**
  5134. * Creates an empty quaternion
  5135. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5136. */
  5137. Quaternion.Zero = function () {
  5138. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5139. };
  5140. /**
  5141. * Inverse a given quaternion
  5142. * @param q defines the source quaternion
  5143. * @returns a new quaternion as the inverted current quaternion
  5144. */
  5145. Quaternion.Inverse = function (q) {
  5146. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5147. };
  5148. /**
  5149. * Creates an identity quaternion
  5150. * @returns the identity quaternion
  5151. */
  5152. Quaternion.Identity = function () {
  5153. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5154. };
  5155. /**
  5156. * Gets a boolean indicating if the given quaternion is identity
  5157. * @param quaternion defines the quaternion to check
  5158. * @returns true if the quaternion is identity
  5159. */
  5160. Quaternion.IsIdentity = function (quaternion) {
  5161. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5162. };
  5163. /**
  5164. * Creates a quaternion from a rotation around an axis
  5165. * @param axis defines the axis to use
  5166. * @param angle defines the angle to use
  5167. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5168. */
  5169. Quaternion.RotationAxis = function (axis, angle) {
  5170. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5171. };
  5172. /**
  5173. * Creates a rotation around an axis and stores it into the given quaternion
  5174. * @param axis defines the axis to use
  5175. * @param angle defines the angle to use
  5176. * @param result defines the target quaternion
  5177. * @returns the target quaternion
  5178. */
  5179. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5180. var sin = Math.sin(angle / 2);
  5181. axis.normalize();
  5182. result.w = Math.cos(angle / 2);
  5183. result.x = axis.x * sin;
  5184. result.y = axis.y * sin;
  5185. result.z = axis.z * sin;
  5186. return result;
  5187. };
  5188. /**
  5189. * Creates a new quaternion from data stored into an array
  5190. * @param array defines the data source
  5191. * @param offset defines the offset in the source array where the data starts
  5192. * @returns a new quaternion
  5193. */
  5194. Quaternion.FromArray = function (array, offset) {
  5195. if (!offset) {
  5196. offset = 0;
  5197. }
  5198. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5199. };
  5200. /**
  5201. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5202. * @param yaw defines the rotation around Y axis
  5203. * @param pitch defines the rotation around X axis
  5204. * @param roll defines the rotation around Z axis
  5205. * @returns the new quaternion
  5206. */
  5207. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5208. var q = new Quaternion();
  5209. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5210. return q;
  5211. };
  5212. /**
  5213. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5214. * @param yaw defines the rotation around Y axis
  5215. * @param pitch defines the rotation around X axis
  5216. * @param roll defines the rotation around Z axis
  5217. * @param result defines the target quaternion
  5218. */
  5219. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5220. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5221. var halfRoll = roll * 0.5;
  5222. var halfPitch = pitch * 0.5;
  5223. var halfYaw = yaw * 0.5;
  5224. var sinRoll = Math.sin(halfRoll);
  5225. var cosRoll = Math.cos(halfRoll);
  5226. var sinPitch = Math.sin(halfPitch);
  5227. var cosPitch = Math.cos(halfPitch);
  5228. var sinYaw = Math.sin(halfYaw);
  5229. var cosYaw = Math.cos(halfYaw);
  5230. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5231. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5232. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5233. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5234. };
  5235. /**
  5236. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5237. * @param alpha defines the rotation around first axis
  5238. * @param beta defines the rotation around second axis
  5239. * @param gamma defines the rotation around third axis
  5240. * @returns the new quaternion
  5241. */
  5242. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5243. var result = new Quaternion();
  5244. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5245. return result;
  5246. };
  5247. /**
  5248. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5249. * @param alpha defines the rotation around first axis
  5250. * @param beta defines the rotation around second axis
  5251. * @param gamma defines the rotation around third axis
  5252. * @param result defines the target quaternion
  5253. */
  5254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5255. // Produces a quaternion from Euler angles in the z-x-z orientation
  5256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5258. var halfBeta = beta * 0.5;
  5259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5263. };
  5264. /**
  5265. * 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)
  5266. * @param axis1 defines the first axis
  5267. * @param axis2 defines the second axis
  5268. * @param axis3 defines the third axis
  5269. * @returns the new quaternion
  5270. */
  5271. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5272. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5273. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5274. return quat;
  5275. };
  5276. /**
  5277. * 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
  5278. * @param axis1 defines the first axis
  5279. * @param axis2 defines the second axis
  5280. * @param axis3 defines the third axis
  5281. * @param ref defines the target quaternion
  5282. */
  5283. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5284. var rotMat = MathTmp.Matrix[0];
  5285. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5286. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5287. };
  5288. /**
  5289. * Interpolates between two quaternions
  5290. * @param left defines first quaternion
  5291. * @param right defines second quaternion
  5292. * @param amount defines the gradient to use
  5293. * @returns the new interpolated quaternion
  5294. */
  5295. Quaternion.Slerp = function (left, right, amount) {
  5296. var result = Quaternion.Identity();
  5297. Quaternion.SlerpToRef(left, right, amount, result);
  5298. return result;
  5299. };
  5300. /**
  5301. * Interpolates between two quaternions and stores it into a target quaternion
  5302. * @param left defines first quaternion
  5303. * @param right defines second quaternion
  5304. * @param amount defines the gradient to use
  5305. * @param result defines the target quaternion
  5306. */
  5307. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5308. var num2;
  5309. var num3;
  5310. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5311. var flag = false;
  5312. if (num4 < 0) {
  5313. flag = true;
  5314. num4 = -num4;
  5315. }
  5316. if (num4 > 0.999999) {
  5317. num3 = 1 - amount;
  5318. num2 = flag ? -amount : amount;
  5319. }
  5320. else {
  5321. var num5 = Math.acos(num4);
  5322. var num6 = (1.0 / Math.sin(num5));
  5323. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5324. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5325. }
  5326. result.x = (num3 * left.x) + (num2 * right.x);
  5327. result.y = (num3 * left.y) + (num2 * right.y);
  5328. result.z = (num3 * left.z) + (num2 * right.z);
  5329. result.w = (num3 * left.w) + (num2 * right.w);
  5330. };
  5331. /**
  5332. * Interpolate between two quaternions using Hermite interpolation
  5333. * @param value1 defines first quaternion
  5334. * @param tangent1 defines the incoming tangent
  5335. * @param value2 defines second quaternion
  5336. * @param tangent2 defines the outgoing tangent
  5337. * @param amount defines the target quaternion
  5338. * @returns the new interpolated quaternion
  5339. */
  5340. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5341. var squared = amount * amount;
  5342. var cubed = amount * squared;
  5343. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5344. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5345. var part3 = (cubed - (2.0 * squared)) + amount;
  5346. var part4 = cubed - squared;
  5347. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5348. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5349. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5350. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5351. return new Quaternion(x, y, z, w);
  5352. };
  5353. return Quaternion;
  5354. }());
  5355. BABYLON.Quaternion = Quaternion;
  5356. /**
  5357. * Class used to store matrix data (4x4)
  5358. */
  5359. var Matrix = /** @class */ (function () {
  5360. /**
  5361. * Creates an empty matrix (filled with zeros)
  5362. */
  5363. function Matrix() {
  5364. this._isIdentity = false;
  5365. this._isIdentityDirty = true;
  5366. /**
  5367. * Gets or sets the internal data of the matrix
  5368. */
  5369. this.m = new Float32Array(16);
  5370. this._markAsUpdated();
  5371. }
  5372. /** @hidden */
  5373. Matrix.prototype._markAsUpdated = function () {
  5374. this.updateFlag = Matrix._updateFlagSeed++;
  5375. this._isIdentityDirty = true;
  5376. };
  5377. // Properties
  5378. /**
  5379. * Check if the current matrix is indentity
  5380. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5381. * @returns true is the matrix is the identity matrix
  5382. */
  5383. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5384. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5385. if (this._isIdentityDirty) {
  5386. this._isIdentityDirty = false;
  5387. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5388. this._isIdentity = false;
  5389. }
  5390. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5391. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5392. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5393. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5394. this._isIdentity = false;
  5395. }
  5396. else {
  5397. this._isIdentity = true;
  5398. }
  5399. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5400. this._isIdentity = false;
  5401. }
  5402. }
  5403. return this._isIdentity;
  5404. };
  5405. /**
  5406. * Gets the determinant of the matrix
  5407. * @returns the matrix determinant
  5408. */
  5409. Matrix.prototype.determinant = function () {
  5410. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5411. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5412. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5413. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5414. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5415. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5416. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5417. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5418. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5419. };
  5420. // Methods
  5421. /**
  5422. * Returns the matrix as a Float32Array
  5423. * @returns the matrix underlying array
  5424. */
  5425. Matrix.prototype.toArray = function () {
  5426. return this.m;
  5427. };
  5428. /**
  5429. * Returns the matrix as a Float32Array
  5430. * @returns the matrix underlying array.
  5431. */
  5432. Matrix.prototype.asArray = function () {
  5433. return this.toArray();
  5434. };
  5435. /**
  5436. * Inverts the current matrix in place
  5437. * @returns the current inverted matrix
  5438. */
  5439. Matrix.prototype.invert = function () {
  5440. this.invertToRef(this);
  5441. return this;
  5442. };
  5443. /**
  5444. * Sets all the matrix elements to zero
  5445. * @returns the current matrix
  5446. */
  5447. Matrix.prototype.reset = function () {
  5448. for (var index = 0; index < 16; index++) {
  5449. this.m[index] = 0.0;
  5450. }
  5451. this._markAsUpdated();
  5452. return this;
  5453. };
  5454. /**
  5455. * Adds the current matrix with a second one
  5456. * @param other defines the matrix to add
  5457. * @returns a new matrix as the addition of the current matrix and the given one
  5458. */
  5459. Matrix.prototype.add = function (other) {
  5460. var result = new Matrix();
  5461. this.addToRef(other, result);
  5462. return result;
  5463. };
  5464. /**
  5465. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5466. * @param other defines the matrix to add
  5467. * @param result defines the target matrix
  5468. * @returns the current matrix
  5469. */
  5470. Matrix.prototype.addToRef = function (other, result) {
  5471. for (var index = 0; index < 16; index++) {
  5472. result.m[index] = this.m[index] + other.m[index];
  5473. }
  5474. result._markAsUpdated();
  5475. return this;
  5476. };
  5477. /**
  5478. * Adds in place the given matrix to the current matrix
  5479. * @param other defines the second operand
  5480. * @returns the current updated matrix
  5481. */
  5482. Matrix.prototype.addToSelf = function (other) {
  5483. for (var index = 0; index < 16; index++) {
  5484. this.m[index] += other.m[index];
  5485. }
  5486. this._markAsUpdated();
  5487. return this;
  5488. };
  5489. /**
  5490. * Sets the given matrix to the current inverted Matrix
  5491. * @param other defines the target matrix
  5492. * @returns the unmodified current matrix
  5493. */
  5494. Matrix.prototype.invertToRef = function (other) {
  5495. var l1 = this.m[0];
  5496. var l2 = this.m[1];
  5497. var l3 = this.m[2];
  5498. var l4 = this.m[3];
  5499. var l5 = this.m[4];
  5500. var l6 = this.m[5];
  5501. var l7 = this.m[6];
  5502. var l8 = this.m[7];
  5503. var l9 = this.m[8];
  5504. var l10 = this.m[9];
  5505. var l11 = this.m[10];
  5506. var l12 = this.m[11];
  5507. var l13 = this.m[12];
  5508. var l14 = this.m[13];
  5509. var l15 = this.m[14];
  5510. var l16 = this.m[15];
  5511. var l17 = (l11 * l16) - (l12 * l15);
  5512. var l18 = (l10 * l16) - (l12 * l14);
  5513. var l19 = (l10 * l15) - (l11 * l14);
  5514. var l20 = (l9 * l16) - (l12 * l13);
  5515. var l21 = (l9 * l15) - (l11 * l13);
  5516. var l22 = (l9 * l14) - (l10 * l13);
  5517. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5518. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5519. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5520. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5521. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5522. var l28 = (l7 * l16) - (l8 * l15);
  5523. var l29 = (l6 * l16) - (l8 * l14);
  5524. var l30 = (l6 * l15) - (l7 * l14);
  5525. var l31 = (l5 * l16) - (l8 * l13);
  5526. var l32 = (l5 * l15) - (l7 * l13);
  5527. var l33 = (l5 * l14) - (l6 * l13);
  5528. var l34 = (l7 * l12) - (l8 * l11);
  5529. var l35 = (l6 * l12) - (l8 * l10);
  5530. var l36 = (l6 * l11) - (l7 * l10);
  5531. var l37 = (l5 * l12) - (l8 * l9);
  5532. var l38 = (l5 * l11) - (l7 * l9);
  5533. var l39 = (l5 * l10) - (l6 * l9);
  5534. other.m[0] = l23 * l27;
  5535. other.m[4] = l24 * l27;
  5536. other.m[8] = l25 * l27;
  5537. other.m[12] = l26 * l27;
  5538. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5539. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5540. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5541. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5542. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5543. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5544. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5545. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5546. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5547. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5548. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5549. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5550. other._markAsUpdated();
  5551. return this;
  5552. };
  5553. /**
  5554. * Inserts the translation vector (using 3 floats) in the current matrix
  5555. * @param x defines the 1st component of the translation
  5556. * @param y defines the 2nd component of the translation
  5557. * @param z defines the 3rd component of the translation
  5558. * @returns the current updated matrix
  5559. */
  5560. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5561. this.m[12] = x;
  5562. this.m[13] = y;
  5563. this.m[14] = z;
  5564. this._markAsUpdated();
  5565. return this;
  5566. };
  5567. /**
  5568. * Inserts the translation vector in the current matrix
  5569. * @param vector3 defines the translation to insert
  5570. * @returns the current updated matrix
  5571. */
  5572. Matrix.prototype.setTranslation = function (vector3) {
  5573. this.m[12] = vector3.x;
  5574. this.m[13] = vector3.y;
  5575. this.m[14] = vector3.z;
  5576. this._markAsUpdated();
  5577. return this;
  5578. };
  5579. /**
  5580. * Gets the translation value of the current matrix
  5581. * @returns a new Vector3 as the extracted translation from the matrix
  5582. */
  5583. Matrix.prototype.getTranslation = function () {
  5584. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5585. };
  5586. /**
  5587. * Fill a Vector3 with the extracted translation from the matrix
  5588. * @param result defines the Vector3 where to store the translation
  5589. * @returns the current matrix
  5590. */
  5591. Matrix.prototype.getTranslationToRef = function (result) {
  5592. result.x = this.m[12];
  5593. result.y = this.m[13];
  5594. result.z = this.m[14];
  5595. return this;
  5596. };
  5597. /**
  5598. * Remove rotation and scaling part from the matrix
  5599. * @returns the updated matrix
  5600. */
  5601. Matrix.prototype.removeRotationAndScaling = function () {
  5602. this.setRowFromFloats(0, 1, 0, 0, 0);
  5603. this.setRowFromFloats(1, 0, 1, 0, 0);
  5604. this.setRowFromFloats(2, 0, 0, 1, 0);
  5605. return this;
  5606. };
  5607. /**
  5608. * Multiply two matrices
  5609. * @param other defines the second operand
  5610. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5611. */
  5612. Matrix.prototype.multiply = function (other) {
  5613. var result = new Matrix();
  5614. this.multiplyToRef(other, result);
  5615. return result;
  5616. };
  5617. /**
  5618. * Copy the current matrix from the given one
  5619. * @param other defines the source matrix
  5620. * @returns the current updated matrix
  5621. */
  5622. Matrix.prototype.copyFrom = function (other) {
  5623. for (var index = 0; index < 16; index++) {
  5624. this.m[index] = other.m[index];
  5625. }
  5626. this._markAsUpdated();
  5627. return this;
  5628. };
  5629. /**
  5630. * Populates the given array from the starting index with the current matrix values
  5631. * @param array defines the target array
  5632. * @param offset defines the offset in the target array where to start storing values
  5633. * @returns the current matrix
  5634. */
  5635. Matrix.prototype.copyToArray = function (array, offset) {
  5636. if (offset === void 0) { offset = 0; }
  5637. for (var index = 0; index < 16; index++) {
  5638. array[offset + index] = this.m[index];
  5639. }
  5640. return this;
  5641. };
  5642. /**
  5643. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5644. * @param other defines the second operand
  5645. * @param result defines the matrix where to store the multiplication
  5646. * @returns the current matrix
  5647. */
  5648. Matrix.prototype.multiplyToRef = function (other, result) {
  5649. this.multiplyToArray(other, result.m, 0);
  5650. result._markAsUpdated();
  5651. return this;
  5652. };
  5653. /**
  5654. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5655. * @param other defines the second operand
  5656. * @param result defines the array where to store the multiplication
  5657. * @param offset defines the offset in the target array where to start storing values
  5658. * @returns the current matrix
  5659. */
  5660. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5661. var tm0 = this.m[0];
  5662. var tm1 = this.m[1];
  5663. var tm2 = this.m[2];
  5664. var tm3 = this.m[3];
  5665. var tm4 = this.m[4];
  5666. var tm5 = this.m[5];
  5667. var tm6 = this.m[6];
  5668. var tm7 = this.m[7];
  5669. var tm8 = this.m[8];
  5670. var tm9 = this.m[9];
  5671. var tm10 = this.m[10];
  5672. var tm11 = this.m[11];
  5673. var tm12 = this.m[12];
  5674. var tm13 = this.m[13];
  5675. var tm14 = this.m[14];
  5676. var tm15 = this.m[15];
  5677. var om0 = other.m[0];
  5678. var om1 = other.m[1];
  5679. var om2 = other.m[2];
  5680. var om3 = other.m[3];
  5681. var om4 = other.m[4];
  5682. var om5 = other.m[5];
  5683. var om6 = other.m[6];
  5684. var om7 = other.m[7];
  5685. var om8 = other.m[8];
  5686. var om9 = other.m[9];
  5687. var om10 = other.m[10];
  5688. var om11 = other.m[11];
  5689. var om12 = other.m[12];
  5690. var om13 = other.m[13];
  5691. var om14 = other.m[14];
  5692. var om15 = other.m[15];
  5693. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5694. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5695. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5696. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5697. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5698. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5699. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5700. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5701. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5702. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5703. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5704. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5705. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5706. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5707. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5708. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5709. return this;
  5710. };
  5711. /**
  5712. * Check equality between this matrix and a second one
  5713. * @param value defines the second matrix to compare
  5714. * @returns true is the current matrix and the given one values are strictly equal
  5715. */
  5716. Matrix.prototype.equals = function (value) {
  5717. return value &&
  5718. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5719. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5720. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5721. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5722. };
  5723. /**
  5724. * Clone the current matrix
  5725. * @returns a new matrix from the current matrix
  5726. */
  5727. Matrix.prototype.clone = function () {
  5728. 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]);
  5729. };
  5730. /**
  5731. * Returns the name of the current matrix class
  5732. * @returns the string "Matrix"
  5733. */
  5734. Matrix.prototype.getClassName = function () {
  5735. return "Matrix";
  5736. };
  5737. /**
  5738. * Gets the hash code of the current matrix
  5739. * @returns the hash code
  5740. */
  5741. Matrix.prototype.getHashCode = function () {
  5742. var hash = this.m[0] || 0;
  5743. for (var i = 1; i < 16; i++) {
  5744. hash = (hash * 397) ^ (this.m[i] || 0);
  5745. }
  5746. return hash;
  5747. };
  5748. /**
  5749. * Decomposes the current Matrix into a translation, rotation and scaling components
  5750. * @param scale defines the scale vector3 given as a reference to update
  5751. * @param rotation defines the rotation quaternion given as a reference to update
  5752. * @param translation defines the translation vector3 given as a reference to update
  5753. * @returns true if operation was successful
  5754. */
  5755. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5756. if (translation) {
  5757. translation.x = this.m[12];
  5758. translation.y = this.m[13];
  5759. translation.z = this.m[14];
  5760. }
  5761. scale = scale || MathTmp.Vector3[0];
  5762. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5763. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5764. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5765. if (this.determinant() <= 0) {
  5766. scale.y *= -1;
  5767. }
  5768. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5769. if (rotation) {
  5770. rotation.x = 0;
  5771. rotation.y = 0;
  5772. rotation.z = 0;
  5773. rotation.w = 1;
  5774. }
  5775. return false;
  5776. }
  5777. if (rotation) {
  5778. 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]);
  5779. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5780. }
  5781. return true;
  5782. };
  5783. /**
  5784. * Gets specific row of the matrix
  5785. * @param index defines the number of the row to get
  5786. * @returns the index-th row of the current matrix as a new Vector4
  5787. */
  5788. Matrix.prototype.getRow = function (index) {
  5789. if (index < 0 || index > 3) {
  5790. return null;
  5791. }
  5792. var i = index * 4;
  5793. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5794. };
  5795. /**
  5796. * Sets the index-th row of the current matrix to the vector4 values
  5797. * @param index defines the number of the row to set
  5798. * @param row defines the target vector4
  5799. * @returns the updated current matrix
  5800. */
  5801. Matrix.prototype.setRow = function (index, row) {
  5802. if (index < 0 || index > 3) {
  5803. return this;
  5804. }
  5805. var i = index * 4;
  5806. this.m[i + 0] = row.x;
  5807. this.m[i + 1] = row.y;
  5808. this.m[i + 2] = row.z;
  5809. this.m[i + 3] = row.w;
  5810. this._markAsUpdated();
  5811. return this;
  5812. };
  5813. /**
  5814. * Compute the transpose of the matrix
  5815. * @returns the new transposed matrix
  5816. */
  5817. Matrix.prototype.transpose = function () {
  5818. return Matrix.Transpose(this);
  5819. };
  5820. /**
  5821. * Compute the transpose of the matrix and store it in a given matrix
  5822. * @param result defines the target matrix
  5823. * @returns the current matrix
  5824. */
  5825. Matrix.prototype.transposeToRef = function (result) {
  5826. Matrix.TransposeToRef(this, result);
  5827. return this;
  5828. };
  5829. /**
  5830. * Sets the index-th row of the current matrix with the given 4 x float values
  5831. * @param index defines the row index
  5832. * @param x defines the x component to set
  5833. * @param y defines the y component to set
  5834. * @param z defines the z component to set
  5835. * @param w defines the w component to set
  5836. * @returns the updated current matrix
  5837. */
  5838. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5839. if (index < 0 || index > 3) {
  5840. return this;
  5841. }
  5842. var i = index * 4;
  5843. this.m[i + 0] = x;
  5844. this.m[i + 1] = y;
  5845. this.m[i + 2] = z;
  5846. this.m[i + 3] = w;
  5847. this._markAsUpdated();
  5848. return this;
  5849. };
  5850. /**
  5851. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5852. * @param scale defines the scale factor
  5853. * @returns a new matrix
  5854. */
  5855. Matrix.prototype.scale = function (scale) {
  5856. var result = new Matrix();
  5857. this.scaleToRef(scale, result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Scale the current matrix values by a factor to a given result matrix
  5862. * @param scale defines the scale factor
  5863. * @param result defines the matrix to store the result
  5864. * @returns the current matrix
  5865. */
  5866. Matrix.prototype.scaleToRef = function (scale, result) {
  5867. for (var index = 0; index < 16; index++) {
  5868. result.m[index] = this.m[index] * scale;
  5869. }
  5870. result._markAsUpdated();
  5871. return this;
  5872. };
  5873. /**
  5874. * Scale the current matrix values by a factor and add the result to a given matrix
  5875. * @param scale defines the scale factor
  5876. * @param result defines the Matrix to store the result
  5877. * @returns the current matrix
  5878. */
  5879. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5880. for (var index = 0; index < 16; index++) {
  5881. result.m[index] += this.m[index] * scale;
  5882. }
  5883. result._markAsUpdated();
  5884. return this;
  5885. };
  5886. /**
  5887. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5888. * @param ref matrix to store the result
  5889. */
  5890. Matrix.prototype.toNormalMatrix = function (ref) {
  5891. this.invertToRef(ref);
  5892. ref.transpose();
  5893. var m = ref.m;
  5894. 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);
  5895. };
  5896. /**
  5897. * Gets only rotation part of the current matrix
  5898. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5899. */
  5900. Matrix.prototype.getRotationMatrix = function () {
  5901. var result = Matrix.Identity();
  5902. this.getRotationMatrixToRef(result);
  5903. return result;
  5904. };
  5905. /**
  5906. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5907. * @param result defines the target matrix to store data to
  5908. * @returns the current matrix
  5909. */
  5910. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5911. var m = this.m;
  5912. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5913. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5914. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5915. if (this.determinant() <= 0) {
  5916. sy *= -1;
  5917. }
  5918. if (sx === 0 || sy === 0 || sz === 0) {
  5919. Matrix.IdentityToRef(result);
  5920. }
  5921. else {
  5922. 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);
  5923. }
  5924. return this;
  5925. };
  5926. // Statics
  5927. /**
  5928. * Creates a matrix from an array
  5929. * @param array defines the source array
  5930. * @param offset defines an offset in the source array
  5931. * @returns a new Matrix set from the starting index of the given array
  5932. */
  5933. Matrix.FromArray = function (array, offset) {
  5934. var result = new Matrix();
  5935. if (!offset) {
  5936. offset = 0;
  5937. }
  5938. Matrix.FromArrayToRef(array, offset, result);
  5939. return result;
  5940. };
  5941. /**
  5942. * Copy the content of an array into a given matrix
  5943. * @param array defines the source array
  5944. * @param offset defines an offset in the source array
  5945. * @param result defines the target matrix
  5946. */
  5947. Matrix.FromArrayToRef = function (array, offset, result) {
  5948. for (var index = 0; index < 16; index++) {
  5949. result.m[index] = array[index + offset];
  5950. }
  5951. result._markAsUpdated();
  5952. };
  5953. /**
  5954. * Stores an array into a matrix after having multiplied each component by a given factor
  5955. * @param array defines the source array
  5956. * @param offset defines the offset in the source array
  5957. * @param scale defines the scaling factor
  5958. * @param result defines the target matrix
  5959. */
  5960. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5961. for (var index = 0; index < 16; index++) {
  5962. result.m[index] = array[index + offset] * scale;
  5963. }
  5964. result._markAsUpdated();
  5965. };
  5966. /**
  5967. * Stores a list of values (16) inside a given matrix
  5968. * @param initialM11 defines 1st value of 1st row
  5969. * @param initialM12 defines 2nd value of 1st row
  5970. * @param initialM13 defines 3rd value of 1st row
  5971. * @param initialM14 defines 4th value of 1st row
  5972. * @param initialM21 defines 1st value of 2nd row
  5973. * @param initialM22 defines 2nd value of 2nd row
  5974. * @param initialM23 defines 3rd value of 2nd row
  5975. * @param initialM24 defines 4th value of 2nd row
  5976. * @param initialM31 defines 1st value of 3rd row
  5977. * @param initialM32 defines 2nd value of 3rd row
  5978. * @param initialM33 defines 3rd value of 3rd row
  5979. * @param initialM34 defines 4th value of 3rd row
  5980. * @param initialM41 defines 1st value of 4th row
  5981. * @param initialM42 defines 2nd value of 4th row
  5982. * @param initialM43 defines 3rd value of 4th row
  5983. * @param initialM44 defines 4th value of 4th row
  5984. * @param result defines the target matrix
  5985. */
  5986. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5987. result.m[0] = initialM11;
  5988. result.m[1] = initialM12;
  5989. result.m[2] = initialM13;
  5990. result.m[3] = initialM14;
  5991. result.m[4] = initialM21;
  5992. result.m[5] = initialM22;
  5993. result.m[6] = initialM23;
  5994. result.m[7] = initialM24;
  5995. result.m[8] = initialM31;
  5996. result.m[9] = initialM32;
  5997. result.m[10] = initialM33;
  5998. result.m[11] = initialM34;
  5999. result.m[12] = initialM41;
  6000. result.m[13] = initialM42;
  6001. result.m[14] = initialM43;
  6002. result.m[15] = initialM44;
  6003. result._markAsUpdated();
  6004. };
  6005. Object.defineProperty(Matrix, "IdentityReadOnly", {
  6006. /**
  6007. * Gets an identity matrix that must not be updated
  6008. */
  6009. get: function () {
  6010. return Matrix._identityReadOnly;
  6011. },
  6012. enumerable: true,
  6013. configurable: true
  6014. });
  6015. /**
  6016. * Creates new matrix from a list of values (16)
  6017. * @param initialM11 defines 1st value of 1st row
  6018. * @param initialM12 defines 2nd value of 1st row
  6019. * @param initialM13 defines 3rd value of 1st row
  6020. * @param initialM14 defines 4th value of 1st row
  6021. * @param initialM21 defines 1st value of 2nd row
  6022. * @param initialM22 defines 2nd value of 2nd row
  6023. * @param initialM23 defines 3rd value of 2nd row
  6024. * @param initialM24 defines 4th value of 2nd row
  6025. * @param initialM31 defines 1st value of 3rd row
  6026. * @param initialM32 defines 2nd value of 3rd row
  6027. * @param initialM33 defines 3rd value of 3rd row
  6028. * @param initialM34 defines 4th value of 3rd row
  6029. * @param initialM41 defines 1st value of 4th row
  6030. * @param initialM42 defines 2nd value of 4th row
  6031. * @param initialM43 defines 3rd value of 4th row
  6032. * @param initialM44 defines 4th value of 4th row
  6033. * @returns the new matrix
  6034. */
  6035. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6036. var result = new Matrix();
  6037. result.m[0] = initialM11;
  6038. result.m[1] = initialM12;
  6039. result.m[2] = initialM13;
  6040. result.m[3] = initialM14;
  6041. result.m[4] = initialM21;
  6042. result.m[5] = initialM22;
  6043. result.m[6] = initialM23;
  6044. result.m[7] = initialM24;
  6045. result.m[8] = initialM31;
  6046. result.m[9] = initialM32;
  6047. result.m[10] = initialM33;
  6048. result.m[11] = initialM34;
  6049. result.m[12] = initialM41;
  6050. result.m[13] = initialM42;
  6051. result.m[14] = initialM43;
  6052. result.m[15] = initialM44;
  6053. return result;
  6054. };
  6055. /**
  6056. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6057. * @param scale defines the scale vector3
  6058. * @param rotation defines the rotation quaternion
  6059. * @param translation defines the translation vector3
  6060. * @returns a new matrix
  6061. */
  6062. Matrix.Compose = function (scale, rotation, translation) {
  6063. var result = Matrix.Identity();
  6064. Matrix.ComposeToRef(scale, rotation, translation, result);
  6065. return result;
  6066. };
  6067. /**
  6068. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6069. * @param scale defines the scale vector3
  6070. * @param rotation defines the rotation quaternion
  6071. * @param translation defines the translation vector3
  6072. * @param result defines the target matrix
  6073. */
  6074. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6075. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6076. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6077. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6078. result.setTranslation(translation);
  6079. };
  6080. /**
  6081. * Creates a new identity matrix
  6082. * @returns a new identity matrix
  6083. */
  6084. Matrix.Identity = function () {
  6085. 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);
  6086. };
  6087. /**
  6088. * Creates a new identity matrix and stores the result in a given matrix
  6089. * @param result defines the target matrix
  6090. */
  6091. Matrix.IdentityToRef = function (result) {
  6092. 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);
  6093. };
  6094. /**
  6095. * Creates a new zero matrix
  6096. * @returns a new zero matrix
  6097. */
  6098. Matrix.Zero = function () {
  6099. 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);
  6100. };
  6101. /**
  6102. * Creates a new rotation matrix for "angle" radians around the X axis
  6103. * @param angle defines the angle (in radians) to use
  6104. * @return the new matrix
  6105. */
  6106. Matrix.RotationX = function (angle) {
  6107. var result = new Matrix();
  6108. Matrix.RotationXToRef(angle, result);
  6109. return result;
  6110. };
  6111. /**
  6112. * Creates a new matrix as the invert of a given matrix
  6113. * @param source defines the source matrix
  6114. * @returns the new matrix
  6115. */
  6116. Matrix.Invert = function (source) {
  6117. var result = new Matrix();
  6118. source.invertToRef(result);
  6119. return result;
  6120. };
  6121. /**
  6122. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6123. * @param angle defines the angle (in radians) to use
  6124. * @param result defines the target matrix
  6125. */
  6126. Matrix.RotationXToRef = function (angle, result) {
  6127. var s = Math.sin(angle);
  6128. var c = Math.cos(angle);
  6129. result.m[0] = 1.0;
  6130. result.m[15] = 1.0;
  6131. result.m[5] = c;
  6132. result.m[10] = c;
  6133. result.m[9] = -s;
  6134. result.m[6] = s;
  6135. result.m[1] = 0.0;
  6136. result.m[2] = 0.0;
  6137. result.m[3] = 0.0;
  6138. result.m[4] = 0.0;
  6139. result.m[7] = 0.0;
  6140. result.m[8] = 0.0;
  6141. result.m[11] = 0.0;
  6142. result.m[12] = 0.0;
  6143. result.m[13] = 0.0;
  6144. result.m[14] = 0.0;
  6145. result._markAsUpdated();
  6146. };
  6147. /**
  6148. * Creates a new rotation matrix for "angle" radians around the Y axis
  6149. * @param angle defines the angle (in radians) to use
  6150. * @return the new matrix
  6151. */
  6152. Matrix.RotationY = function (angle) {
  6153. var result = new Matrix();
  6154. Matrix.RotationYToRef(angle, result);
  6155. return result;
  6156. };
  6157. /**
  6158. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6159. * @param angle defines the angle (in radians) to use
  6160. * @param result defines the target matrix
  6161. */
  6162. Matrix.RotationYToRef = function (angle, result) {
  6163. var s = Math.sin(angle);
  6164. var c = Math.cos(angle);
  6165. result.m[5] = 1.0;
  6166. result.m[15] = 1.0;
  6167. result.m[0] = c;
  6168. result.m[2] = -s;
  6169. result.m[8] = s;
  6170. result.m[10] = c;
  6171. result.m[1] = 0.0;
  6172. result.m[3] = 0.0;
  6173. result.m[4] = 0.0;
  6174. result.m[6] = 0.0;
  6175. result.m[7] = 0.0;
  6176. result.m[9] = 0.0;
  6177. result.m[11] = 0.0;
  6178. result.m[12] = 0.0;
  6179. result.m[13] = 0.0;
  6180. result.m[14] = 0.0;
  6181. result._markAsUpdated();
  6182. };
  6183. /**
  6184. * Creates a new rotation matrix for "angle" radians around the Z axis
  6185. * @param angle defines the angle (in radians) to use
  6186. * @return the new matrix
  6187. */
  6188. Matrix.RotationZ = function (angle) {
  6189. var result = new Matrix();
  6190. Matrix.RotationZToRef(angle, result);
  6191. return result;
  6192. };
  6193. /**
  6194. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6195. * @param angle defines the angle (in radians) to use
  6196. * @param result defines the target matrix
  6197. */
  6198. Matrix.RotationZToRef = function (angle, result) {
  6199. var s = Math.sin(angle);
  6200. var c = Math.cos(angle);
  6201. result.m[10] = 1.0;
  6202. result.m[15] = 1.0;
  6203. result.m[0] = c;
  6204. result.m[1] = s;
  6205. result.m[4] = -s;
  6206. result.m[5] = c;
  6207. result.m[2] = 0.0;
  6208. result.m[3] = 0.0;
  6209. result.m[6] = 0.0;
  6210. result.m[7] = 0.0;
  6211. result.m[8] = 0.0;
  6212. result.m[9] = 0.0;
  6213. result.m[11] = 0.0;
  6214. result.m[12] = 0.0;
  6215. result.m[13] = 0.0;
  6216. result.m[14] = 0.0;
  6217. result._markAsUpdated();
  6218. };
  6219. /**
  6220. * Creates a new rotation matrix for "angle" radians around the given axis
  6221. * @param axis defines the axis to use
  6222. * @param angle defines the angle (in radians) to use
  6223. * @return the new matrix
  6224. */
  6225. Matrix.RotationAxis = function (axis, angle) {
  6226. var result = Matrix.Zero();
  6227. Matrix.RotationAxisToRef(axis, angle, result);
  6228. return result;
  6229. };
  6230. /**
  6231. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6232. * @param axis defines the axis to use
  6233. * @param angle defines the angle (in radians) to use
  6234. * @param result defines the target matrix
  6235. */
  6236. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6237. var s = Math.sin(-angle);
  6238. var c = Math.cos(-angle);
  6239. var c1 = 1 - c;
  6240. axis.normalize();
  6241. result.m[0] = (axis.x * axis.x) * c1 + c;
  6242. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6243. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6244. result.m[3] = 0.0;
  6245. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6246. result.m[5] = (axis.y * axis.y) * c1 + c;
  6247. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6248. result.m[7] = 0.0;
  6249. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6250. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6251. result.m[10] = (axis.z * axis.z) * c1 + c;
  6252. result.m[11] = 0.0;
  6253. result.m[15] = 1.0;
  6254. result._markAsUpdated();
  6255. };
  6256. /**
  6257. * Creates a rotation matrix
  6258. * @param yaw defines the yaw angle in radians (Y axis)
  6259. * @param pitch defines the pitch angle in radians (X axis)
  6260. * @param roll defines the roll angle in radians (X axis)
  6261. * @returns the new rotation matrix
  6262. */
  6263. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6264. var result = new Matrix();
  6265. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6266. return result;
  6267. };
  6268. /**
  6269. * Creates a rotation matrix and stores it in a given matrix
  6270. * @param yaw defines the yaw angle in radians (Y axis)
  6271. * @param pitch defines the pitch angle in radians (X axis)
  6272. * @param roll defines the roll angle in radians (X axis)
  6273. * @param result defines the target matrix
  6274. */
  6275. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6276. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6277. this._tempQuaternion.toRotationMatrix(result);
  6278. };
  6279. /**
  6280. * Creates a scaling matrix
  6281. * @param x defines the scale factor on X axis
  6282. * @param y defines the scale factor on Y axis
  6283. * @param z defines the scale factor on Z axis
  6284. * @returns the new matrix
  6285. */
  6286. Matrix.Scaling = function (x, y, z) {
  6287. var result = Matrix.Zero();
  6288. Matrix.ScalingToRef(x, y, z, result);
  6289. return result;
  6290. };
  6291. /**
  6292. * Creates a scaling matrix and stores it in a given matrix
  6293. * @param x defines the scale factor on X axis
  6294. * @param y defines the scale factor on Y axis
  6295. * @param z defines the scale factor on Z axis
  6296. * @param result defines the target matrix
  6297. */
  6298. Matrix.ScalingToRef = function (x, y, z, result) {
  6299. result.m[0] = x;
  6300. result.m[1] = 0.0;
  6301. result.m[2] = 0.0;
  6302. result.m[3] = 0.0;
  6303. result.m[4] = 0.0;
  6304. result.m[5] = y;
  6305. result.m[6] = 0.0;
  6306. result.m[7] = 0.0;
  6307. result.m[8] = 0.0;
  6308. result.m[9] = 0.0;
  6309. result.m[10] = z;
  6310. result.m[11] = 0.0;
  6311. result.m[12] = 0.0;
  6312. result.m[13] = 0.0;
  6313. result.m[14] = 0.0;
  6314. result.m[15] = 1.0;
  6315. result._markAsUpdated();
  6316. };
  6317. /**
  6318. * Creates a translation matrix
  6319. * @param x defines the translation on X axis
  6320. * @param y defines the translation on Y axis
  6321. * @param z defines the translationon Z axis
  6322. * @returns the new matrix
  6323. */
  6324. Matrix.Translation = function (x, y, z) {
  6325. var result = Matrix.Identity();
  6326. Matrix.TranslationToRef(x, y, z, result);
  6327. return result;
  6328. };
  6329. /**
  6330. * Creates a translation matrix and stores it in a given matrix
  6331. * @param x defines the translation on X axis
  6332. * @param y defines the translation on Y axis
  6333. * @param z defines the translationon Z axis
  6334. * @param result defines the target matrix
  6335. */
  6336. Matrix.TranslationToRef = function (x, y, z, result) {
  6337. 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);
  6338. };
  6339. /**
  6340. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6341. * @param startValue defines the start value
  6342. * @param endValue defines the end value
  6343. * @param gradient defines the gradient factor
  6344. * @returns the new matrix
  6345. */
  6346. Matrix.Lerp = function (startValue, endValue, gradient) {
  6347. var result = Matrix.Zero();
  6348. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6349. return result;
  6350. };
  6351. /**
  6352. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6353. * @param startValue defines the start value
  6354. * @param endValue defines the end value
  6355. * @param gradient defines the gradient factor
  6356. * @param result defines the Matrix object where to store data
  6357. */
  6358. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6359. for (var index = 0; index < 16; index++) {
  6360. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6361. }
  6362. result._markAsUpdated();
  6363. };
  6364. /**
  6365. * Builds a new matrix whose values are computed by:
  6366. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6367. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6368. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6369. * @param startValue defines the first matrix
  6370. * @param endValue defines the second matrix
  6371. * @param gradient defines the gradient between the two matrices
  6372. * @returns the new matrix
  6373. */
  6374. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6375. var result = Matrix.Zero();
  6376. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6377. return result;
  6378. };
  6379. /**
  6380. * Update a matrix to values which are computed by:
  6381. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6382. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6383. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6384. * @param startValue defines the first matrix
  6385. * @param endValue defines the second matrix
  6386. * @param gradient defines the gradient between the two matrices
  6387. * @param result defines the target matrix
  6388. */
  6389. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6390. var startScale = MathTmp.Vector3[0];
  6391. var startRotation = MathTmp.Quaternion[0];
  6392. var startTranslation = MathTmp.Vector3[1];
  6393. startValue.decompose(startScale, startRotation, startTranslation);
  6394. var endScale = MathTmp.Vector3[2];
  6395. var endRotation = MathTmp.Quaternion[1];
  6396. var endTranslation = MathTmp.Vector3[3];
  6397. endValue.decompose(endScale, endRotation, endTranslation);
  6398. var resultScale = MathTmp.Vector3[4];
  6399. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6400. var resultRotation = MathTmp.Quaternion[2];
  6401. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6402. var resultTranslation = MathTmp.Vector3[5];
  6403. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6404. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6405. };
  6406. /**
  6407. * 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"
  6408. * This function works in left handed mode
  6409. * @param eye defines the final position of the entity
  6410. * @param target defines where the entity should look at
  6411. * @param up defines the up vector for the entity
  6412. * @returns the new matrix
  6413. */
  6414. Matrix.LookAtLH = function (eye, target, up) {
  6415. var result = Matrix.Zero();
  6416. Matrix.LookAtLHToRef(eye, target, up, result);
  6417. return result;
  6418. };
  6419. /**
  6420. * 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".
  6421. * This function works in left handed mode
  6422. * @param eye defines the final position of the entity
  6423. * @param target defines where the entity should look at
  6424. * @param up defines the up vector for the entity
  6425. * @param result defines the target matrix
  6426. */
  6427. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6428. // Z axis
  6429. target.subtractToRef(eye, this._zAxis);
  6430. this._zAxis.normalize();
  6431. // X axis
  6432. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6433. if (this._xAxis.lengthSquared() === 0) {
  6434. this._xAxis.x = 1.0;
  6435. }
  6436. else {
  6437. this._xAxis.normalize();
  6438. }
  6439. // Y axis
  6440. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6441. this._yAxis.normalize();
  6442. // Eye angles
  6443. var ex = -Vector3.Dot(this._xAxis, eye);
  6444. var ey = -Vector3.Dot(this._yAxis, eye);
  6445. var ez = -Vector3.Dot(this._zAxis, eye);
  6446. 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);
  6447. };
  6448. /**
  6449. * 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"
  6450. * This function works in right handed mode
  6451. * @param eye defines the final position of the entity
  6452. * @param target defines where the entity should look at
  6453. * @param up defines the up vector for the entity
  6454. * @returns the new matrix
  6455. */
  6456. Matrix.LookAtRH = function (eye, target, up) {
  6457. var result = Matrix.Zero();
  6458. Matrix.LookAtRHToRef(eye, target, up, result);
  6459. return result;
  6460. };
  6461. /**
  6462. * 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".
  6463. * This function works in right handed mode
  6464. * @param eye defines the final position of the entity
  6465. * @param target defines where the entity should look at
  6466. * @param up defines the up vector for the entity
  6467. * @param result defines the target matrix
  6468. */
  6469. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6470. // Z axis
  6471. eye.subtractToRef(target, this._zAxis);
  6472. this._zAxis.normalize();
  6473. // X axis
  6474. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6475. if (this._xAxis.lengthSquared() === 0) {
  6476. this._xAxis.x = 1.0;
  6477. }
  6478. else {
  6479. this._xAxis.normalize();
  6480. }
  6481. // Y axis
  6482. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6483. this._yAxis.normalize();
  6484. // Eye angles
  6485. var ex = -Vector3.Dot(this._xAxis, eye);
  6486. var ey = -Vector3.Dot(this._yAxis, eye);
  6487. var ez = -Vector3.Dot(this._zAxis, eye);
  6488. 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);
  6489. };
  6490. /**
  6491. * Create a left-handed orthographic projection matrix
  6492. * @param width defines the viewport width
  6493. * @param height defines the viewport height
  6494. * @param znear defines the near clip plane
  6495. * @param zfar defines the far clip plane
  6496. * @returns a new matrix as a left-handed orthographic projection matrix
  6497. */
  6498. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6499. var matrix = Matrix.Zero();
  6500. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6501. return matrix;
  6502. };
  6503. /**
  6504. * Store a left-handed orthographic projection to a given matrix
  6505. * @param width defines the viewport width
  6506. * @param height defines the viewport height
  6507. * @param znear defines the near clip plane
  6508. * @param zfar defines the far clip plane
  6509. * @param result defines the target matrix
  6510. */
  6511. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6512. var n = znear;
  6513. var f = zfar;
  6514. var a = 2.0 / width;
  6515. var b = 2.0 / height;
  6516. var c = 2.0 / (f - n);
  6517. var d = -(f + n) / (f - n);
  6518. 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);
  6519. };
  6520. /**
  6521. * Create a left-handed orthographic projection matrix
  6522. * @param left defines the viewport left coordinate
  6523. * @param right defines the viewport right coordinate
  6524. * @param bottom defines the viewport bottom coordinate
  6525. * @param top defines the viewport top coordinate
  6526. * @param znear defines the near clip plane
  6527. * @param zfar defines the far clip plane
  6528. * @returns a new matrix as a left-handed orthographic projection matrix
  6529. */
  6530. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6531. var matrix = Matrix.Zero();
  6532. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6533. return matrix;
  6534. };
  6535. /**
  6536. * Stores a left-handed orthographic projection into a given matrix
  6537. * @param left defines the viewport left coordinate
  6538. * @param right defines the viewport right coordinate
  6539. * @param bottom defines the viewport bottom coordinate
  6540. * @param top defines the viewport top coordinate
  6541. * @param znear defines the near clip plane
  6542. * @param zfar defines the far clip plane
  6543. * @param result defines the target matrix
  6544. */
  6545. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6546. var n = znear;
  6547. var f = zfar;
  6548. var a = 2.0 / (right - left);
  6549. var b = 2.0 / (top - bottom);
  6550. var c = 2.0 / (f - n);
  6551. var d = -(f + n) / (f - n);
  6552. var i0 = (left + right) / (left - right);
  6553. var i1 = (top + bottom) / (bottom - top);
  6554. 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);
  6555. };
  6556. /**
  6557. * Creates a right-handed orthographic projection matrix
  6558. * @param left defines the viewport left coordinate
  6559. * @param right defines the viewport right coordinate
  6560. * @param bottom defines the viewport bottom coordinate
  6561. * @param top defines the viewport top coordinate
  6562. * @param znear defines the near clip plane
  6563. * @param zfar defines the far clip plane
  6564. * @returns a new matrix as a right-handed orthographic projection matrix
  6565. */
  6566. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6567. var matrix = Matrix.Zero();
  6568. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6569. return matrix;
  6570. };
  6571. /**
  6572. * Stores a right-handed orthographic projection into a given matrix
  6573. * @param left defines the viewport left coordinate
  6574. * @param right defines the viewport right coordinate
  6575. * @param bottom defines the viewport bottom coordinate
  6576. * @param top defines the viewport top coordinate
  6577. * @param znear defines the near clip plane
  6578. * @param zfar defines the far clip plane
  6579. * @param result defines the target matrix
  6580. */
  6581. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6582. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6583. result.m[10] *= -1.0;
  6584. };
  6585. /**
  6586. * Creates a left-handed perspective projection matrix
  6587. * @param width defines the viewport width
  6588. * @param height defines the viewport height
  6589. * @param znear defines the near clip plane
  6590. * @param zfar defines the far clip plane
  6591. * @returns a new matrix as a left-handed perspective projection matrix
  6592. */
  6593. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6594. var matrix = Matrix.Zero();
  6595. var n = znear;
  6596. var f = zfar;
  6597. var a = 2.0 * n / width;
  6598. var b = 2.0 * n / height;
  6599. var c = (f + n) / (f - n);
  6600. var d = -2.0 * f * n / (f - n);
  6601. 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);
  6602. return matrix;
  6603. };
  6604. /**
  6605. * Creates a left-handed perspective projection matrix
  6606. * @param fov defines the horizontal field of view
  6607. * @param aspect defines the aspect ratio
  6608. * @param znear defines the near clip plane
  6609. * @param zfar defines the far clip plane
  6610. * @returns a new matrix as a left-handed perspective projection matrix
  6611. */
  6612. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6613. var matrix = Matrix.Zero();
  6614. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6615. return matrix;
  6616. };
  6617. /**
  6618. * Stores a left-handed perspective projection into a given matrix
  6619. * @param fov defines the horizontal field of view
  6620. * @param aspect defines the aspect ratio
  6621. * @param znear defines the near clip plane
  6622. * @param zfar defines the far clip plane
  6623. * @param result defines the target matrix
  6624. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6625. */
  6626. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6627. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6628. var n = znear;
  6629. var f = zfar;
  6630. var t = 1.0 / (Math.tan(fov * 0.5));
  6631. var a = isVerticalFovFixed ? (t / aspect) : t;
  6632. var b = isVerticalFovFixed ? t : (t * aspect);
  6633. var c = (f + n) / (f - n);
  6634. var d = -2.0 * f * n / (f - n);
  6635. 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);
  6636. };
  6637. /**
  6638. * Creates a right-handed perspective projection matrix
  6639. * @param fov defines the horizontal field of view
  6640. * @param aspect defines the aspect ratio
  6641. * @param znear defines the near clip plane
  6642. * @param zfar defines the far clip plane
  6643. * @returns a new matrix as a right-handed perspective projection matrix
  6644. */
  6645. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6646. var matrix = Matrix.Zero();
  6647. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6648. return matrix;
  6649. };
  6650. /**
  6651. * Stores a right-handed perspective projection into a given matrix
  6652. * @param fov defines the horizontal field of view
  6653. * @param aspect defines the aspect ratio
  6654. * @param znear defines the near clip plane
  6655. * @param zfar defines the far clip plane
  6656. * @param result defines the target matrix
  6657. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6658. */
  6659. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6660. //alternatively this could be expressed as:
  6661. // m = PerspectiveFovLHToRef
  6662. // m[10] *= -1.0;
  6663. // m[11] *= -1.0;
  6664. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6665. var n = znear;
  6666. var f = zfar;
  6667. var t = 1.0 / (Math.tan(fov * 0.5));
  6668. var a = isVerticalFovFixed ? (t / aspect) : t;
  6669. var b = isVerticalFovFixed ? t : (t * aspect);
  6670. var c = -(f + n) / (f - n);
  6671. var d = -2 * f * n / (f - n);
  6672. 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);
  6673. };
  6674. /**
  6675. * Stores a perspective projection for WebVR info a given matrix
  6676. * @param fov defines the field of view
  6677. * @param znear defines the near clip plane
  6678. * @param zfar defines the far clip plane
  6679. * @param result defines the target matrix
  6680. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6681. */
  6682. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6683. if (rightHanded === void 0) { rightHanded = false; }
  6684. var rightHandedFactor = rightHanded ? -1 : 1;
  6685. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6686. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6687. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6688. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6689. var xScale = 2.0 / (leftTan + rightTan);
  6690. var yScale = 2.0 / (upTan + downTan);
  6691. result.m[0] = xScale;
  6692. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6693. result.m[5] = yScale;
  6694. result.m[6] = result.m[7] = 0.0;
  6695. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6696. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6697. result.m[10] = -zfar / (znear - zfar);
  6698. result.m[11] = 1.0 * rightHandedFactor;
  6699. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6700. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6701. result._markAsUpdated();
  6702. };
  6703. /**
  6704. * Computes a complete transformation matrix
  6705. * @param viewport defines the viewport to use
  6706. * @param world defines the world matrix
  6707. * @param view defines the view matrix
  6708. * @param projection defines the projection matrix
  6709. * @param zmin defines the near clip plane
  6710. * @param zmax defines the far clip plane
  6711. * @returns the transformation matrix
  6712. */
  6713. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6714. var cw = viewport.width;
  6715. var ch = viewport.height;
  6716. var cx = viewport.x;
  6717. var cy = viewport.y;
  6718. 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);
  6719. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6720. };
  6721. /**
  6722. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6723. * @param matrix defines the matrix to use
  6724. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6725. */
  6726. Matrix.GetAsMatrix2x2 = function (matrix) {
  6727. return new Float32Array([
  6728. matrix.m[0], matrix.m[1],
  6729. matrix.m[4], matrix.m[5]
  6730. ]);
  6731. };
  6732. /**
  6733. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6734. * @param matrix defines the matrix to use
  6735. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6736. */
  6737. Matrix.GetAsMatrix3x3 = function (matrix) {
  6738. return new Float32Array([
  6739. matrix.m[0], matrix.m[1], matrix.m[2],
  6740. matrix.m[4], matrix.m[5], matrix.m[6],
  6741. matrix.m[8], matrix.m[9], matrix.m[10]
  6742. ]);
  6743. };
  6744. /**
  6745. * Compute the transpose of a given matrix
  6746. * @param matrix defines the matrix to transpose
  6747. * @returns the new matrix
  6748. */
  6749. Matrix.Transpose = function (matrix) {
  6750. var result = new Matrix();
  6751. Matrix.TransposeToRef(matrix, result);
  6752. return result;
  6753. };
  6754. /**
  6755. * Compute the transpose of a matrix and store it in a target matrix
  6756. * @param matrix defines the matrix to transpose
  6757. * @param result defines the target matrix
  6758. */
  6759. Matrix.TransposeToRef = function (matrix, result) {
  6760. result.m[0] = matrix.m[0];
  6761. result.m[1] = matrix.m[4];
  6762. result.m[2] = matrix.m[8];
  6763. result.m[3] = matrix.m[12];
  6764. result.m[4] = matrix.m[1];
  6765. result.m[5] = matrix.m[5];
  6766. result.m[6] = matrix.m[9];
  6767. result.m[7] = matrix.m[13];
  6768. result.m[8] = matrix.m[2];
  6769. result.m[9] = matrix.m[6];
  6770. result.m[10] = matrix.m[10];
  6771. result.m[11] = matrix.m[14];
  6772. result.m[12] = matrix.m[3];
  6773. result.m[13] = matrix.m[7];
  6774. result.m[14] = matrix.m[11];
  6775. result.m[15] = matrix.m[15];
  6776. };
  6777. /**
  6778. * Computes a reflection matrix from a plane
  6779. * @param plane defines the reflection plane
  6780. * @returns a new matrix
  6781. */
  6782. Matrix.Reflection = function (plane) {
  6783. var matrix = new Matrix();
  6784. Matrix.ReflectionToRef(plane, matrix);
  6785. return matrix;
  6786. };
  6787. /**
  6788. * Computes a reflection matrix from a plane
  6789. * @param plane defines the reflection plane
  6790. * @param result defines the target matrix
  6791. */
  6792. Matrix.ReflectionToRef = function (plane, result) {
  6793. plane.normalize();
  6794. var x = plane.normal.x;
  6795. var y = plane.normal.y;
  6796. var z = plane.normal.z;
  6797. var temp = -2 * x;
  6798. var temp2 = -2 * y;
  6799. var temp3 = -2 * z;
  6800. result.m[0] = (temp * x) + 1;
  6801. result.m[1] = temp2 * x;
  6802. result.m[2] = temp3 * x;
  6803. result.m[3] = 0.0;
  6804. result.m[4] = temp * y;
  6805. result.m[5] = (temp2 * y) + 1;
  6806. result.m[6] = temp3 * y;
  6807. result.m[7] = 0.0;
  6808. result.m[8] = temp * z;
  6809. result.m[9] = temp2 * z;
  6810. result.m[10] = (temp3 * z) + 1;
  6811. result.m[11] = 0.0;
  6812. result.m[12] = temp * plane.d;
  6813. result.m[13] = temp2 * plane.d;
  6814. result.m[14] = temp3 * plane.d;
  6815. result.m[15] = 1.0;
  6816. result._markAsUpdated();
  6817. };
  6818. /**
  6819. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6820. * @param xaxis defines the value of the 1st axis
  6821. * @param yaxis defines the value of the 2nd axis
  6822. * @param zaxis defines the value of the 3rd axis
  6823. * @param result defines the target matrix
  6824. */
  6825. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6826. result.m[0] = xaxis.x;
  6827. result.m[1] = xaxis.y;
  6828. result.m[2] = xaxis.z;
  6829. result.m[3] = 0.0;
  6830. result.m[4] = yaxis.x;
  6831. result.m[5] = yaxis.y;
  6832. result.m[6] = yaxis.z;
  6833. result.m[7] = 0.0;
  6834. result.m[8] = zaxis.x;
  6835. result.m[9] = zaxis.y;
  6836. result.m[10] = zaxis.z;
  6837. result.m[11] = 0.0;
  6838. result.m[12] = 0.0;
  6839. result.m[13] = 0.0;
  6840. result.m[14] = 0.0;
  6841. result.m[15] = 1.0;
  6842. result._markAsUpdated();
  6843. };
  6844. /**
  6845. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6846. * @param quat defines the quaternion to use
  6847. * @param result defines the target matrix
  6848. */
  6849. Matrix.FromQuaternionToRef = function (quat, result) {
  6850. var xx = quat.x * quat.x;
  6851. var yy = quat.y * quat.y;
  6852. var zz = quat.z * quat.z;
  6853. var xy = quat.x * quat.y;
  6854. var zw = quat.z * quat.w;
  6855. var zx = quat.z * quat.x;
  6856. var yw = quat.y * quat.w;
  6857. var yz = quat.y * quat.z;
  6858. var xw = quat.x * quat.w;
  6859. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6860. result.m[1] = 2.0 * (xy + zw);
  6861. result.m[2] = 2.0 * (zx - yw);
  6862. result.m[3] = 0.0;
  6863. result.m[4] = 2.0 * (xy - zw);
  6864. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6865. result.m[6] = 2.0 * (yz + xw);
  6866. result.m[7] = 0.0;
  6867. result.m[8] = 2.0 * (zx + yw);
  6868. result.m[9] = 2.0 * (yz - xw);
  6869. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6870. result.m[11] = 0.0;
  6871. result.m[12] = 0.0;
  6872. result.m[13] = 0.0;
  6873. result.m[14] = 0.0;
  6874. result.m[15] = 1.0;
  6875. result._markAsUpdated();
  6876. };
  6877. Matrix._tempQuaternion = new Quaternion();
  6878. Matrix._xAxis = Vector3.Zero();
  6879. Matrix._yAxis = Vector3.Zero();
  6880. Matrix._zAxis = Vector3.Zero();
  6881. Matrix._updateFlagSeed = 0;
  6882. Matrix._identityReadOnly = Matrix.Identity();
  6883. return Matrix;
  6884. }());
  6885. BABYLON.Matrix = Matrix;
  6886. /**
  6887. * Represens a plane by the equation ax + by + cz + d = 0
  6888. */
  6889. var Plane = /** @class */ (function () {
  6890. /**
  6891. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6892. * @param a a component of the plane
  6893. * @param b b component of the plane
  6894. * @param c c component of the plane
  6895. * @param d d component of the plane
  6896. */
  6897. function Plane(a, b, c, d) {
  6898. this.normal = new Vector3(a, b, c);
  6899. this.d = d;
  6900. }
  6901. /**
  6902. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6903. */
  6904. Plane.prototype.asArray = function () {
  6905. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6906. };
  6907. // Methods
  6908. /**
  6909. * @returns a new plane copied from the current Plane.
  6910. */
  6911. Plane.prototype.clone = function () {
  6912. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6913. };
  6914. /**
  6915. * @returns the string "Plane".
  6916. */
  6917. Plane.prototype.getClassName = function () {
  6918. return "Plane";
  6919. };
  6920. /**
  6921. * @returns the Plane hash code.
  6922. */
  6923. Plane.prototype.getHashCode = function () {
  6924. var hash = this.normal.getHashCode();
  6925. hash = (hash * 397) ^ (this.d || 0);
  6926. return hash;
  6927. };
  6928. /**
  6929. * Normalize the current Plane in place.
  6930. * @returns the updated Plane.
  6931. */
  6932. Plane.prototype.normalize = function () {
  6933. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6934. var magnitude = 0.0;
  6935. if (norm !== 0) {
  6936. magnitude = 1.0 / norm;
  6937. }
  6938. this.normal.x *= magnitude;
  6939. this.normal.y *= magnitude;
  6940. this.normal.z *= magnitude;
  6941. this.d *= magnitude;
  6942. return this;
  6943. };
  6944. /**
  6945. * Applies a transformation the plane and returns the result
  6946. * @param transformation the transformation matrix to be applied to the plane
  6947. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6948. */
  6949. Plane.prototype.transform = function (transformation) {
  6950. var transposedMatrix = Matrix.Transpose(transformation);
  6951. var x = this.normal.x;
  6952. var y = this.normal.y;
  6953. var z = this.normal.z;
  6954. var d = this.d;
  6955. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6956. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6957. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6958. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6959. return new Plane(normalX, normalY, normalZ, finalD);
  6960. };
  6961. /**
  6962. * Calcualtte the dot product between the point and the plane normal
  6963. * @param point point to calculate the dot product with
  6964. * @returns the dot product (float) of the point coordinates and the plane normal.
  6965. */
  6966. Plane.prototype.dotCoordinate = function (point) {
  6967. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6968. };
  6969. /**
  6970. * Updates the current Plane from the plane defined by the three given points.
  6971. * @param point1 one of the points used to contruct the plane
  6972. * @param point2 one of the points used to contruct the plane
  6973. * @param point3 one of the points used to contruct the plane
  6974. * @returns the updated Plane.
  6975. */
  6976. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6977. var x1 = point2.x - point1.x;
  6978. var y1 = point2.y - point1.y;
  6979. var z1 = point2.z - point1.z;
  6980. var x2 = point3.x - point1.x;
  6981. var y2 = point3.y - point1.y;
  6982. var z2 = point3.z - point1.z;
  6983. var yz = (y1 * z2) - (z1 * y2);
  6984. var xz = (z1 * x2) - (x1 * z2);
  6985. var xy = (x1 * y2) - (y1 * x2);
  6986. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6987. var invPyth;
  6988. if (pyth !== 0) {
  6989. invPyth = 1.0 / pyth;
  6990. }
  6991. else {
  6992. invPyth = 0.0;
  6993. }
  6994. this.normal.x = yz * invPyth;
  6995. this.normal.y = xz * invPyth;
  6996. this.normal.z = xy * invPyth;
  6997. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6998. return this;
  6999. };
  7000. /**
  7001. * Checks if the plane is facing a given direction
  7002. * @param direction the direction to check if the plane is facing
  7003. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  7004. * @returns True is the vector "direction" is the same side than the plane normal.
  7005. */
  7006. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  7007. var dot = Vector3.Dot(this.normal, direction);
  7008. return (dot <= epsilon);
  7009. };
  7010. /**
  7011. * Calculates the distance to a point
  7012. * @param point point to calculate distance to
  7013. * @returns the signed distance (float) from the given point to the Plane.
  7014. */
  7015. Plane.prototype.signedDistanceTo = function (point) {
  7016. return Vector3.Dot(point, this.normal) + this.d;
  7017. };
  7018. // Statics
  7019. /**
  7020. * Creates a plane from an array
  7021. * @param array the array to create a plane from
  7022. * @returns a new Plane from the given array.
  7023. */
  7024. Plane.FromArray = function (array) {
  7025. return new Plane(array[0], array[1], array[2], array[3]);
  7026. };
  7027. /**
  7028. * Creates a plane from three points
  7029. * @param point1 point used to create the plane
  7030. * @param point2 point used to create the plane
  7031. * @param point3 point used to create the plane
  7032. * @returns a new Plane defined by the three given points.
  7033. */
  7034. Plane.FromPoints = function (point1, point2, point3) {
  7035. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7036. result.copyFromPoints(point1, point2, point3);
  7037. return result;
  7038. };
  7039. /**
  7040. * Creates a plane from an origin point and a normal
  7041. * @param origin origin of the plane to be constructed
  7042. * @param normal normal of the plane to be constructed
  7043. * @returns a new Plane the normal vector to this plane at the given origin point.
  7044. * Note : the vector "normal" is updated because normalized.
  7045. */
  7046. Plane.FromPositionAndNormal = function (origin, normal) {
  7047. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7048. normal.normalize();
  7049. result.normal = normal;
  7050. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7051. return result;
  7052. };
  7053. /**
  7054. * Calculates the distance from a plane and a point
  7055. * @param origin origin of the plane to be constructed
  7056. * @param normal normal of the plane to be constructed
  7057. * @param point point to calculate distance to
  7058. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7059. */
  7060. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7061. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7062. return Vector3.Dot(point, normal) + d;
  7063. };
  7064. return Plane;
  7065. }());
  7066. BABYLON.Plane = Plane;
  7067. /**
  7068. * Class used to represent a viewport on screen
  7069. */
  7070. var Viewport = /** @class */ (function () {
  7071. /**
  7072. * Creates a Viewport object located at (x, y) and sized (width, height)
  7073. * @param x defines viewport left coordinate
  7074. * @param y defines viewport top coordinate
  7075. * @param width defines the viewport width
  7076. * @param height defines the viewport height
  7077. */
  7078. function Viewport(
  7079. /** viewport left coordinate */
  7080. x,
  7081. /** viewport top coordinate */
  7082. y,
  7083. /**viewport width */
  7084. width,
  7085. /** viewport height */
  7086. height) {
  7087. this.x = x;
  7088. this.y = y;
  7089. this.width = width;
  7090. this.height = height;
  7091. }
  7092. /**
  7093. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7094. * @param renderWidthOrEngine defines either an engine or the rendering width
  7095. * @param renderHeight defines the rendering height
  7096. * @returns a new Viewport
  7097. */
  7098. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7099. if (renderWidthOrEngine.getRenderWidth) {
  7100. var engine = renderWidthOrEngine;
  7101. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7102. }
  7103. var renderWidth = renderWidthOrEngine;
  7104. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7105. };
  7106. /**
  7107. * Returns a new Viewport copied from the current one
  7108. * @returns a new Viewport
  7109. */
  7110. Viewport.prototype.clone = function () {
  7111. return new Viewport(this.x, this.y, this.width, this.height);
  7112. };
  7113. return Viewport;
  7114. }());
  7115. BABYLON.Viewport = Viewport;
  7116. /**
  7117. * Reprasents a camera frustum
  7118. */
  7119. var Frustum = /** @class */ (function () {
  7120. function Frustum() {
  7121. }
  7122. /**
  7123. * Gets the planes representing the frustum
  7124. * @param transform matrix to be applied to the returned planes
  7125. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7126. */
  7127. Frustum.GetPlanes = function (transform) {
  7128. var frustumPlanes = [];
  7129. for (var index = 0; index < 6; index++) {
  7130. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7131. }
  7132. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7133. return frustumPlanes;
  7134. };
  7135. /**
  7136. * Gets the near frustum plane transformed by the transform matrix
  7137. * @param transform transformation matrix to be applied to the resulting frustum plane
  7138. * @param frustumPlane the resuling frustum plane
  7139. */
  7140. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7141. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7142. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7143. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7144. frustumPlane.d = transform.m[15] + transform.m[14];
  7145. frustumPlane.normalize();
  7146. };
  7147. /**
  7148. * Gets the far frustum plane transformed by the transform matrix
  7149. * @param transform transformation matrix to be applied to the resulting frustum plane
  7150. * @param frustumPlane the resuling frustum plane
  7151. */
  7152. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7153. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7154. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7155. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7156. frustumPlane.d = transform.m[15] - transform.m[14];
  7157. frustumPlane.normalize();
  7158. };
  7159. /**
  7160. * Gets the left frustum plane transformed by the transform matrix
  7161. * @param transform transformation matrix to be applied to the resulting frustum plane
  7162. * @param frustumPlane the resuling frustum plane
  7163. */
  7164. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7165. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7166. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7167. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7168. frustumPlane.d = transform.m[15] + transform.m[12];
  7169. frustumPlane.normalize();
  7170. };
  7171. /**
  7172. * Gets the right frustum plane transformed by the transform matrix
  7173. * @param transform transformation matrix to be applied to the resulting frustum plane
  7174. * @param frustumPlane the resuling frustum plane
  7175. */
  7176. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7177. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7178. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7179. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7180. frustumPlane.d = transform.m[15] - transform.m[12];
  7181. frustumPlane.normalize();
  7182. };
  7183. /**
  7184. * Gets the top frustum plane transformed by the transform matrix
  7185. * @param transform transformation matrix to be applied to the resulting frustum plane
  7186. * @param frustumPlane the resuling frustum plane
  7187. */
  7188. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7189. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7190. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7191. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7192. frustumPlane.d = transform.m[15] - transform.m[13];
  7193. frustumPlane.normalize();
  7194. };
  7195. /**
  7196. * Gets the bottom frustum plane transformed by the transform matrix
  7197. * @param transform transformation matrix to be applied to the resulting frustum plane
  7198. * @param frustumPlane the resuling frustum plane
  7199. */
  7200. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7201. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7202. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7203. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7204. frustumPlane.d = transform.m[15] + transform.m[13];
  7205. frustumPlane.normalize();
  7206. };
  7207. /**
  7208. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7209. * @param transform transformation matrix to be applied to the resulting frustum planes
  7210. * @param frustumPlanes the resuling frustum planes
  7211. */
  7212. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7213. // Near
  7214. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7215. // Far
  7216. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7217. // Left
  7218. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7219. // Right
  7220. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7221. // Top
  7222. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7223. // Bottom
  7224. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7225. };
  7226. return Frustum;
  7227. }());
  7228. BABYLON.Frustum = Frustum;
  7229. /** Defines supported spaces */
  7230. var Space;
  7231. (function (Space) {
  7232. /** Local (object) space */
  7233. Space[Space["LOCAL"] = 0] = "LOCAL";
  7234. /** World space */
  7235. Space[Space["WORLD"] = 1] = "WORLD";
  7236. /** Bone space */
  7237. Space[Space["BONE"] = 2] = "BONE";
  7238. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7239. /** Defines the 3 main axes */
  7240. var Axis = /** @class */ (function () {
  7241. function Axis() {
  7242. }
  7243. /** X axis */
  7244. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7245. /** Y axis */
  7246. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7247. /** Z axis */
  7248. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7249. return Axis;
  7250. }());
  7251. BABYLON.Axis = Axis;
  7252. ;
  7253. /** Class used to represent a Bezier curve */
  7254. var BezierCurve = /** @class */ (function () {
  7255. function BezierCurve() {
  7256. }
  7257. /**
  7258. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7259. * @param t defines the time
  7260. * @param x1 defines the left coordinate on X axis
  7261. * @param y1 defines the left coordinate on Y axis
  7262. * @param x2 defines the right coordinate on X axis
  7263. * @param y2 defines the right coordinate on Y axis
  7264. * @returns the interpolated value
  7265. */
  7266. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7267. // Extract X (which is equal to time here)
  7268. var f0 = 1 - 3 * x2 + 3 * x1;
  7269. var f1 = 3 * x2 - 6 * x1;
  7270. var f2 = 3 * x1;
  7271. var refinedT = t;
  7272. for (var i = 0; i < 5; i++) {
  7273. var refinedT2 = refinedT * refinedT;
  7274. var refinedT3 = refinedT2 * refinedT;
  7275. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7276. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7277. refinedT -= (x - t) * slope;
  7278. refinedT = Math.min(1, Math.max(0, refinedT));
  7279. }
  7280. // Resolve cubic bezier for the given x
  7281. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7282. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7283. Math.pow(refinedT, 3);
  7284. };
  7285. return BezierCurve;
  7286. }());
  7287. BABYLON.BezierCurve = BezierCurve;
  7288. /**
  7289. * Defines potential orientation for back face culling
  7290. */
  7291. var Orientation;
  7292. (function (Orientation) {
  7293. /**
  7294. * Clockwise
  7295. */
  7296. Orientation[Orientation["CW"] = 0] = "CW";
  7297. /** Counter clockwise */
  7298. Orientation[Orientation["CCW"] = 1] = "CCW";
  7299. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7300. /**
  7301. * Defines angle representation
  7302. */
  7303. var Angle = /** @class */ (function () {
  7304. /**
  7305. * Creates an Angle object of "radians" radians (float).
  7306. */
  7307. function Angle(radians) {
  7308. this._radians = radians;
  7309. if (this._radians < 0.0)
  7310. this._radians += (2.0 * Math.PI);
  7311. }
  7312. /**
  7313. * Get value in degrees
  7314. * @returns the Angle value in degrees (float)
  7315. */
  7316. Angle.prototype.degrees = function () {
  7317. return this._radians * 180.0 / Math.PI;
  7318. };
  7319. /**
  7320. * Get value in radians
  7321. * @returns the Angle value in radians (float)
  7322. */
  7323. Angle.prototype.radians = function () {
  7324. return this._radians;
  7325. };
  7326. /**
  7327. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7328. * @param a defines first vector
  7329. * @param b defines second vector
  7330. * @returns a new Angle
  7331. */
  7332. Angle.BetweenTwoPoints = function (a, b) {
  7333. var delta = b.subtract(a);
  7334. var theta = Math.atan2(delta.y, delta.x);
  7335. return new Angle(theta);
  7336. };
  7337. /**
  7338. * Gets a new Angle object from the given float in radians
  7339. * @param radians defines the angle value in radians
  7340. * @returns a new Angle
  7341. */
  7342. Angle.FromRadians = function (radians) {
  7343. return new Angle(radians);
  7344. };
  7345. /**
  7346. * Gets a new Angle object from the given float in degrees
  7347. * @param degrees defines the angle value in degrees
  7348. * @returns a new Angle
  7349. */
  7350. Angle.FromDegrees = function (degrees) {
  7351. return new Angle(degrees * Math.PI / 180.0);
  7352. };
  7353. return Angle;
  7354. }());
  7355. BABYLON.Angle = Angle;
  7356. /**
  7357. * This represents an arc in a 2d space.
  7358. */
  7359. var Arc2 = /** @class */ (function () {
  7360. /**
  7361. * Creates an Arc object from the three given points : start, middle and end.
  7362. * @param startPoint Defines the start point of the arc
  7363. * @param midPoint Defines the midlle point of the arc
  7364. * @param endPoint Defines the end point of the arc
  7365. */
  7366. function Arc2(
  7367. /** Defines the start point of the arc */
  7368. startPoint,
  7369. /** Defines the mid point of the arc */
  7370. midPoint,
  7371. /** Defines the end point of the arc */
  7372. endPoint) {
  7373. this.startPoint = startPoint;
  7374. this.midPoint = midPoint;
  7375. this.endPoint = endPoint;
  7376. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7377. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7378. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7379. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7380. 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);
  7381. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7382. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7383. var a1 = this.startAngle.degrees();
  7384. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7385. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7386. // angles correction
  7387. if (a2 - a1 > +180.0)
  7388. a2 -= 360.0;
  7389. if (a2 - a1 < -180.0)
  7390. a2 += 360.0;
  7391. if (a3 - a2 > +180.0)
  7392. a3 -= 360.0;
  7393. if (a3 - a2 < -180.0)
  7394. a3 += 360.0;
  7395. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7396. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7397. }
  7398. return Arc2;
  7399. }());
  7400. BABYLON.Arc2 = Arc2;
  7401. /**
  7402. * Represents a 2D path made up of multiple 2D points
  7403. */
  7404. var Path2 = /** @class */ (function () {
  7405. /**
  7406. * Creates a Path2 object from the starting 2D coordinates x and y.
  7407. * @param x the starting points x value
  7408. * @param y the starting points y value
  7409. */
  7410. function Path2(x, y) {
  7411. this._points = new Array();
  7412. this._length = 0.0;
  7413. /**
  7414. * If the path start and end point are the same
  7415. */
  7416. this.closed = false;
  7417. this._points.push(new Vector2(x, y));
  7418. }
  7419. /**
  7420. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7421. * @param x the added points x value
  7422. * @param y the added points y value
  7423. * @returns the updated Path2.
  7424. */
  7425. Path2.prototype.addLineTo = function (x, y) {
  7426. if (this.closed) {
  7427. return this;
  7428. }
  7429. var newPoint = new Vector2(x, y);
  7430. var previousPoint = this._points[this._points.length - 1];
  7431. this._points.push(newPoint);
  7432. this._length += newPoint.subtract(previousPoint).length();
  7433. return this;
  7434. };
  7435. /**
  7436. * 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.
  7437. * @param midX middle point x value
  7438. * @param midY middle point y value
  7439. * @param endX end point x value
  7440. * @param endY end point y value
  7441. * @param numberOfSegments (default: 36)
  7442. * @returns the updated Path2.
  7443. */
  7444. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7445. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7446. if (this.closed) {
  7447. return this;
  7448. }
  7449. var startPoint = this._points[this._points.length - 1];
  7450. var midPoint = new Vector2(midX, midY);
  7451. var endPoint = new Vector2(endX, endY);
  7452. var arc = new Arc2(startPoint, midPoint, endPoint);
  7453. var increment = arc.angle.radians() / numberOfSegments;
  7454. if (arc.orientation === Orientation.CW)
  7455. increment *= -1;
  7456. var currentAngle = arc.startAngle.radians() + increment;
  7457. for (var i = 0; i < numberOfSegments; i++) {
  7458. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7459. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7460. this.addLineTo(x, y);
  7461. currentAngle += increment;
  7462. }
  7463. return this;
  7464. };
  7465. /**
  7466. * Closes the Path2.
  7467. * @returns the Path2.
  7468. */
  7469. Path2.prototype.close = function () {
  7470. this.closed = true;
  7471. return this;
  7472. };
  7473. /**
  7474. * Gets the sum of the distance between each sequential point in the path
  7475. * @returns the Path2 total length (float).
  7476. */
  7477. Path2.prototype.length = function () {
  7478. var result = this._length;
  7479. if (!this.closed) {
  7480. var lastPoint = this._points[this._points.length - 1];
  7481. var firstPoint = this._points[0];
  7482. result += (firstPoint.subtract(lastPoint).length());
  7483. }
  7484. return result;
  7485. };
  7486. /**
  7487. * Gets the points which construct the path
  7488. * @returns the Path2 internal array of points.
  7489. */
  7490. Path2.prototype.getPoints = function () {
  7491. return this._points;
  7492. };
  7493. /**
  7494. * Retreives the point at the distance aways from the starting point
  7495. * @param normalizedLengthPosition the length along the path to retreive the point from
  7496. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7497. */
  7498. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7499. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7500. return Vector2.Zero();
  7501. }
  7502. var lengthPosition = normalizedLengthPosition * this.length();
  7503. var previousOffset = 0;
  7504. for (var i = 0; i < this._points.length; i++) {
  7505. var j = (i + 1) % this._points.length;
  7506. var a = this._points[i];
  7507. var b = this._points[j];
  7508. var bToA = b.subtract(a);
  7509. var nextOffset = (bToA.length() + previousOffset);
  7510. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7511. var dir = bToA.normalize();
  7512. var localOffset = lengthPosition - previousOffset;
  7513. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7514. }
  7515. previousOffset = nextOffset;
  7516. }
  7517. return Vector2.Zero();
  7518. };
  7519. /**
  7520. * Creates a new path starting from an x and y position
  7521. * @param x starting x value
  7522. * @param y starting y value
  7523. * @returns a new Path2 starting at the coordinates (x, y).
  7524. */
  7525. Path2.StartingAt = function (x, y) {
  7526. return new Path2(x, y);
  7527. };
  7528. return Path2;
  7529. }());
  7530. BABYLON.Path2 = Path2;
  7531. /**
  7532. * Represents a 3D path made up of multiple 3D points
  7533. */
  7534. var Path3D = /** @class */ (function () {
  7535. /**
  7536. * new Path3D(path, normal, raw)
  7537. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7538. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7539. * @param path an array of Vector3, the curve axis of the Path3D
  7540. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7541. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7542. */
  7543. function Path3D(
  7544. /**
  7545. * an array of Vector3, the curve axis of the Path3D
  7546. */
  7547. path, firstNormal, raw) {
  7548. if (firstNormal === void 0) { firstNormal = null; }
  7549. this.path = path;
  7550. this._curve = new Array();
  7551. this._distances = new Array();
  7552. this._tangents = new Array();
  7553. this._normals = new Array();
  7554. this._binormals = new Array();
  7555. for (var p = 0; p < path.length; p++) {
  7556. this._curve[p] = path[p].clone(); // hard copy
  7557. }
  7558. this._raw = raw || false;
  7559. this._compute(firstNormal);
  7560. }
  7561. /**
  7562. * Returns the Path3D array of successive Vector3 designing its curve.
  7563. * @returns the Path3D array of successive Vector3 designing its curve.
  7564. */
  7565. Path3D.prototype.getCurve = function () {
  7566. return this._curve;
  7567. };
  7568. /**
  7569. * Returns an array populated with tangent vectors on each Path3D curve point.
  7570. * @returns an array populated with tangent vectors on each Path3D curve point.
  7571. */
  7572. Path3D.prototype.getTangents = function () {
  7573. return this._tangents;
  7574. };
  7575. /**
  7576. * Returns an array populated with normal vectors on each Path3D curve point.
  7577. * @returns an array populated with normal vectors on each Path3D curve point.
  7578. */
  7579. Path3D.prototype.getNormals = function () {
  7580. return this._normals;
  7581. };
  7582. /**
  7583. * Returns an array populated with binormal vectors on each Path3D curve point.
  7584. * @returns an array populated with binormal vectors on each Path3D curve point.
  7585. */
  7586. Path3D.prototype.getBinormals = function () {
  7587. return this._binormals;
  7588. };
  7589. /**
  7590. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7591. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7592. */
  7593. Path3D.prototype.getDistances = function () {
  7594. return this._distances;
  7595. };
  7596. /**
  7597. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7598. * @param path path which all values are copied into the curves points
  7599. * @param firstNormal which should be projected onto the curve
  7600. * @returns the same object updated.
  7601. */
  7602. Path3D.prototype.update = function (path, firstNormal) {
  7603. if (firstNormal === void 0) { firstNormal = null; }
  7604. for (var p = 0; p < path.length; p++) {
  7605. this._curve[p].x = path[p].x;
  7606. this._curve[p].y = path[p].y;
  7607. this._curve[p].z = path[p].z;
  7608. }
  7609. this._compute(firstNormal);
  7610. return this;
  7611. };
  7612. // private function compute() : computes tangents, normals and binormals
  7613. Path3D.prototype._compute = function (firstNormal) {
  7614. var l = this._curve.length;
  7615. // first and last tangents
  7616. this._tangents[0] = this._getFirstNonNullVector(0);
  7617. if (!this._raw) {
  7618. this._tangents[0].normalize();
  7619. }
  7620. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7621. if (!this._raw) {
  7622. this._tangents[l - 1].normalize();
  7623. }
  7624. // normals and binormals at first point : arbitrary vector with _normalVector()
  7625. var tg0 = this._tangents[0];
  7626. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7627. this._normals[0] = pp0;
  7628. if (!this._raw) {
  7629. this._normals[0].normalize();
  7630. }
  7631. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7632. if (!this._raw) {
  7633. this._binormals[0].normalize();
  7634. }
  7635. this._distances[0] = 0.0;
  7636. // normals and binormals : next points
  7637. var prev; // previous vector (segment)
  7638. var cur; // current vector (segment)
  7639. var curTang; // current tangent
  7640. // previous normal
  7641. var prevBinor; // previous binormal
  7642. for (var i = 1; i < l; i++) {
  7643. // tangents
  7644. prev = this._getLastNonNullVector(i);
  7645. if (i < l - 1) {
  7646. cur = this._getFirstNonNullVector(i);
  7647. this._tangents[i] = prev.add(cur);
  7648. this._tangents[i].normalize();
  7649. }
  7650. this._distances[i] = this._distances[i - 1] + prev.length();
  7651. // normals and binormals
  7652. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7653. curTang = this._tangents[i];
  7654. prevBinor = this._binormals[i - 1];
  7655. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7656. if (!this._raw) {
  7657. this._normals[i].normalize();
  7658. }
  7659. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7660. if (!this._raw) {
  7661. this._binormals[i].normalize();
  7662. }
  7663. }
  7664. };
  7665. // private function getFirstNonNullVector(index)
  7666. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7667. Path3D.prototype._getFirstNonNullVector = function (index) {
  7668. var i = 1;
  7669. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7670. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7671. i++;
  7672. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7673. }
  7674. return nNVector;
  7675. };
  7676. // private function getLastNonNullVector(index)
  7677. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7678. Path3D.prototype._getLastNonNullVector = function (index) {
  7679. var i = 1;
  7680. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7681. while (nLVector.length() === 0 && index > i + 1) {
  7682. i++;
  7683. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7684. }
  7685. return nLVector;
  7686. };
  7687. // private function normalVector(v0, vt, va) :
  7688. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7689. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7690. Path3D.prototype._normalVector = function (v0, vt, va) {
  7691. var normal0;
  7692. var tgl = vt.length();
  7693. if (tgl === 0.0) {
  7694. tgl = 1.0;
  7695. }
  7696. if (va === undefined || va === null) {
  7697. var point;
  7698. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7699. point = new Vector3(0.0, -1.0, 0.0);
  7700. }
  7701. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7702. point = new Vector3(1.0, 0.0, 0.0);
  7703. }
  7704. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7705. point = new Vector3(0.0, 0.0, 1.0);
  7706. }
  7707. else {
  7708. point = Vector3.Zero();
  7709. }
  7710. normal0 = Vector3.Cross(vt, point);
  7711. }
  7712. else {
  7713. normal0 = Vector3.Cross(vt, va);
  7714. Vector3.CrossToRef(normal0, vt, normal0);
  7715. }
  7716. normal0.normalize();
  7717. return normal0;
  7718. };
  7719. return Path3D;
  7720. }());
  7721. BABYLON.Path3D = Path3D;
  7722. /**
  7723. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7724. * A Curve3 is designed from a series of successive Vector3.
  7725. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7726. */
  7727. var Curve3 = /** @class */ (function () {
  7728. /**
  7729. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7730. * A Curve3 is designed from a series of successive Vector3.
  7731. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7732. * @param points points which make up the curve
  7733. */
  7734. function Curve3(points) {
  7735. this._length = 0.0;
  7736. this._points = points;
  7737. this._length = this._computeLength(points);
  7738. }
  7739. /**
  7740. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7741. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7742. * @param v1 (Vector3) the control point
  7743. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7744. * @param nbPoints (integer) the wanted number of points in the curve
  7745. * @returns the created Curve3
  7746. */
  7747. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7748. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7749. var bez = new Array();
  7750. var equation = function (t, val0, val1, val2) {
  7751. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7752. return res;
  7753. };
  7754. for (var i = 0; i <= nbPoints; i++) {
  7755. 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)));
  7756. }
  7757. return new Curve3(bez);
  7758. };
  7759. /**
  7760. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7761. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7762. * @param v1 (Vector3) the first control point
  7763. * @param v2 (Vector3) the second control point
  7764. * @param v3 (Vector3) the end point of the Cubic Bezier
  7765. * @param nbPoints (integer) the wanted number of points in the curve
  7766. * @returns the created Curve3
  7767. */
  7768. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7769. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7770. var bez = new Array();
  7771. var equation = function (t, val0, val1, val2, val3) {
  7772. 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;
  7773. return res;
  7774. };
  7775. for (var i = 0; i <= nbPoints; i++) {
  7776. 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)));
  7777. }
  7778. return new Curve3(bez);
  7779. };
  7780. /**
  7781. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7782. * @param p1 (Vector3) the origin point of the Hermite Spline
  7783. * @param t1 (Vector3) the tangent vector at the origin point
  7784. * @param p2 (Vector3) the end point of the Hermite Spline
  7785. * @param t2 (Vector3) the tangent vector at the end point
  7786. * @param nbPoints (integer) the wanted number of points in the curve
  7787. * @returns the created Curve3
  7788. */
  7789. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7790. var hermite = new Array();
  7791. var step = 1.0 / nbPoints;
  7792. for (var i = 0; i <= nbPoints; i++) {
  7793. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7794. }
  7795. return new Curve3(hermite);
  7796. };
  7797. /**
  7798. * Returns a Curve3 object along a CatmullRom Spline curve :
  7799. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7800. * @param nbPoints (integer) the wanted number of points between each curve control points
  7801. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7802. * @returns the created Curve3
  7803. */
  7804. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7805. var catmullRom = new Array();
  7806. var step = 1.0 / nbPoints;
  7807. var amount = 0.0;
  7808. if (closed) {
  7809. var pointsCount = points.length;
  7810. for (var i = 0; i < pointsCount; i++) {
  7811. amount = 0;
  7812. for (var c = 0; c < nbPoints; c++) {
  7813. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7814. amount += step;
  7815. }
  7816. }
  7817. catmullRom.push(catmullRom[0]);
  7818. }
  7819. else {
  7820. var totalPoints = new Array();
  7821. totalPoints.push(points[0].clone());
  7822. Array.prototype.push.apply(totalPoints, points);
  7823. totalPoints.push(points[points.length - 1].clone());
  7824. for (var i = 0; i < totalPoints.length - 3; i++) {
  7825. amount = 0;
  7826. for (var c = 0; c < nbPoints; c++) {
  7827. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7828. amount += step;
  7829. }
  7830. }
  7831. i--;
  7832. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7833. }
  7834. return new Curve3(catmullRom);
  7835. };
  7836. /**
  7837. * @returns the Curve3 stored array of successive Vector3
  7838. */
  7839. Curve3.prototype.getPoints = function () {
  7840. return this._points;
  7841. };
  7842. /**
  7843. * @returns the computed length (float) of the curve.
  7844. */
  7845. Curve3.prototype.length = function () {
  7846. return this._length;
  7847. };
  7848. /**
  7849. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7850. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7851. * curveA and curveB keep unchanged.
  7852. * @param curve the curve to continue from this curve
  7853. * @returns the newly constructed curve
  7854. */
  7855. Curve3.prototype.continue = function (curve) {
  7856. var lastPoint = this._points[this._points.length - 1];
  7857. var continuedPoints = this._points.slice();
  7858. var curvePoints = curve.getPoints();
  7859. for (var i = 1; i < curvePoints.length; i++) {
  7860. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7861. }
  7862. var continuedCurve = new Curve3(continuedPoints);
  7863. return continuedCurve;
  7864. };
  7865. Curve3.prototype._computeLength = function (path) {
  7866. var l = 0;
  7867. for (var i = 1; i < path.length; i++) {
  7868. l += (path[i].subtract(path[i - 1])).length();
  7869. }
  7870. return l;
  7871. };
  7872. return Curve3;
  7873. }());
  7874. BABYLON.Curve3 = Curve3;
  7875. // Vertex formats
  7876. /**
  7877. * Contains position and normal vectors for a vertex
  7878. */
  7879. var PositionNormalVertex = /** @class */ (function () {
  7880. /**
  7881. * Creates a PositionNormalVertex
  7882. * @param position the position of the vertex (defaut: 0,0,0)
  7883. * @param normal the normal of the vertex (defaut: 0,1,0)
  7884. */
  7885. function PositionNormalVertex(
  7886. /** the position of the vertex (defaut: 0,0,0) */
  7887. position,
  7888. /** the normal of the vertex (defaut: 0,1,0) */
  7889. normal) {
  7890. if (position === void 0) { position = Vector3.Zero(); }
  7891. if (normal === void 0) { normal = Vector3.Up(); }
  7892. this.position = position;
  7893. this.normal = normal;
  7894. }
  7895. /**
  7896. * Clones the PositionNormalVertex
  7897. * @returns the cloned PositionNormalVertex
  7898. */
  7899. PositionNormalVertex.prototype.clone = function () {
  7900. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7901. };
  7902. return PositionNormalVertex;
  7903. }());
  7904. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7905. /**
  7906. * Contains position, normal and uv vectors for a vertex
  7907. */
  7908. var PositionNormalTextureVertex = /** @class */ (function () {
  7909. /**
  7910. * Creates a PositionNormalTextureVertex
  7911. * @param position the position of the vertex (defaut: 0,0,0)
  7912. * @param normal the normal of the vertex (defaut: 0,1,0)
  7913. * @param uv the uv of the vertex (default: 0,0)
  7914. */
  7915. function PositionNormalTextureVertex(
  7916. /** the position of the vertex (defaut: 0,0,0) */
  7917. position,
  7918. /** the normal of the vertex (defaut: 0,1,0) */
  7919. normal,
  7920. /** the uv of the vertex (default: 0,0) */
  7921. uv) {
  7922. if (position === void 0) { position = Vector3.Zero(); }
  7923. if (normal === void 0) { normal = Vector3.Up(); }
  7924. if (uv === void 0) { uv = Vector2.Zero(); }
  7925. this.position = position;
  7926. this.normal = normal;
  7927. this.uv = uv;
  7928. }
  7929. /**
  7930. * Clones the PositionNormalTextureVertex
  7931. * @returns the cloned PositionNormalTextureVertex
  7932. */
  7933. PositionNormalTextureVertex.prototype.clone = function () {
  7934. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7935. };
  7936. return PositionNormalTextureVertex;
  7937. }());
  7938. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7939. // Temporary pre-allocated objects for engine internal use
  7940. // usage in any internal function :
  7941. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7942. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7943. /**
  7944. * @hidden
  7945. */
  7946. var Tmp = /** @class */ (function () {
  7947. function Tmp() {
  7948. }
  7949. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7950. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7951. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7952. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7953. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7954. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7955. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7956. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7957. Matrix.Zero(), Matrix.Zero(),
  7958. Matrix.Zero(), Matrix.Zero(),
  7959. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7960. return Tmp;
  7961. }());
  7962. BABYLON.Tmp = Tmp;
  7963. /**
  7964. * @hidden
  7965. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7966. */
  7967. var MathTmp = /** @class */ (function () {
  7968. function MathTmp() {
  7969. }
  7970. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7971. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7972. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7973. return MathTmp;
  7974. }());
  7975. })(BABYLON || (BABYLON = {}));
  7976. //# sourceMappingURL=babylon.math.js.map
  7977. var BABYLON;
  7978. (function (BABYLON) {
  7979. var Scalar = /** @class */ (function () {
  7980. function Scalar() {
  7981. }
  7982. /**
  7983. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7984. */
  7985. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7986. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7987. var num = a - b;
  7988. return -epsilon <= num && num <= epsilon;
  7989. };
  7990. /**
  7991. * Returns a string : the upper case translation of the number i to hexadecimal.
  7992. */
  7993. Scalar.ToHex = function (i) {
  7994. var str = i.toString(16);
  7995. if (i <= 15) {
  7996. return ("0" + str).toUpperCase();
  7997. }
  7998. return str.toUpperCase();
  7999. };
  8000. /**
  8001. * Returns -1 if value is negative and +1 is value is positive.
  8002. * Returns the value itself if it's equal to zero.
  8003. */
  8004. Scalar.Sign = function (value) {
  8005. value = +value; // convert to a number
  8006. if (value === 0 || isNaN(value))
  8007. return value;
  8008. return value > 0 ? 1 : -1;
  8009. };
  8010. /**
  8011. * Returns the value itself if it's between min and max.
  8012. * Returns min if the value is lower than min.
  8013. * Returns max if the value is greater than max.
  8014. */
  8015. Scalar.Clamp = function (value, min, max) {
  8016. if (min === void 0) { min = 0; }
  8017. if (max === void 0) { max = 1; }
  8018. return Math.min(max, Math.max(min, value));
  8019. };
  8020. /**
  8021. * Returns the log2 of value.
  8022. */
  8023. Scalar.Log2 = function (value) {
  8024. return Math.log(value) * Math.LOG2E;
  8025. };
  8026. /**
  8027. * Loops the value, so that it is never larger than length and never smaller than 0.
  8028. *
  8029. * This is similar to the modulo operator but it works with floating point numbers.
  8030. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8031. * With t = 5 and length = 2.5, the result would be 0.0.
  8032. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8033. */
  8034. Scalar.Repeat = function (value, length) {
  8035. return value - Math.floor(value / length) * length;
  8036. };
  8037. /**
  8038. * Normalize the value between 0.0 and 1.0 using min and max values
  8039. */
  8040. Scalar.Normalize = function (value, min, max) {
  8041. return (value - min) / (max - min);
  8042. };
  8043. /**
  8044. * Denormalize the value from 0.0 and 1.0 using min and max values
  8045. */
  8046. Scalar.Denormalize = function (normalized, min, max) {
  8047. return (normalized * (max - min) + min);
  8048. };
  8049. /**
  8050. * Calculates the shortest difference between two given angles given in degrees.
  8051. */
  8052. Scalar.DeltaAngle = function (current, target) {
  8053. var num = Scalar.Repeat(target - current, 360.0);
  8054. if (num > 180.0) {
  8055. num -= 360.0;
  8056. }
  8057. return num;
  8058. };
  8059. /**
  8060. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8061. *
  8062. * The returned value will move back and forth between 0 and length
  8063. */
  8064. Scalar.PingPong = function (tx, length) {
  8065. var t = Scalar.Repeat(tx, length * 2.0);
  8066. return length - Math.abs(t - length);
  8067. };
  8068. /**
  8069. * Interpolates between min and max with smoothing at the limits.
  8070. *
  8071. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8072. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8073. */
  8074. Scalar.SmoothStep = function (from, to, tx) {
  8075. var t = Scalar.Clamp(tx);
  8076. t = -2.0 * t * t * t + 3.0 * t * t;
  8077. return to * t + from * (1.0 - t);
  8078. };
  8079. /**
  8080. * Moves a value current towards target.
  8081. *
  8082. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8083. * Negative values of maxDelta pushes the value away from target.
  8084. */
  8085. Scalar.MoveTowards = function (current, target, maxDelta) {
  8086. var result = 0;
  8087. if (Math.abs(target - current) <= maxDelta) {
  8088. result = target;
  8089. }
  8090. else {
  8091. result = current + Scalar.Sign(target - current) * maxDelta;
  8092. }
  8093. return result;
  8094. };
  8095. /**
  8096. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8097. *
  8098. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8099. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8100. */
  8101. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8102. var num = Scalar.DeltaAngle(current, target);
  8103. var result = 0;
  8104. if (-maxDelta < num && num < maxDelta) {
  8105. result = target;
  8106. }
  8107. else {
  8108. target = current + num;
  8109. result = Scalar.MoveTowards(current, target, maxDelta);
  8110. }
  8111. return result;
  8112. };
  8113. /**
  8114. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8115. */
  8116. Scalar.Lerp = function (start, end, amount) {
  8117. return start + ((end - start) * amount);
  8118. };
  8119. /**
  8120. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8121. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8122. */
  8123. Scalar.LerpAngle = function (start, end, amount) {
  8124. var num = Scalar.Repeat(end - start, 360.0);
  8125. if (num > 180.0) {
  8126. num -= 360.0;
  8127. }
  8128. return start + num * Scalar.Clamp(amount);
  8129. };
  8130. /**
  8131. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8132. */
  8133. Scalar.InverseLerp = function (a, b, value) {
  8134. var result = 0;
  8135. if (a != b) {
  8136. result = Scalar.Clamp((value - a) / (b - a));
  8137. }
  8138. else {
  8139. result = 0.0;
  8140. }
  8141. return result;
  8142. };
  8143. /**
  8144. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8145. */
  8146. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8147. var squared = amount * amount;
  8148. var cubed = amount * squared;
  8149. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8150. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8151. var part3 = (cubed - (2.0 * squared)) + amount;
  8152. var part4 = cubed - squared;
  8153. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8154. };
  8155. /**
  8156. * Returns a random float number between and min and max values
  8157. */
  8158. Scalar.RandomRange = function (min, max) {
  8159. if (min === max)
  8160. return min;
  8161. return ((Math.random() * (max - min)) + min);
  8162. };
  8163. /**
  8164. * This function returns percentage of a number in a given range.
  8165. *
  8166. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8167. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8168. */
  8169. Scalar.RangeToPercent = function (number, min, max) {
  8170. return ((number - min) / (max - min));
  8171. };
  8172. /**
  8173. * This function returns number that corresponds to the percentage in a given range.
  8174. *
  8175. * PercentToRange(0.34,0,100) will return 34.
  8176. */
  8177. Scalar.PercentToRange = function (percent, min, max) {
  8178. return ((max - min) * percent + min);
  8179. };
  8180. /**
  8181. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8182. * @param angle The angle to normalize in radian.
  8183. * @return The converted angle.
  8184. */
  8185. Scalar.NormalizeRadians = function (angle) {
  8186. // More precise but slower version kept for reference.
  8187. // angle = angle % Tools.TwoPi;
  8188. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8189. //if (angle > Math.PI) {
  8190. // angle -= Tools.TwoPi;
  8191. //}
  8192. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8193. return angle;
  8194. };
  8195. /**
  8196. * Two pi constants convenient for computation.
  8197. */
  8198. Scalar.TwoPi = Math.PI * 2;
  8199. return Scalar;
  8200. }());
  8201. BABYLON.Scalar = Scalar;
  8202. })(BABYLON || (BABYLON = {}));
  8203. //# sourceMappingURL=babylon.math.scalar.js.map
  8204. //# sourceMappingURL=babylon.mixins.js.map
  8205. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8206. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8207. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8208. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8209. //# sourceMappingURL=babylon.webgl2.js.map
  8210. var BABYLON;
  8211. (function (BABYLON) {
  8212. var __decoratorInitialStore = {};
  8213. var __mergedStore = {};
  8214. var _copySource = function (creationFunction, source, instanciate) {
  8215. var destination = creationFunction();
  8216. // Tags
  8217. if (BABYLON.Tags) {
  8218. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8219. }
  8220. var classStore = getMergedStore(destination);
  8221. // Properties
  8222. for (var property in classStore) {
  8223. var propertyDescriptor = classStore[property];
  8224. var sourceProperty = source[property];
  8225. var propertyType = propertyDescriptor.type;
  8226. if (sourceProperty !== undefined && sourceProperty !== null) {
  8227. switch (propertyType) {
  8228. case 0: // Value
  8229. case 6: // Mesh reference
  8230. case 11: // Camera reference
  8231. destination[property] = sourceProperty;
  8232. break;
  8233. case 1: // Texture
  8234. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8235. break;
  8236. case 2: // Color3
  8237. case 3: // FresnelParameters
  8238. case 4: // Vector2
  8239. case 5: // Vector3
  8240. case 7: // Color Curves
  8241. case 10: // Quaternion
  8242. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8243. break;
  8244. }
  8245. }
  8246. }
  8247. return destination;
  8248. };
  8249. function getDirectStore(target) {
  8250. var classKey = target.getClassName();
  8251. if (!__decoratorInitialStore[classKey]) {
  8252. __decoratorInitialStore[classKey] = {};
  8253. }
  8254. return __decoratorInitialStore[classKey];
  8255. }
  8256. /**
  8257. * Return the list of properties flagged as serializable
  8258. * @param target: host object
  8259. */
  8260. function getMergedStore(target) {
  8261. var classKey = target.getClassName();
  8262. if (__mergedStore[classKey]) {
  8263. return __mergedStore[classKey];
  8264. }
  8265. __mergedStore[classKey] = {};
  8266. var store = __mergedStore[classKey];
  8267. var currentTarget = target;
  8268. var currentKey = classKey;
  8269. while (currentKey) {
  8270. var initialStore = __decoratorInitialStore[currentKey];
  8271. for (var property in initialStore) {
  8272. store[property] = initialStore[property];
  8273. }
  8274. var parent_1 = void 0;
  8275. var done = false;
  8276. do {
  8277. parent_1 = Object.getPrototypeOf(currentTarget);
  8278. if (!parent_1.getClassName) {
  8279. done = true;
  8280. break;
  8281. }
  8282. if (parent_1.getClassName() !== currentKey) {
  8283. break;
  8284. }
  8285. currentTarget = parent_1;
  8286. } while (parent_1);
  8287. if (done) {
  8288. break;
  8289. }
  8290. currentKey = parent_1.getClassName();
  8291. currentTarget = parent_1;
  8292. }
  8293. return store;
  8294. }
  8295. function generateSerializableMember(type, sourceName) {
  8296. return function (target, propertyKey) {
  8297. var classStore = getDirectStore(target);
  8298. if (!classStore[propertyKey]) {
  8299. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8300. }
  8301. };
  8302. }
  8303. function generateExpandMember(setCallback, targetKey) {
  8304. if (targetKey === void 0) { targetKey = null; }
  8305. return function (target, propertyKey) {
  8306. var key = targetKey || ("_" + propertyKey);
  8307. Object.defineProperty(target, propertyKey, {
  8308. get: function () {
  8309. return this[key];
  8310. },
  8311. set: function (value) {
  8312. if (this[key] === value) {
  8313. return;
  8314. }
  8315. this[key] = value;
  8316. target[setCallback].apply(this);
  8317. },
  8318. enumerable: true,
  8319. configurable: true
  8320. });
  8321. };
  8322. }
  8323. function expandToProperty(callback, targetKey) {
  8324. if (targetKey === void 0) { targetKey = null; }
  8325. return generateExpandMember(callback, targetKey);
  8326. }
  8327. BABYLON.expandToProperty = expandToProperty;
  8328. function serialize(sourceName) {
  8329. return generateSerializableMember(0, sourceName); // value member
  8330. }
  8331. BABYLON.serialize = serialize;
  8332. function serializeAsTexture(sourceName) {
  8333. return generateSerializableMember(1, sourceName); // texture member
  8334. }
  8335. BABYLON.serializeAsTexture = serializeAsTexture;
  8336. function serializeAsColor3(sourceName) {
  8337. return generateSerializableMember(2, sourceName); // color3 member
  8338. }
  8339. BABYLON.serializeAsColor3 = serializeAsColor3;
  8340. function serializeAsFresnelParameters(sourceName) {
  8341. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8342. }
  8343. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8344. function serializeAsVector2(sourceName) {
  8345. return generateSerializableMember(4, sourceName); // vector2 member
  8346. }
  8347. BABYLON.serializeAsVector2 = serializeAsVector2;
  8348. function serializeAsVector3(sourceName) {
  8349. return generateSerializableMember(5, sourceName); // vector3 member
  8350. }
  8351. BABYLON.serializeAsVector3 = serializeAsVector3;
  8352. function serializeAsMeshReference(sourceName) {
  8353. return generateSerializableMember(6, sourceName); // mesh reference member
  8354. }
  8355. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8356. function serializeAsColorCurves(sourceName) {
  8357. return generateSerializableMember(7, sourceName); // color curves
  8358. }
  8359. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8360. function serializeAsColor4(sourceName) {
  8361. return generateSerializableMember(8, sourceName); // color 4
  8362. }
  8363. BABYLON.serializeAsColor4 = serializeAsColor4;
  8364. function serializeAsImageProcessingConfiguration(sourceName) {
  8365. return generateSerializableMember(9, sourceName); // image processing
  8366. }
  8367. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8368. function serializeAsQuaternion(sourceName) {
  8369. return generateSerializableMember(10, sourceName); // quaternion member
  8370. }
  8371. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8372. /**
  8373. * Decorator used to define property that can be serialized as reference to a camera
  8374. * @param sourceName defines the name of the property to decorate
  8375. */
  8376. function serializeAsCameraReference(sourceName) {
  8377. return generateSerializableMember(11, sourceName); // camera reference member
  8378. }
  8379. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8380. var SerializationHelper = /** @class */ (function () {
  8381. function SerializationHelper() {
  8382. }
  8383. SerializationHelper.Serialize = function (entity, serializationObject) {
  8384. if (!serializationObject) {
  8385. serializationObject = {};
  8386. }
  8387. // Tags
  8388. if (BABYLON.Tags) {
  8389. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8390. }
  8391. var serializedProperties = getMergedStore(entity);
  8392. // Properties
  8393. for (var property in serializedProperties) {
  8394. var propertyDescriptor = serializedProperties[property];
  8395. var targetPropertyName = propertyDescriptor.sourceName || property;
  8396. var propertyType = propertyDescriptor.type;
  8397. var sourceProperty = entity[property];
  8398. if (sourceProperty !== undefined && sourceProperty !== null) {
  8399. switch (propertyType) {
  8400. case 0: // Value
  8401. serializationObject[targetPropertyName] = sourceProperty;
  8402. break;
  8403. case 1: // Texture
  8404. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8405. break;
  8406. case 2: // Color3
  8407. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8408. break;
  8409. case 3: // FresnelParameters
  8410. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8411. break;
  8412. case 4: // Vector2
  8413. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8414. break;
  8415. case 5: // Vector3
  8416. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8417. break;
  8418. case 6: // Mesh reference
  8419. serializationObject[targetPropertyName] = sourceProperty.id;
  8420. break;
  8421. case 7: // Color Curves
  8422. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8423. break;
  8424. case 8: // Color 4
  8425. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8426. break;
  8427. case 9: // Image Processing
  8428. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8429. break;
  8430. case 10: // Quaternion
  8431. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8432. break;
  8433. case 11: // Camera reference
  8434. serializationObject[targetPropertyName] = sourceProperty.id;
  8435. break;
  8436. }
  8437. }
  8438. }
  8439. return serializationObject;
  8440. };
  8441. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8442. if (rootUrl === void 0) { rootUrl = null; }
  8443. var destination = creationFunction();
  8444. if (!rootUrl) {
  8445. rootUrl = "";
  8446. }
  8447. // Tags
  8448. if (BABYLON.Tags) {
  8449. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8450. }
  8451. var classStore = getMergedStore(destination);
  8452. // Properties
  8453. for (var property in classStore) {
  8454. var propertyDescriptor = classStore[property];
  8455. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8456. var propertyType = propertyDescriptor.type;
  8457. if (sourceProperty !== undefined && sourceProperty !== null) {
  8458. var dest = destination;
  8459. switch (propertyType) {
  8460. case 0: // Value
  8461. dest[property] = sourceProperty;
  8462. break;
  8463. case 1: // Texture
  8464. if (scene) {
  8465. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8466. }
  8467. break;
  8468. case 2: // Color3
  8469. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8470. break;
  8471. case 3: // FresnelParameters
  8472. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8473. break;
  8474. case 4: // Vector2
  8475. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8476. break;
  8477. case 5: // Vector3
  8478. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8479. break;
  8480. case 6: // Mesh reference
  8481. if (scene) {
  8482. dest[property] = scene.getLastMeshByID(sourceProperty);
  8483. }
  8484. break;
  8485. case 7: // Color Curves
  8486. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8487. break;
  8488. case 8: // Color 4
  8489. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8490. break;
  8491. case 9: // Image Processing
  8492. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8493. break;
  8494. case 10: // Quaternion
  8495. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8496. break;
  8497. case 11: // Camera reference
  8498. if (scene) {
  8499. dest[property] = scene.getCameraByID(sourceProperty);
  8500. }
  8501. break;
  8502. }
  8503. }
  8504. }
  8505. return destination;
  8506. };
  8507. SerializationHelper.Clone = function (creationFunction, source) {
  8508. return _copySource(creationFunction, source, false);
  8509. };
  8510. SerializationHelper.Instanciate = function (creationFunction, source) {
  8511. return _copySource(creationFunction, source, true);
  8512. };
  8513. return SerializationHelper;
  8514. }());
  8515. BABYLON.SerializationHelper = SerializationHelper;
  8516. })(BABYLON || (BABYLON = {}));
  8517. //# sourceMappingURL=babylon.decorators.js.map
  8518. var BABYLON;
  8519. (function (BABYLON) {
  8520. /**
  8521. * Wrapper class for promise with external resolve and reject.
  8522. */
  8523. var Deferred = /** @class */ (function () {
  8524. /**
  8525. * Constructor for this deferred object.
  8526. */
  8527. function Deferred() {
  8528. var _this = this;
  8529. this.promise = new Promise(function (resolve, reject) {
  8530. _this._resolve = resolve;
  8531. _this._reject = reject;
  8532. });
  8533. }
  8534. Object.defineProperty(Deferred.prototype, "resolve", {
  8535. /**
  8536. * The resolve method of the promise associated with this deferred object.
  8537. */
  8538. get: function () {
  8539. return this._resolve;
  8540. },
  8541. enumerable: true,
  8542. configurable: true
  8543. });
  8544. Object.defineProperty(Deferred.prototype, "reject", {
  8545. /**
  8546. * The reject method of the promise associated with this deferred object.
  8547. */
  8548. get: function () {
  8549. return this._reject;
  8550. },
  8551. enumerable: true,
  8552. configurable: true
  8553. });
  8554. return Deferred;
  8555. }());
  8556. BABYLON.Deferred = Deferred;
  8557. })(BABYLON || (BABYLON = {}));
  8558. //# sourceMappingURL=babylon.deferred.js.map
  8559. var BABYLON;
  8560. (function (BABYLON) {
  8561. /**
  8562. * A class serves as a medium between the observable and its observers
  8563. */
  8564. var EventState = /** @class */ (function () {
  8565. /**
  8566. * Create a new EventState
  8567. * @param mask defines the mask associated with this state
  8568. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8569. * @param target defines the original target of the state
  8570. * @param currentTarget defines the current target of the state
  8571. */
  8572. function EventState(mask, skipNextObservers, target, currentTarget) {
  8573. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8574. this.initalize(mask, skipNextObservers, target, currentTarget);
  8575. }
  8576. /**
  8577. * Initialize the current event state
  8578. * @param mask defines the mask associated with this state
  8579. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8580. * @param target defines the original target of the state
  8581. * @param currentTarget defines the current target of the state
  8582. * @returns the current event state
  8583. */
  8584. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8585. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8586. this.mask = mask;
  8587. this.skipNextObservers = skipNextObservers;
  8588. this.target = target;
  8589. this.currentTarget = currentTarget;
  8590. return this;
  8591. };
  8592. return EventState;
  8593. }());
  8594. BABYLON.EventState = EventState;
  8595. /**
  8596. * Represent an Observer registered to a given Observable object.
  8597. */
  8598. var Observer = /** @class */ (function () {
  8599. /**
  8600. * Creates a new observer
  8601. * @param callback defines the callback to call when the observer is notified
  8602. * @param mask defines the mask of the observer (used to filter notifications)
  8603. * @param scope defines the current scope used to restore the JS context
  8604. */
  8605. function Observer(
  8606. /**
  8607. * Defines the callback to call when the observer is notified
  8608. */
  8609. callback,
  8610. /**
  8611. * Defines the mask of the observer (used to filter notifications)
  8612. */
  8613. mask,
  8614. /**
  8615. * Defines the current scope used to restore the JS context
  8616. */
  8617. scope) {
  8618. if (scope === void 0) { scope = null; }
  8619. this.callback = callback;
  8620. this.mask = mask;
  8621. this.scope = scope;
  8622. /** @hidden */
  8623. this._willBeUnregistered = false;
  8624. /**
  8625. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8626. */
  8627. this.unregisterOnNextCall = false;
  8628. }
  8629. return Observer;
  8630. }());
  8631. BABYLON.Observer = Observer;
  8632. /**
  8633. * Represent a list of observers registered to multiple Observables object.
  8634. */
  8635. var MultiObserver = /** @class */ (function () {
  8636. function MultiObserver() {
  8637. }
  8638. /**
  8639. * Release associated resources
  8640. */
  8641. MultiObserver.prototype.dispose = function () {
  8642. if (this._observers && this._observables) {
  8643. for (var index = 0; index < this._observers.length; index++) {
  8644. this._observables[index].remove(this._observers[index]);
  8645. }
  8646. }
  8647. this._observers = null;
  8648. this._observables = null;
  8649. };
  8650. /**
  8651. * Raise a callback when one of the observable will notify
  8652. * @param observables defines a list of observables to watch
  8653. * @param callback defines the callback to call on notification
  8654. * @param mask defines the mask used to filter notifications
  8655. * @param scope defines the current scope used to restore the JS context
  8656. * @returns the new MultiObserver
  8657. */
  8658. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8659. if (mask === void 0) { mask = -1; }
  8660. if (scope === void 0) { scope = null; }
  8661. var result = new MultiObserver();
  8662. result._observers = new Array();
  8663. result._observables = observables;
  8664. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8665. var observable = observables_1[_i];
  8666. var observer = observable.add(callback, mask, false, scope);
  8667. if (observer) {
  8668. result._observers.push(observer);
  8669. }
  8670. }
  8671. return result;
  8672. };
  8673. return MultiObserver;
  8674. }());
  8675. BABYLON.MultiObserver = MultiObserver;
  8676. /**
  8677. * The Observable class is a simple implementation of the Observable pattern.
  8678. *
  8679. * 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.
  8680. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8681. * 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).
  8682. * 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.
  8683. */
  8684. var Observable = /** @class */ (function () {
  8685. /**
  8686. * Creates a new observable
  8687. * @param onObserverAdded defines a callback to call when a new observer is added
  8688. */
  8689. function Observable(onObserverAdded) {
  8690. this._observers = new Array();
  8691. this._eventState = new EventState(0);
  8692. if (onObserverAdded) {
  8693. this._onObserverAdded = onObserverAdded;
  8694. }
  8695. }
  8696. /**
  8697. * Create a new Observer with the specified callback
  8698. * @param callback the callback that will be executed for that Observer
  8699. * @param mask the mask used to filter observers
  8700. * @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.
  8701. * @param scope optional scope for the callback to be called from
  8702. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8703. * @returns the new observer created for the callback
  8704. */
  8705. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8706. if (mask === void 0) { mask = -1; }
  8707. if (insertFirst === void 0) { insertFirst = false; }
  8708. if (scope === void 0) { scope = null; }
  8709. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8710. if (!callback) {
  8711. return null;
  8712. }
  8713. var observer = new Observer(callback, mask, scope);
  8714. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8715. if (insertFirst) {
  8716. this._observers.unshift(observer);
  8717. }
  8718. else {
  8719. this._observers.push(observer);
  8720. }
  8721. if (this._onObserverAdded) {
  8722. this._onObserverAdded(observer);
  8723. }
  8724. return observer;
  8725. };
  8726. /**
  8727. * Create a new Observer with the specified callback and unregisters after the next notification
  8728. * @param callback the callback that will be executed for that Observer
  8729. * @returns the new observer created for the callback
  8730. */
  8731. Observable.prototype.addOnce = function (callback) {
  8732. return this.add(callback, undefined, undefined, undefined, true);
  8733. };
  8734. /**
  8735. * Remove an Observer from the Observable object
  8736. * @param observer the instance of the Observer to remove
  8737. * @returns false if it doesn't belong to this Observable
  8738. */
  8739. Observable.prototype.remove = function (observer) {
  8740. if (!observer) {
  8741. return false;
  8742. }
  8743. var index = this._observers.indexOf(observer);
  8744. if (index !== -1) {
  8745. this._deferUnregister(observer);
  8746. return true;
  8747. }
  8748. return false;
  8749. };
  8750. /**
  8751. * Remove a callback from the Observable object
  8752. * @param callback the callback to remove
  8753. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8754. * @returns false if it doesn't belong to this Observable
  8755. */
  8756. Observable.prototype.removeCallback = function (callback, scope) {
  8757. for (var index = 0; index < this._observers.length; index++) {
  8758. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8759. this._deferUnregister(this._observers[index]);
  8760. return true;
  8761. }
  8762. }
  8763. return false;
  8764. };
  8765. Observable.prototype._deferUnregister = function (observer) {
  8766. var _this = this;
  8767. observer.unregisterOnNextCall = false;
  8768. observer._willBeUnregistered = true;
  8769. BABYLON.Tools.SetImmediate(function () {
  8770. _this._remove(observer);
  8771. });
  8772. };
  8773. // This should only be called when not iterating over _observers to avoid callback skipping.
  8774. // Removes an observer from the _observer Array.
  8775. Observable.prototype._remove = function (observer) {
  8776. if (!observer) {
  8777. return false;
  8778. }
  8779. var index = this._observers.indexOf(observer);
  8780. if (index !== -1) {
  8781. this._observers.splice(index, 1);
  8782. return true;
  8783. }
  8784. return false;
  8785. };
  8786. /**
  8787. * Notify all Observers by calling their respective callback with the given data
  8788. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8789. * @param eventData defines the data to send to all observers
  8790. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8791. * @param target defines the original target of the state
  8792. * @param currentTarget defines the current target of the state
  8793. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8794. */
  8795. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8796. if (mask === void 0) { mask = -1; }
  8797. if (!this._observers.length) {
  8798. return true;
  8799. }
  8800. var state = this._eventState;
  8801. state.mask = mask;
  8802. state.target = target;
  8803. state.currentTarget = currentTarget;
  8804. state.skipNextObservers = false;
  8805. state.lastReturnValue = eventData;
  8806. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8807. var obs = _a[_i];
  8808. if (obs._willBeUnregistered) {
  8809. continue;
  8810. }
  8811. if (obs.mask & mask) {
  8812. if (obs.scope) {
  8813. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8814. }
  8815. else {
  8816. state.lastReturnValue = obs.callback(eventData, state);
  8817. }
  8818. if (obs.unregisterOnNextCall) {
  8819. this._deferUnregister(obs);
  8820. }
  8821. }
  8822. if (state.skipNextObservers) {
  8823. return false;
  8824. }
  8825. }
  8826. return true;
  8827. };
  8828. /**
  8829. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8830. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8831. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8832. * and it is crucial that all callbacks will be executed.
  8833. * The order of the callbacks is kept, callbacks are not executed parallel.
  8834. *
  8835. * @param eventData The data to be sent to each callback
  8836. * @param mask is used to filter observers defaults to -1
  8837. * @param target defines the callback target (see EventState)
  8838. * @param currentTarget defines he current object in the bubbling phase
  8839. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8840. */
  8841. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8842. var _this = this;
  8843. if (mask === void 0) { mask = -1; }
  8844. // create an empty promise
  8845. var p = Promise.resolve(eventData);
  8846. // no observers? return this promise.
  8847. if (!this._observers.length) {
  8848. return p;
  8849. }
  8850. var state = this._eventState;
  8851. state.mask = mask;
  8852. state.target = target;
  8853. state.currentTarget = currentTarget;
  8854. state.skipNextObservers = false;
  8855. // execute one callback after another (not using Promise.all, the order is important)
  8856. this._observers.forEach(function (obs) {
  8857. if (state.skipNextObservers) {
  8858. return;
  8859. }
  8860. if (obs._willBeUnregistered) {
  8861. return;
  8862. }
  8863. if (obs.mask & mask) {
  8864. if (obs.scope) {
  8865. p = p.then(function (lastReturnedValue) {
  8866. state.lastReturnValue = lastReturnedValue;
  8867. return obs.callback.apply(obs.scope, [eventData, state]);
  8868. });
  8869. }
  8870. else {
  8871. p = p.then(function (lastReturnedValue) {
  8872. state.lastReturnValue = lastReturnedValue;
  8873. return obs.callback(eventData, state);
  8874. });
  8875. }
  8876. if (obs.unregisterOnNextCall) {
  8877. _this._deferUnregister(obs);
  8878. }
  8879. }
  8880. });
  8881. // return the eventData
  8882. return p.then(function () { return eventData; });
  8883. };
  8884. /**
  8885. * Notify a specific observer
  8886. * @param observer defines the observer to notify
  8887. * @param eventData defines the data to be sent to each callback
  8888. * @param mask is used to filter observers defaults to -1
  8889. */
  8890. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8891. if (mask === void 0) { mask = -1; }
  8892. var state = this._eventState;
  8893. state.mask = mask;
  8894. state.skipNextObservers = false;
  8895. observer.callback(eventData, state);
  8896. };
  8897. /**
  8898. * Gets a boolean indicating if the observable has at least one observer
  8899. * @returns true is the Observable has at least one Observer registered
  8900. */
  8901. Observable.prototype.hasObservers = function () {
  8902. return this._observers.length > 0;
  8903. };
  8904. /**
  8905. * Clear the list of observers
  8906. */
  8907. Observable.prototype.clear = function () {
  8908. this._observers = new Array();
  8909. this._onObserverAdded = null;
  8910. };
  8911. /**
  8912. * Clone the current observable
  8913. * @returns a new observable
  8914. */
  8915. Observable.prototype.clone = function () {
  8916. var result = new Observable();
  8917. result._observers = this._observers.slice(0);
  8918. return result;
  8919. };
  8920. /**
  8921. * Does this observable handles observer registered with a given mask
  8922. * @param mask defines the mask to be tested
  8923. * @return whether or not one observer registered with the given mask is handeled
  8924. **/
  8925. Observable.prototype.hasSpecificMask = function (mask) {
  8926. if (mask === void 0) { mask = -1; }
  8927. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8928. var obs = _a[_i];
  8929. if (obs.mask & mask || obs.mask === mask) {
  8930. return true;
  8931. }
  8932. }
  8933. return false;
  8934. };
  8935. return Observable;
  8936. }());
  8937. BABYLON.Observable = Observable;
  8938. })(BABYLON || (BABYLON = {}));
  8939. //# sourceMappingURL=babylon.observable.js.map
  8940. var BABYLON;
  8941. (function (BABYLON) {
  8942. /**
  8943. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8944. */
  8945. var SmartArray = /** @class */ (function () {
  8946. /**
  8947. * Instantiates a Smart Array.
  8948. * @param capacity defines the default capacity of the array.
  8949. */
  8950. function SmartArray(capacity) {
  8951. /**
  8952. * The active length of the array.
  8953. */
  8954. this.length = 0;
  8955. this.data = new Array(capacity);
  8956. this._id = SmartArray._GlobalId++;
  8957. }
  8958. /**
  8959. * Pushes a value at the end of the active data.
  8960. * @param value defines the object to push in the array.
  8961. */
  8962. SmartArray.prototype.push = function (value) {
  8963. this.data[this.length++] = value;
  8964. if (this.length > this.data.length) {
  8965. this.data.length *= 2;
  8966. }
  8967. };
  8968. /**
  8969. * Iterates over the active data and apply the lambda to them.
  8970. * @param func defines the action to apply on each value.
  8971. */
  8972. SmartArray.prototype.forEach = function (func) {
  8973. for (var index = 0; index < this.length; index++) {
  8974. func(this.data[index]);
  8975. }
  8976. };
  8977. /**
  8978. * Sorts the full sets of data.
  8979. * @param compareFn defines the comparison function to apply.
  8980. */
  8981. SmartArray.prototype.sort = function (compareFn) {
  8982. this.data.sort(compareFn);
  8983. };
  8984. /**
  8985. * Resets the active data to an empty array.
  8986. */
  8987. SmartArray.prototype.reset = function () {
  8988. this.length = 0;
  8989. };
  8990. /**
  8991. * Releases all the data from the array as well as the array.
  8992. */
  8993. SmartArray.prototype.dispose = function () {
  8994. this.reset();
  8995. if (this.data) {
  8996. this.data.length = 0;
  8997. this.data = [];
  8998. }
  8999. };
  9000. /**
  9001. * Concats the active data with a given array.
  9002. * @param array defines the data to concatenate with.
  9003. */
  9004. SmartArray.prototype.concat = function (array) {
  9005. if (array.length === 0) {
  9006. return;
  9007. }
  9008. if (this.length + array.length > this.data.length) {
  9009. this.data.length = (this.length + array.length) * 2;
  9010. }
  9011. for (var index = 0; index < array.length; index++) {
  9012. this.data[this.length++] = (array.data || array)[index];
  9013. }
  9014. };
  9015. /**
  9016. * Returns the position of a value in the active data.
  9017. * @param value defines the value to find the index for
  9018. * @returns the index if found in the active data otherwise -1
  9019. */
  9020. SmartArray.prototype.indexOf = function (value) {
  9021. var position = this.data.indexOf(value);
  9022. if (position >= this.length) {
  9023. return -1;
  9024. }
  9025. return position;
  9026. };
  9027. /**
  9028. * Returns whether an element is part of the active data.
  9029. * @param value defines the value to look for
  9030. * @returns true if found in the active data otherwise false
  9031. */
  9032. SmartArray.prototype.contains = function (value) {
  9033. return this.indexOf(value) !== -1;
  9034. };
  9035. // Statics
  9036. SmartArray._GlobalId = 0;
  9037. return SmartArray;
  9038. }());
  9039. BABYLON.SmartArray = SmartArray;
  9040. /**
  9041. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9042. * The data in this array can only be present once
  9043. */
  9044. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9045. __extends(SmartArrayNoDuplicate, _super);
  9046. function SmartArrayNoDuplicate() {
  9047. var _this = _super !== null && _super.apply(this, arguments) || this;
  9048. _this._duplicateId = 0;
  9049. return _this;
  9050. }
  9051. /**
  9052. * Pushes a value at the end of the active data.
  9053. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9054. * @param value defines the object to push in the array.
  9055. */
  9056. SmartArrayNoDuplicate.prototype.push = function (value) {
  9057. _super.prototype.push.call(this, value);
  9058. if (!value.__smartArrayFlags) {
  9059. value.__smartArrayFlags = {};
  9060. }
  9061. value.__smartArrayFlags[this._id] = this._duplicateId;
  9062. };
  9063. /**
  9064. * Pushes a value at the end of the active data.
  9065. * If the data is already present, it won t be added again
  9066. * @param value defines the object to push in the array.
  9067. * @returns true if added false if it was already present
  9068. */
  9069. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9070. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9071. return false;
  9072. }
  9073. this.push(value);
  9074. return true;
  9075. };
  9076. /**
  9077. * Resets the active data to an empty array.
  9078. */
  9079. SmartArrayNoDuplicate.prototype.reset = function () {
  9080. _super.prototype.reset.call(this);
  9081. this._duplicateId++;
  9082. };
  9083. /**
  9084. * Concats the active data with a given array.
  9085. * This ensures no dupplicate will be present in the result.
  9086. * @param array defines the data to concatenate with.
  9087. */
  9088. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9089. if (array.length === 0) {
  9090. return;
  9091. }
  9092. if (this.length + array.length > this.data.length) {
  9093. this.data.length = (this.length + array.length) * 2;
  9094. }
  9095. for (var index = 0; index < array.length; index++) {
  9096. var item = (array.data || array)[index];
  9097. this.pushNoDuplicate(item);
  9098. }
  9099. };
  9100. return SmartArrayNoDuplicate;
  9101. }(SmartArray));
  9102. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9103. })(BABYLON || (BABYLON = {}));
  9104. //# sourceMappingURL=babylon.smartArray.js.map
  9105. var BABYLON;
  9106. (function (BABYLON) {
  9107. /** Class used to store color4 gradient */
  9108. var ColorGradient = /** @class */ (function () {
  9109. function ColorGradient() {
  9110. }
  9111. /**
  9112. * Will get a color picked randomly between color1 and color2.
  9113. * If color2 is undefined then color1 will be used
  9114. * @param result defines the target Color4 to store the result in
  9115. */
  9116. ColorGradient.prototype.getColorToRef = function (result) {
  9117. if (!this.color2) {
  9118. result.copyFrom(this.color1);
  9119. return;
  9120. }
  9121. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9122. };
  9123. return ColorGradient;
  9124. }());
  9125. BABYLON.ColorGradient = ColorGradient;
  9126. /** Class used to store color 3 gradient */
  9127. var Color3Gradient = /** @class */ (function () {
  9128. function Color3Gradient() {
  9129. }
  9130. return Color3Gradient;
  9131. }());
  9132. BABYLON.Color3Gradient = Color3Gradient;
  9133. /** Class used to store factor gradient */
  9134. var FactorGradient = /** @class */ (function () {
  9135. function FactorGradient() {
  9136. }
  9137. /**
  9138. * Will get a number picked randomly between factor1 and factor2.
  9139. * If factor2 is undefined then factor1 will be used
  9140. * @returns the picked number
  9141. */
  9142. FactorGradient.prototype.getFactor = function () {
  9143. if (this.factor2 === undefined) {
  9144. return this.factor1;
  9145. }
  9146. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9147. };
  9148. return FactorGradient;
  9149. }());
  9150. BABYLON.FactorGradient = FactorGradient;
  9151. /**
  9152. * Application error to support additional information when loading a file
  9153. */
  9154. var LoadFileError = /** @class */ (function (_super) {
  9155. __extends(LoadFileError, _super);
  9156. /**
  9157. * Creates a new LoadFileError
  9158. * @param message defines the message of the error
  9159. * @param request defines the optional XHR request
  9160. */
  9161. function LoadFileError(message, request) {
  9162. var _this = _super.call(this, message) || this;
  9163. _this.request = request;
  9164. _this.name = "LoadFileError";
  9165. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9166. return _this;
  9167. }
  9168. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9169. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9170. // Polyfill for Object.setPrototypeOf if necessary.
  9171. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9172. return LoadFileError;
  9173. }(Error));
  9174. BABYLON.LoadFileError = LoadFileError;
  9175. /**
  9176. * Class used to define a retry strategy when error happens while loading assets
  9177. */
  9178. var RetryStrategy = /** @class */ (function () {
  9179. function RetryStrategy() {
  9180. }
  9181. /**
  9182. * Function used to defines an exponential back off strategy
  9183. * @param maxRetries defines the maximum number of retries (3 by default)
  9184. * @param baseInterval defines the interval between retries
  9185. * @returns the strategy function to use
  9186. */
  9187. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9188. if (maxRetries === void 0) { maxRetries = 3; }
  9189. if (baseInterval === void 0) { baseInterval = 500; }
  9190. return function (url, request, retryIndex) {
  9191. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9192. return -1;
  9193. }
  9194. return Math.pow(2, retryIndex) * baseInterval;
  9195. };
  9196. };
  9197. return RetryStrategy;
  9198. }());
  9199. BABYLON.RetryStrategy = RetryStrategy;
  9200. // Screenshots
  9201. var screenshotCanvas;
  9202. var cloneValue = function (source, destinationObject) {
  9203. if (!source)
  9204. return null;
  9205. if (source instanceof BABYLON.Mesh) {
  9206. return null;
  9207. }
  9208. if (source instanceof BABYLON.SubMesh) {
  9209. return source.clone(destinationObject);
  9210. }
  9211. else if (source.clone) {
  9212. return source.clone();
  9213. }
  9214. return null;
  9215. };
  9216. /**
  9217. * Class containing a set of static utilities functions
  9218. */
  9219. var Tools = /** @class */ (function () {
  9220. function Tools() {
  9221. }
  9222. /**
  9223. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9224. * @param u defines the coordinate on X axis
  9225. * @param v defines the coordinate on Y axis
  9226. * @param width defines the width of the source data
  9227. * @param height defines the height of the source data
  9228. * @param pixels defines the source byte array
  9229. * @param color defines the output color
  9230. */
  9231. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9232. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9233. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9234. var position = (wrappedU + wrappedV * width) * 4;
  9235. color.r = pixels[position] / 255;
  9236. color.g = pixels[position + 1] / 255;
  9237. color.b = pixels[position + 2] / 255;
  9238. color.a = pixels[position + 3] / 255;
  9239. };
  9240. /**
  9241. * Interpolates between a and b via alpha
  9242. * @param a The lower value (returned when alpha = 0)
  9243. * @param b The upper value (returned when alpha = 1)
  9244. * @param alpha The interpolation-factor
  9245. * @return The mixed value
  9246. */
  9247. Tools.Mix = function (a, b, alpha) {
  9248. return a * (1 - alpha) + b * alpha;
  9249. };
  9250. /**
  9251. * Tries to instantiate a new object from a given class name
  9252. * @param className defines the class name to instantiate
  9253. * @returns the new object or null if the system was not able to do the instantiation
  9254. */
  9255. Tools.Instantiate = function (className) {
  9256. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9257. return Tools.RegisteredExternalClasses[className];
  9258. }
  9259. var arr = className.split(".");
  9260. var fn = (window || this);
  9261. for (var i = 0, len = arr.length; i < len; i++) {
  9262. fn = fn[arr[i]];
  9263. }
  9264. if (typeof fn !== "function") {
  9265. return null;
  9266. }
  9267. return fn;
  9268. };
  9269. /**
  9270. * Provides a slice function that will work even on IE
  9271. * @param data defines the array to slice
  9272. * @param start defines the start of the data (optional)
  9273. * @param end defines the end of the data (optional)
  9274. * @returns the new sliced array
  9275. */
  9276. Tools.Slice = function (data, start, end) {
  9277. if (data.slice) {
  9278. return data.slice(start, end);
  9279. }
  9280. return Array.prototype.slice.call(data, start, end);
  9281. };
  9282. /**
  9283. * Polyfill for setImmediate
  9284. * @param action defines the action to execute after the current execution block
  9285. */
  9286. Tools.SetImmediate = function (action) {
  9287. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9288. window.setImmediate(action);
  9289. }
  9290. else {
  9291. setTimeout(action, 1);
  9292. }
  9293. };
  9294. /**
  9295. * Function indicating if a number is an exponent of 2
  9296. * @param value defines the value to test
  9297. * @returns true if the value is an exponent of 2
  9298. */
  9299. Tools.IsExponentOfTwo = function (value) {
  9300. var count = 1;
  9301. do {
  9302. count *= 2;
  9303. } while (count < value);
  9304. return count === value;
  9305. };
  9306. /**
  9307. * Returns the nearest 32-bit single precision float representation of a Number
  9308. * @param value A Number. If the parameter is of a different type, it will get converted
  9309. * to a number or to NaN if it cannot be converted
  9310. * @returns number
  9311. */
  9312. Tools.FloatRound = function (value) {
  9313. if (Math.fround) {
  9314. return Math.fround(value);
  9315. }
  9316. return (Tools._tmpFloatArray[0] = value);
  9317. };
  9318. /**
  9319. * Find the next highest power of two.
  9320. * @param x Number to start search from.
  9321. * @return Next highest power of two.
  9322. */
  9323. Tools.CeilingPOT = function (x) {
  9324. x--;
  9325. x |= x >> 1;
  9326. x |= x >> 2;
  9327. x |= x >> 4;
  9328. x |= x >> 8;
  9329. x |= x >> 16;
  9330. x++;
  9331. return x;
  9332. };
  9333. /**
  9334. * Find the next lowest power of two.
  9335. * @param x Number to start search from.
  9336. * @return Next lowest power of two.
  9337. */
  9338. Tools.FloorPOT = function (x) {
  9339. x = x | (x >> 1);
  9340. x = x | (x >> 2);
  9341. x = x | (x >> 4);
  9342. x = x | (x >> 8);
  9343. x = x | (x >> 16);
  9344. return x - (x >> 1);
  9345. };
  9346. /**
  9347. * Find the nearest power of two.
  9348. * @param x Number to start search from.
  9349. * @return Next nearest power of two.
  9350. */
  9351. Tools.NearestPOT = function (x) {
  9352. var c = Tools.CeilingPOT(x);
  9353. var f = Tools.FloorPOT(x);
  9354. return (c - x) > (x - f) ? f : c;
  9355. };
  9356. /**
  9357. * Get the closest exponent of two
  9358. * @param value defines the value to approximate
  9359. * @param max defines the maximum value to return
  9360. * @param mode defines how to define the closest value
  9361. * @returns closest exponent of two of the given value
  9362. */
  9363. Tools.GetExponentOfTwo = function (value, max, mode) {
  9364. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9365. var pot;
  9366. switch (mode) {
  9367. case BABYLON.Engine.SCALEMODE_FLOOR:
  9368. pot = Tools.FloorPOT(value);
  9369. break;
  9370. case BABYLON.Engine.SCALEMODE_NEAREST:
  9371. pot = Tools.NearestPOT(value);
  9372. break;
  9373. case BABYLON.Engine.SCALEMODE_CEILING:
  9374. default:
  9375. pot = Tools.CeilingPOT(value);
  9376. break;
  9377. }
  9378. return Math.min(pot, max);
  9379. };
  9380. /**
  9381. * Extracts the filename from a path
  9382. * @param path defines the path to use
  9383. * @returns the filename
  9384. */
  9385. Tools.GetFilename = function (path) {
  9386. var index = path.lastIndexOf("/");
  9387. if (index < 0)
  9388. return path;
  9389. return path.substring(index + 1);
  9390. };
  9391. /**
  9392. * Extracts the "folder" part of a path (everything before the filename).
  9393. * @param uri The URI to extract the info from
  9394. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9395. * @returns The "folder" part of the path
  9396. */
  9397. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9398. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9399. var index = uri.lastIndexOf("/");
  9400. if (index < 0) {
  9401. if (returnUnchangedIfNoSlash) {
  9402. return uri;
  9403. }
  9404. return "";
  9405. }
  9406. return uri.substring(0, index + 1);
  9407. };
  9408. /**
  9409. * Extracts text content from a DOM element hierarchy
  9410. * @param element defines the root element
  9411. * @returns a string
  9412. */
  9413. Tools.GetDOMTextContent = function (element) {
  9414. var result = "";
  9415. var child = element.firstChild;
  9416. while (child) {
  9417. if (child.nodeType === 3) {
  9418. result += child.textContent;
  9419. }
  9420. child = child.nextSibling;
  9421. }
  9422. return result;
  9423. };
  9424. /**
  9425. * Convert an angle in radians to degrees
  9426. * @param angle defines the angle to convert
  9427. * @returns the angle in degrees
  9428. */
  9429. Tools.ToDegrees = function (angle) {
  9430. return angle * 180 / Math.PI;
  9431. };
  9432. /**
  9433. * Convert an angle in degrees to radians
  9434. * @param angle defines the angle to convert
  9435. * @returns the angle in radians
  9436. */
  9437. Tools.ToRadians = function (angle) {
  9438. return angle * Math.PI / 180;
  9439. };
  9440. /**
  9441. * Encode a buffer to a base64 string
  9442. * @param buffer defines the buffer to encode
  9443. * @returns the encoded string
  9444. */
  9445. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9446. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9447. var output = "";
  9448. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9449. var i = 0;
  9450. var bytes = new Uint8Array(buffer);
  9451. while (i < bytes.length) {
  9452. chr1 = bytes[i++];
  9453. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9454. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9455. enc1 = chr1 >> 2;
  9456. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9457. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9458. enc4 = chr3 & 63;
  9459. if (isNaN(chr2)) {
  9460. enc3 = enc4 = 64;
  9461. }
  9462. else if (isNaN(chr3)) {
  9463. enc4 = 64;
  9464. }
  9465. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9466. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9467. }
  9468. return "data:image/png;base64," + output;
  9469. };
  9470. /**
  9471. * Extracts minimum and maximum values from a list of indexed positions
  9472. * @param positions defines the positions to use
  9473. * @param indices defines the indices to the positions
  9474. * @param indexStart defines the start index
  9475. * @param indexCount defines the end index
  9476. * @param bias defines bias value to add to the result
  9477. * @return minimum and maximum values
  9478. */
  9479. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9480. if (bias === void 0) { bias = null; }
  9481. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9482. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9483. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9484. var offset = indices[index];
  9485. var x = positions[offset];
  9486. var y = positions[offset + 1];
  9487. var z = positions[offset + 2];
  9488. minimum.minimizeInPlaceFromFloats(x, y, z);
  9489. maximum.maximizeInPlaceFromFloats(x, y, z);
  9490. }
  9491. if (bias) {
  9492. minimum.x -= minimum.x * bias.x + bias.y;
  9493. minimum.y -= minimum.y * bias.x + bias.y;
  9494. minimum.z -= minimum.z * bias.x + bias.y;
  9495. maximum.x += maximum.x * bias.x + bias.y;
  9496. maximum.y += maximum.y * bias.x + bias.y;
  9497. maximum.z += maximum.z * bias.x + bias.y;
  9498. }
  9499. return {
  9500. minimum: minimum,
  9501. maximum: maximum
  9502. };
  9503. };
  9504. /**
  9505. * Extracts minimum and maximum values from a list of positions
  9506. * @param positions defines the positions to use
  9507. * @param start defines the start index in the positions array
  9508. * @param count defines the number of positions to handle
  9509. * @param bias defines bias value to add to the result
  9510. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9511. * @return minimum and maximum values
  9512. */
  9513. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9514. if (bias === void 0) { bias = null; }
  9515. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9516. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9517. if (!stride) {
  9518. stride = 3;
  9519. }
  9520. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9521. var x = positions[offset];
  9522. var y = positions[offset + 1];
  9523. var z = positions[offset + 2];
  9524. minimum.minimizeInPlaceFromFloats(x, y, z);
  9525. maximum.maximizeInPlaceFromFloats(x, y, z);
  9526. }
  9527. if (bias) {
  9528. minimum.x -= minimum.x * bias.x + bias.y;
  9529. minimum.y -= minimum.y * bias.x + bias.y;
  9530. minimum.z -= minimum.z * bias.x + bias.y;
  9531. maximum.x += maximum.x * bias.x + bias.y;
  9532. maximum.y += maximum.y * bias.x + bias.y;
  9533. maximum.z += maximum.z * bias.x + bias.y;
  9534. }
  9535. return {
  9536. minimum: minimum,
  9537. maximum: maximum
  9538. };
  9539. };
  9540. /**
  9541. * Returns an array if obj is not an array
  9542. * @param obj defines the object to evaluate as an array
  9543. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9544. * @returns either obj directly if obj is an array or a new array containing obj
  9545. */
  9546. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9547. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9548. return null;
  9549. return Array.isArray(obj) ? obj : [obj];
  9550. };
  9551. /**
  9552. * Gets the pointer prefix to use
  9553. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9554. */
  9555. Tools.GetPointerPrefix = function () {
  9556. var eventPrefix = "pointer";
  9557. // Check if pointer events are supported
  9558. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9559. eventPrefix = "mouse";
  9560. }
  9561. return eventPrefix;
  9562. };
  9563. /**
  9564. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9565. * @param func - the function to be called
  9566. * @param requester - the object that will request the next frame. Falls back to window.
  9567. * @returns frame number
  9568. */
  9569. Tools.QueueNewFrame = function (func, requester) {
  9570. if (!Tools.IsWindowObjectExist()) {
  9571. return setTimeout(func, 16);
  9572. }
  9573. if (!requester) {
  9574. requester = window;
  9575. }
  9576. if (requester.requestAnimationFrame) {
  9577. return requester.requestAnimationFrame(func);
  9578. }
  9579. else if (requester.msRequestAnimationFrame) {
  9580. return requester.msRequestAnimationFrame(func);
  9581. }
  9582. else if (requester.webkitRequestAnimationFrame) {
  9583. return requester.webkitRequestAnimationFrame(func);
  9584. }
  9585. else if (requester.mozRequestAnimationFrame) {
  9586. return requester.mozRequestAnimationFrame(func);
  9587. }
  9588. else if (requester.oRequestAnimationFrame) {
  9589. return requester.oRequestAnimationFrame(func);
  9590. }
  9591. else {
  9592. return window.setTimeout(func, 16);
  9593. }
  9594. };
  9595. /**
  9596. * Ask the browser to promote the current element to fullscreen rendering mode
  9597. * @param element defines the DOM element to promote
  9598. */
  9599. Tools.RequestFullscreen = function (element) {
  9600. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9601. if (!requestFunction)
  9602. return;
  9603. requestFunction.call(element);
  9604. };
  9605. /**
  9606. * Asks the browser to exit fullscreen mode
  9607. */
  9608. Tools.ExitFullscreen = function () {
  9609. if (document.exitFullscreen) {
  9610. document.exitFullscreen();
  9611. }
  9612. else if (document.mozCancelFullScreen) {
  9613. document.mozCancelFullScreen();
  9614. }
  9615. else if (document.webkitCancelFullScreen) {
  9616. document.webkitCancelFullScreen();
  9617. }
  9618. else if (document.msCancelFullScreen) {
  9619. document.msCancelFullScreen();
  9620. }
  9621. };
  9622. /**
  9623. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9624. * @param url define the url we are trying
  9625. * @param element define the dom element where to configure the cors policy
  9626. */
  9627. Tools.SetCorsBehavior = function (url, element) {
  9628. if (url && url.indexOf("data:") === 0) {
  9629. return;
  9630. }
  9631. if (Tools.CorsBehavior) {
  9632. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9633. element.crossOrigin = Tools.CorsBehavior;
  9634. }
  9635. else {
  9636. var result = Tools.CorsBehavior(url);
  9637. if (result) {
  9638. element.crossOrigin = result;
  9639. }
  9640. }
  9641. }
  9642. };
  9643. // External files
  9644. /**
  9645. * Removes unwanted characters from an url
  9646. * @param url defines the url to clean
  9647. * @returns the cleaned url
  9648. */
  9649. Tools.CleanUrl = function (url) {
  9650. url = url.replace(/#/mg, "%23");
  9651. return url;
  9652. };
  9653. /**
  9654. * Loads an image as an HTMLImageElement.
  9655. * @param input url string, ArrayBuffer, or Blob to load
  9656. * @param onLoad callback called when the image successfully loads
  9657. * @param onError callback called when the image fails to load
  9658. * @param database database for caching
  9659. * @returns the HTMLImageElement of the loaded image
  9660. */
  9661. Tools.LoadImage = function (input, onLoad, onError, database) {
  9662. var url;
  9663. var usingObjectURL = false;
  9664. if (input instanceof ArrayBuffer) {
  9665. url = URL.createObjectURL(new Blob([input]));
  9666. usingObjectURL = true;
  9667. }
  9668. else if (input instanceof Blob) {
  9669. url = URL.createObjectURL(input);
  9670. usingObjectURL = true;
  9671. }
  9672. else {
  9673. url = Tools.CleanUrl(input);
  9674. url = Tools.PreprocessUrl(input);
  9675. }
  9676. var img = new Image();
  9677. Tools.SetCorsBehavior(url, img);
  9678. var loadHandler = function () {
  9679. if (usingObjectURL && img.src) {
  9680. URL.revokeObjectURL(img.src);
  9681. }
  9682. img.removeEventListener("load", loadHandler);
  9683. img.removeEventListener("error", errorHandler);
  9684. onLoad(img);
  9685. };
  9686. var errorHandler = function (err) {
  9687. if (usingObjectURL && img.src) {
  9688. URL.revokeObjectURL(img.src);
  9689. }
  9690. img.removeEventListener("load", loadHandler);
  9691. img.removeEventListener("error", errorHandler);
  9692. Tools.Error("Error while trying to load image: " + input);
  9693. if (onError) {
  9694. onError("Error while trying to load image: " + input, err);
  9695. }
  9696. };
  9697. img.addEventListener("load", loadHandler);
  9698. img.addEventListener("error", errorHandler);
  9699. var noIndexedDB = function () {
  9700. img.src = url;
  9701. };
  9702. var loadFromIndexedDB = function () {
  9703. if (database) {
  9704. database.loadImageFromDB(url, img);
  9705. }
  9706. };
  9707. //ANY database to do!
  9708. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9709. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9710. }
  9711. else {
  9712. if (url.indexOf("file:") !== -1) {
  9713. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9714. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9715. try {
  9716. var blobURL;
  9717. try {
  9718. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9719. }
  9720. catch (ex) {
  9721. // Chrome doesn't support oneTimeOnly parameter
  9722. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9723. }
  9724. img.src = blobURL;
  9725. usingObjectURL = true;
  9726. }
  9727. catch (e) {
  9728. img.src = "";
  9729. }
  9730. return img;
  9731. }
  9732. }
  9733. noIndexedDB();
  9734. }
  9735. return img;
  9736. };
  9737. /**
  9738. * Loads a file
  9739. * @param url url string, ArrayBuffer, or Blob to load
  9740. * @param onSuccess callback called when the file successfully loads
  9741. * @param onProgress callback called while file is loading (if the server supports this mode)
  9742. * @param database database for caching
  9743. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9744. * @param onError callback called when the file fails to load
  9745. * @returns a file request object
  9746. */
  9747. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9748. url = Tools.CleanUrl(url);
  9749. url = Tools.PreprocessUrl(url);
  9750. // If file and file input are set
  9751. if (url.indexOf("file:") !== -1) {
  9752. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9753. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9754. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9755. }
  9756. }
  9757. var loadUrl = Tools.BaseUrl + url;
  9758. var aborted = false;
  9759. var fileRequest = {
  9760. onCompleteObservable: new BABYLON.Observable(),
  9761. abort: function () { return aborted = true; },
  9762. };
  9763. var requestFile = function () {
  9764. var request = new XMLHttpRequest();
  9765. var retryHandle = null;
  9766. fileRequest.abort = function () {
  9767. aborted = true;
  9768. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9769. request.abort();
  9770. }
  9771. if (retryHandle !== null) {
  9772. clearTimeout(retryHandle);
  9773. retryHandle = null;
  9774. }
  9775. };
  9776. var retryLoop = function (retryIndex) {
  9777. request.open('GET', loadUrl, true);
  9778. if (useArrayBuffer) {
  9779. request.responseType = "arraybuffer";
  9780. }
  9781. if (onProgress) {
  9782. request.addEventListener("progress", onProgress);
  9783. }
  9784. var onLoadEnd = function () {
  9785. request.removeEventListener("loadend", onLoadEnd);
  9786. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9787. fileRequest.onCompleteObservable.clear();
  9788. };
  9789. request.addEventListener("loadend", onLoadEnd);
  9790. var onReadyStateChange = function () {
  9791. if (aborted) {
  9792. return;
  9793. }
  9794. // In case of undefined state in some browsers.
  9795. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9796. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9797. request.removeEventListener("readystatechange", onReadyStateChange);
  9798. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9799. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9800. return;
  9801. }
  9802. var retryStrategy = Tools.DefaultRetryStrategy;
  9803. if (retryStrategy) {
  9804. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9805. if (waitTime !== -1) {
  9806. // Prevent the request from completing for retry.
  9807. request.removeEventListener("loadend", onLoadEnd);
  9808. request = new XMLHttpRequest();
  9809. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9810. return;
  9811. }
  9812. }
  9813. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9814. if (onError) {
  9815. onError(request, e);
  9816. }
  9817. else {
  9818. throw e;
  9819. }
  9820. }
  9821. };
  9822. request.addEventListener("readystatechange", onReadyStateChange);
  9823. request.send();
  9824. };
  9825. retryLoop(0);
  9826. };
  9827. // Caching all files
  9828. if (database && database.enableSceneOffline) {
  9829. var noIndexedDB_1 = function (request) {
  9830. if (request && request.status > 400) {
  9831. if (onError) {
  9832. onError(request);
  9833. }
  9834. }
  9835. else {
  9836. if (!aborted) {
  9837. requestFile();
  9838. }
  9839. }
  9840. };
  9841. var loadFromIndexedDB = function () {
  9842. // TODO: database needs to support aborting and should return a IFileRequest
  9843. if (aborted) {
  9844. return;
  9845. }
  9846. if (database) {
  9847. database.loadFileFromDB(url, function (data) {
  9848. if (!aborted) {
  9849. onSuccess(data);
  9850. }
  9851. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9852. }, onProgress ? function (event) {
  9853. if (!aborted) {
  9854. onProgress(event);
  9855. }
  9856. } : undefined, noIndexedDB_1, useArrayBuffer);
  9857. }
  9858. };
  9859. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9860. }
  9861. else {
  9862. requestFile();
  9863. }
  9864. return fileRequest;
  9865. };
  9866. /**
  9867. * Load a script (identified by an url). When the url returns, the
  9868. * content of this file is added into a new script element, attached to the DOM (body element)
  9869. * @param scriptUrl defines the url of the script to laod
  9870. * @param onSuccess defines the callback called when the script is loaded
  9871. * @param onError defines the callback to call if an error occurs
  9872. */
  9873. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9874. if (!Tools.IsWindowObjectExist()) {
  9875. return;
  9876. }
  9877. var head = document.getElementsByTagName('head')[0];
  9878. var script = document.createElement('script');
  9879. script.type = 'text/javascript';
  9880. script.src = scriptUrl;
  9881. script.onload = function () {
  9882. if (onSuccess) {
  9883. onSuccess();
  9884. }
  9885. };
  9886. script.onerror = function (e) {
  9887. if (onError) {
  9888. onError("Unable to load script '" + scriptUrl + "'", e);
  9889. }
  9890. };
  9891. head.appendChild(script);
  9892. };
  9893. /**
  9894. * Loads a file from a blob
  9895. * @param fileToLoad defines the blob to use
  9896. * @param callback defines the callback to call when data is loaded
  9897. * @param progressCallback defines the callback to call during loading process
  9898. * @returns a file request object
  9899. */
  9900. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9901. var reader = new FileReader();
  9902. var request = {
  9903. onCompleteObservable: new BABYLON.Observable(),
  9904. abort: function () { return reader.abort(); },
  9905. };
  9906. reader.onloadend = function (e) {
  9907. request.onCompleteObservable.notifyObservers(request);
  9908. };
  9909. reader.onload = function (e) {
  9910. //target doesn't have result from ts 1.3
  9911. callback(e.target['result']);
  9912. };
  9913. reader.onprogress = progressCallback;
  9914. reader.readAsDataURL(fileToLoad);
  9915. return request;
  9916. };
  9917. /**
  9918. * Loads a file
  9919. * @param fileToLoad defines the file to load
  9920. * @param callback defines the callback to call when data is loaded
  9921. * @param progressCallBack defines the callback to call during loading process
  9922. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  9923. * @returns a file request object
  9924. */
  9925. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9926. var reader = new FileReader();
  9927. var request = {
  9928. onCompleteObservable: new BABYLON.Observable(),
  9929. abort: function () { return reader.abort(); },
  9930. };
  9931. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9932. reader.onerror = function (e) {
  9933. Tools.Log("Error while reading file: " + fileToLoad.name);
  9934. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9935. };
  9936. reader.onload = function (e) {
  9937. //target doesn't have result from ts 1.3
  9938. callback(e.target['result']);
  9939. };
  9940. if (progressCallBack) {
  9941. reader.onprogress = progressCallBack;
  9942. }
  9943. if (!useArrayBuffer) {
  9944. // Asynchronous read
  9945. reader.readAsText(fileToLoad);
  9946. }
  9947. else {
  9948. reader.readAsArrayBuffer(fileToLoad);
  9949. }
  9950. return request;
  9951. };
  9952. /**
  9953. * Creates a data url from a given string content
  9954. * @param content defines the content to convert
  9955. * @returns the new data url link
  9956. */
  9957. Tools.FileAsURL = function (content) {
  9958. var fileBlob = new Blob([content]);
  9959. var url = window.URL || window.webkitURL;
  9960. var link = url.createObjectURL(fileBlob);
  9961. return link;
  9962. };
  9963. /**
  9964. * Format the given number to a specific decimal format
  9965. * @param value defines the number to format
  9966. * @param decimals defines the number of decimals to use
  9967. * @returns the formatted string
  9968. */
  9969. Tools.Format = function (value, decimals) {
  9970. if (decimals === void 0) { decimals = 2; }
  9971. return value.toFixed(decimals);
  9972. };
  9973. /**
  9974. * Checks if a given vector is inside a specific range
  9975. * @param v defines the vector to test
  9976. * @param min defines the minimum range
  9977. * @param max defines the maximum range
  9978. */
  9979. Tools.CheckExtends = function (v, min, max) {
  9980. if (v.x < min.x)
  9981. min.x = v.x;
  9982. if (v.y < min.y)
  9983. min.y = v.y;
  9984. if (v.z < min.z)
  9985. min.z = v.z;
  9986. if (v.x > max.x)
  9987. max.x = v.x;
  9988. if (v.y > max.y)
  9989. max.y = v.y;
  9990. if (v.z > max.z)
  9991. max.z = v.z;
  9992. };
  9993. /**
  9994. * Tries to copy an object by duplicating every property
  9995. * @param source defines the source object
  9996. * @param destination defines the target object
  9997. * @param doNotCopyList defines a list of properties to avoid
  9998. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  9999. */
  10000. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10001. for (var prop in source) {
  10002. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10003. continue;
  10004. }
  10005. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10006. continue;
  10007. }
  10008. var sourceValue = source[prop];
  10009. var typeOfSourceValue = typeof sourceValue;
  10010. if (typeOfSourceValue === "function") {
  10011. continue;
  10012. }
  10013. try {
  10014. if (typeOfSourceValue === "object") {
  10015. if (sourceValue instanceof Array) {
  10016. destination[prop] = [];
  10017. if (sourceValue.length > 0) {
  10018. if (typeof sourceValue[0] == "object") {
  10019. for (var index = 0; index < sourceValue.length; index++) {
  10020. var clonedValue = cloneValue(sourceValue[index], destination);
  10021. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10022. destination[prop].push(clonedValue);
  10023. }
  10024. }
  10025. }
  10026. else {
  10027. destination[prop] = sourceValue.slice(0);
  10028. }
  10029. }
  10030. }
  10031. else {
  10032. destination[prop] = cloneValue(sourceValue, destination);
  10033. }
  10034. }
  10035. else {
  10036. destination[prop] = sourceValue;
  10037. }
  10038. }
  10039. catch (e) {
  10040. // Just ignore error (it could be because of a read-only property)
  10041. }
  10042. }
  10043. };
  10044. /**
  10045. * Gets a boolean indicating if the given object has no own property
  10046. * @param obj defines the object to test
  10047. * @returns true if object has no own property
  10048. */
  10049. Tools.IsEmpty = function (obj) {
  10050. for (var i in obj) {
  10051. if (obj.hasOwnProperty(i)) {
  10052. return false;
  10053. }
  10054. }
  10055. return true;
  10056. };
  10057. /**
  10058. * Function used to register events at window level
  10059. * @param events defines the events to register
  10060. */
  10061. Tools.RegisterTopRootEvents = function (events) {
  10062. for (var index = 0; index < events.length; index++) {
  10063. var event = events[index];
  10064. window.addEventListener(event.name, event.handler, false);
  10065. try {
  10066. if (window.parent) {
  10067. window.parent.addEventListener(event.name, event.handler, false);
  10068. }
  10069. }
  10070. catch (e) {
  10071. // Silently fails...
  10072. }
  10073. }
  10074. };
  10075. /**
  10076. * Function used to unregister events from window level
  10077. * @param events defines the events to unregister
  10078. */
  10079. Tools.UnregisterTopRootEvents = function (events) {
  10080. for (var index = 0; index < events.length; index++) {
  10081. var event = events[index];
  10082. window.removeEventListener(event.name, event.handler);
  10083. try {
  10084. if (window.parent) {
  10085. window.parent.removeEventListener(event.name, event.handler);
  10086. }
  10087. }
  10088. catch (e) {
  10089. // Silently fails...
  10090. }
  10091. }
  10092. };
  10093. /**
  10094. * Dumps the current bound framebuffer
  10095. * @param width defines the rendering width
  10096. * @param height defines the rendering height
  10097. * @param engine defines the hosting engine
  10098. * @param successCallback defines the callback triggered once the data are available
  10099. * @param mimeType defines the mime type of the result
  10100. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10101. */
  10102. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10103. if (mimeType === void 0) { mimeType = "image/png"; }
  10104. // Read the contents of the framebuffer
  10105. var numberOfChannelsByLine = width * 4;
  10106. var halfHeight = height / 2;
  10107. //Reading datas from WebGL
  10108. var data = engine.readPixels(0, 0, width, height);
  10109. //To flip image on Y axis.
  10110. for (var i = 0; i < halfHeight; i++) {
  10111. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10112. var currentCell = j + i * numberOfChannelsByLine;
  10113. var targetLine = height - i - 1;
  10114. var targetCell = j + targetLine * numberOfChannelsByLine;
  10115. var temp = data[currentCell];
  10116. data[currentCell] = data[targetCell];
  10117. data[targetCell] = temp;
  10118. }
  10119. }
  10120. // Create a 2D canvas to store the result
  10121. if (!screenshotCanvas) {
  10122. screenshotCanvas = document.createElement('canvas');
  10123. }
  10124. screenshotCanvas.width = width;
  10125. screenshotCanvas.height = height;
  10126. var context = screenshotCanvas.getContext('2d');
  10127. if (context) {
  10128. // Copy the pixels to a 2D canvas
  10129. var imageData = context.createImageData(width, height);
  10130. var castData = (imageData.data);
  10131. castData.set(data);
  10132. context.putImageData(imageData, 0, 0);
  10133. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10134. }
  10135. };
  10136. /**
  10137. * Converts the canvas data to blob.
  10138. * This acts as a polyfill for browsers not supporting the to blob function.
  10139. * @param canvas Defines the canvas to extract the data from
  10140. * @param successCallback Defines the callback triggered once the data are available
  10141. * @param mimeType Defines the mime type of the result
  10142. */
  10143. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10144. if (mimeType === void 0) { mimeType = "image/png"; }
  10145. // We need HTMLCanvasElement.toBlob for HD screenshots
  10146. if (!canvas.toBlob) {
  10147. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10148. canvas.toBlob = function (callback, type, quality) {
  10149. var _this = this;
  10150. setTimeout(function () {
  10151. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10152. for (var i = 0; i < len; i++) {
  10153. arr[i] = binStr.charCodeAt(i);
  10154. }
  10155. callback(new Blob([arr]));
  10156. });
  10157. };
  10158. }
  10159. canvas.toBlob(function (blob) {
  10160. successCallback(blob);
  10161. }, mimeType);
  10162. };
  10163. /**
  10164. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10165. * @param successCallback defines the callback triggered once the data are available
  10166. * @param mimeType defines the mime type of the result
  10167. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10168. */
  10169. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10170. if (mimeType === void 0) { mimeType = "image/png"; }
  10171. if (successCallback) {
  10172. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10173. successCallback(base64Image);
  10174. }
  10175. else {
  10176. this.ToBlob(screenshotCanvas, function (blob) {
  10177. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10178. if (("download" in document.createElement("a"))) {
  10179. if (!fileName) {
  10180. var date = new Date();
  10181. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10182. fileName = "screenshot_" + stringDate + ".png";
  10183. }
  10184. Tools.Download(blob, fileName);
  10185. }
  10186. else {
  10187. var url = URL.createObjectURL(blob);
  10188. var newWindow = window.open("");
  10189. if (!newWindow)
  10190. return;
  10191. var img = newWindow.document.createElement("img");
  10192. img.onload = function () {
  10193. // no longer need to read the blob so it's revoked
  10194. URL.revokeObjectURL(url);
  10195. };
  10196. img.src = url;
  10197. newWindow.document.body.appendChild(img);
  10198. }
  10199. }, mimeType);
  10200. }
  10201. };
  10202. /**
  10203. * Downloads a blob in the browser
  10204. * @param blob defines the blob to download
  10205. * @param fileName defines the name of the downloaded file
  10206. */
  10207. Tools.Download = function (blob, fileName) {
  10208. if (navigator && navigator.msSaveBlob) {
  10209. navigator.msSaveBlob(blob, fileName);
  10210. return;
  10211. }
  10212. var url = window.URL.createObjectURL(blob);
  10213. var a = document.createElement("a");
  10214. document.body.appendChild(a);
  10215. a.style.display = "none";
  10216. a.href = url;
  10217. a.download = fileName;
  10218. a.addEventListener("click", function () {
  10219. if (a.parentElement) {
  10220. a.parentElement.removeChild(a);
  10221. }
  10222. });
  10223. a.click();
  10224. window.URL.revokeObjectURL(url);
  10225. };
  10226. /**
  10227. * Captures a screenshot of the current rendering
  10228. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10229. * @param engine defines the rendering engine
  10230. * @param camera defines the source camera
  10231. * @param size This parameter can be set to a single number or to an object with the
  10232. * following (optional) properties: precision, width, height. If a single number is passed,
  10233. * it will be used for both width and height. If an object is passed, the screenshot size
  10234. * will be derived from the parameters. The precision property is a multiplier allowing
  10235. * rendering at a higher or lower resolution
  10236. * @param successCallback defines the callback receives a single parameter which contains the
  10237. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10238. * src parameter of an <img> to display it
  10239. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10240. * Check your browser for supported MIME types
  10241. */
  10242. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10243. if (mimeType === void 0) { mimeType = "image/png"; }
  10244. var width;
  10245. var height;
  10246. // If a precision value is specified
  10247. if (size.precision) {
  10248. width = Math.round(engine.getRenderWidth() * size.precision);
  10249. height = Math.round(width / engine.getAspectRatio(camera));
  10250. }
  10251. else if (size.width && size.height) {
  10252. width = size.width;
  10253. height = size.height;
  10254. }
  10255. //If passing only width, computing height to keep display canvas ratio.
  10256. else if (size.width && !size.height) {
  10257. width = size.width;
  10258. height = Math.round(width / engine.getAspectRatio(camera));
  10259. }
  10260. //If passing only height, computing width to keep display canvas ratio.
  10261. else if (size.height && !size.width) {
  10262. height = size.height;
  10263. width = Math.round(height * engine.getAspectRatio(camera));
  10264. }
  10265. //Assuming here that "size" parameter is a number
  10266. else if (!isNaN(size)) {
  10267. height = size;
  10268. width = size;
  10269. }
  10270. else {
  10271. Tools.Error("Invalid 'size' parameter !");
  10272. return;
  10273. }
  10274. if (!screenshotCanvas) {
  10275. screenshotCanvas = document.createElement('canvas');
  10276. }
  10277. screenshotCanvas.width = width;
  10278. screenshotCanvas.height = height;
  10279. var renderContext = screenshotCanvas.getContext("2d");
  10280. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10281. var newWidth = width;
  10282. var newHeight = newWidth / ratio;
  10283. if (newHeight > height) {
  10284. newHeight = height;
  10285. newWidth = newHeight * ratio;
  10286. }
  10287. var offsetX = Math.max(0, width - newWidth) / 2;
  10288. var offsetY = Math.max(0, height - newHeight) / 2;
  10289. var renderingCanvas = engine.getRenderingCanvas();
  10290. if (renderContext && renderingCanvas) {
  10291. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10292. }
  10293. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10294. };
  10295. /**
  10296. * Generates an image screenshot from the specified camera.
  10297. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10298. * @param engine The engine to use for rendering
  10299. * @param camera The camera to use for rendering
  10300. * @param size This parameter can be set to a single number or to an object with the
  10301. * following (optional) properties: precision, width, height. If a single number is passed,
  10302. * it will be used for both width and height. If an object is passed, the screenshot size
  10303. * will be derived from the parameters. The precision property is a multiplier allowing
  10304. * rendering at a higher or lower resolution
  10305. * @param successCallback The callback receives a single parameter which contains the
  10306. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10307. * src parameter of an <img> to display it
  10308. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10309. * Check your browser for supported MIME types
  10310. * @param samples Texture samples (default: 1)
  10311. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10312. * @param fileName A name for for the downloaded file.
  10313. */
  10314. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10315. if (mimeType === void 0) { mimeType = "image/png"; }
  10316. if (samples === void 0) { samples = 1; }
  10317. if (antialiasing === void 0) { antialiasing = false; }
  10318. var width;
  10319. var height;
  10320. //If a precision value is specified
  10321. if (size.precision) {
  10322. width = Math.round(engine.getRenderWidth() * size.precision);
  10323. height = Math.round(width / engine.getAspectRatio(camera));
  10324. size = { width: width, height: height };
  10325. }
  10326. else if (size.width && size.height) {
  10327. width = size.width;
  10328. height = size.height;
  10329. }
  10330. //If passing only width, computing height to keep display canvas ratio.
  10331. else if (size.width && !size.height) {
  10332. width = size.width;
  10333. height = Math.round(width / engine.getAspectRatio(camera));
  10334. size = { width: width, height: height };
  10335. }
  10336. //If passing only height, computing width to keep display canvas ratio.
  10337. else if (size.height && !size.width) {
  10338. height = size.height;
  10339. width = Math.round(height * engine.getAspectRatio(camera));
  10340. size = { width: width, height: height };
  10341. }
  10342. //Assuming here that "size" parameter is a number
  10343. else if (!isNaN(size)) {
  10344. height = size;
  10345. width = size;
  10346. }
  10347. else {
  10348. Tools.Error("Invalid 'size' parameter !");
  10349. return;
  10350. }
  10351. var scene = camera.getScene();
  10352. var previousCamera = null;
  10353. if (scene.activeCamera !== camera) {
  10354. previousCamera = scene.activeCamera;
  10355. scene.activeCamera = camera;
  10356. }
  10357. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10358. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10359. texture.renderList = null;
  10360. texture.samples = samples;
  10361. if (antialiasing) {
  10362. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10363. }
  10364. texture.onAfterRenderObservable.add(function () {
  10365. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10366. });
  10367. scene.incrementRenderId();
  10368. scene.resetCachedMaterial();
  10369. texture.render(true);
  10370. texture.dispose();
  10371. if (previousCamera) {
  10372. scene.activeCamera = previousCamera;
  10373. }
  10374. camera.getProjectionMatrix(true); // Force cache refresh;
  10375. };
  10376. /**
  10377. * Validates if xhr data is correct
  10378. * @param xhr defines the request to validate
  10379. * @param dataType defines the expected data type
  10380. * @returns true if data is correct
  10381. */
  10382. Tools.ValidateXHRData = function (xhr, dataType) {
  10383. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10384. if (dataType === void 0) { dataType = 7; }
  10385. try {
  10386. if (dataType & 1) {
  10387. if (xhr.responseText && xhr.responseText.length > 0) {
  10388. return true;
  10389. }
  10390. else if (dataType === 1) {
  10391. return false;
  10392. }
  10393. }
  10394. if (dataType & 2) {
  10395. // Check header width and height since there is no "TGA" magic number
  10396. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10397. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10398. return true;
  10399. }
  10400. else if (dataType === 2) {
  10401. return false;
  10402. }
  10403. }
  10404. if (dataType & 4) {
  10405. // Check for the "DDS" magic number
  10406. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10407. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10408. return true;
  10409. }
  10410. else {
  10411. return false;
  10412. }
  10413. }
  10414. }
  10415. catch (e) {
  10416. // Global protection
  10417. }
  10418. return false;
  10419. };
  10420. /**
  10421. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10422. * Be aware Math.random() could cause collisions, but:
  10423. * "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"
  10424. * @returns a pseudo random id
  10425. */
  10426. Tools.RandomId = function () {
  10427. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10428. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10429. return v.toString(16);
  10430. });
  10431. };
  10432. /**
  10433. * Test if the given uri is a base64 string
  10434. * @param uri The uri to test
  10435. * @return True if the uri is a base64 string or false otherwise
  10436. */
  10437. Tools.IsBase64 = function (uri) {
  10438. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10439. };
  10440. /**
  10441. * Decode the given base64 uri.
  10442. * @param uri The uri to decode
  10443. * @return The decoded base64 data.
  10444. */
  10445. Tools.DecodeBase64 = function (uri) {
  10446. var decodedString = atob(uri.split(",")[1]);
  10447. var bufferLength = decodedString.length;
  10448. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10449. for (var i = 0; i < bufferLength; i++) {
  10450. bufferView[i] = decodedString.charCodeAt(i);
  10451. }
  10452. return bufferView.buffer;
  10453. };
  10454. Tools._AddLogEntry = function (entry) {
  10455. Tools._LogCache = entry + Tools._LogCache;
  10456. if (Tools.OnNewCacheEntry) {
  10457. Tools.OnNewCacheEntry(entry);
  10458. }
  10459. };
  10460. Tools._FormatMessage = function (message) {
  10461. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10462. var date = new Date();
  10463. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10464. };
  10465. Tools._LogDisabled = function (message) {
  10466. // nothing to do
  10467. };
  10468. Tools._LogEnabled = function (message) {
  10469. var formattedMessage = Tools._FormatMessage(message);
  10470. console.log("BJS - " + formattedMessage);
  10471. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10472. Tools._AddLogEntry(entry);
  10473. };
  10474. Tools._WarnDisabled = function (message) {
  10475. // nothing to do
  10476. };
  10477. Tools._WarnEnabled = function (message) {
  10478. var formattedMessage = Tools._FormatMessage(message);
  10479. console.warn("BJS - " + formattedMessage);
  10480. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10481. Tools._AddLogEntry(entry);
  10482. };
  10483. Tools._ErrorDisabled = function (message) {
  10484. // nothing to do
  10485. };
  10486. Tools._ErrorEnabled = function (message) {
  10487. Tools.errorsCount++;
  10488. var formattedMessage = Tools._FormatMessage(message);
  10489. console.error("BJS - " + formattedMessage);
  10490. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10491. Tools._AddLogEntry(entry);
  10492. };
  10493. Object.defineProperty(Tools, "LogCache", {
  10494. /**
  10495. * Gets current log cache (list of logs)
  10496. */
  10497. get: function () {
  10498. return Tools._LogCache;
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. /**
  10504. * Clears the log cache
  10505. */
  10506. Tools.ClearLogCache = function () {
  10507. Tools._LogCache = "";
  10508. Tools.errorsCount = 0;
  10509. };
  10510. Object.defineProperty(Tools, "LogLevels", {
  10511. /**
  10512. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10513. */
  10514. set: function (level) {
  10515. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10516. Tools.Log = Tools._LogEnabled;
  10517. }
  10518. else {
  10519. Tools.Log = Tools._LogDisabled;
  10520. }
  10521. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10522. Tools.Warn = Tools._WarnEnabled;
  10523. }
  10524. else {
  10525. Tools.Warn = Tools._WarnDisabled;
  10526. }
  10527. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10528. Tools.Error = Tools._ErrorEnabled;
  10529. }
  10530. else {
  10531. Tools.Error = Tools._ErrorDisabled;
  10532. }
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. /**
  10538. * Checks if the loaded document was accessed via `file:`-Protocol.
  10539. * @returns boolean
  10540. */
  10541. Tools.IsFileURL = function () {
  10542. return location.protocol === "file:";
  10543. };
  10544. /**
  10545. * Checks if the window object exists
  10546. * @returns true if the window object exists
  10547. */
  10548. Tools.IsWindowObjectExist = function () {
  10549. return (typeof window) !== "undefined";
  10550. };
  10551. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10552. /**
  10553. * Sets the current performance log level
  10554. */
  10555. set: function (level) {
  10556. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10557. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10558. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10559. return;
  10560. }
  10561. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10562. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10563. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10564. return;
  10565. }
  10566. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10567. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10568. },
  10569. enumerable: true,
  10570. configurable: true
  10571. });
  10572. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10573. };
  10574. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10575. };
  10576. Tools._StartUserMark = function (counterName, condition) {
  10577. if (condition === void 0) { condition = true; }
  10578. if (!Tools._performance) {
  10579. if (!Tools.IsWindowObjectExist()) {
  10580. return;
  10581. }
  10582. Tools._performance = window.performance;
  10583. }
  10584. if (!condition || !Tools._performance.mark) {
  10585. return;
  10586. }
  10587. Tools._performance.mark(counterName + "-Begin");
  10588. };
  10589. Tools._EndUserMark = function (counterName, condition) {
  10590. if (condition === void 0) { condition = true; }
  10591. if (!condition || !Tools._performance.mark) {
  10592. return;
  10593. }
  10594. Tools._performance.mark(counterName + "-End");
  10595. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10596. };
  10597. Tools._StartPerformanceConsole = function (counterName, condition) {
  10598. if (condition === void 0) { condition = true; }
  10599. if (!condition) {
  10600. return;
  10601. }
  10602. Tools._StartUserMark(counterName, condition);
  10603. if (console.time) {
  10604. console.time(counterName);
  10605. }
  10606. };
  10607. Tools._EndPerformanceConsole = function (counterName, condition) {
  10608. if (condition === void 0) { condition = true; }
  10609. if (!condition) {
  10610. return;
  10611. }
  10612. Tools._EndUserMark(counterName, condition);
  10613. if (console.time) {
  10614. console.timeEnd(counterName);
  10615. }
  10616. };
  10617. Object.defineProperty(Tools, "Now", {
  10618. /**
  10619. * Gets either window.performance.now() if supported or Date.now() else
  10620. */
  10621. get: function () {
  10622. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10623. return window.performance.now();
  10624. }
  10625. return Date.now();
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. /**
  10631. * This method will return the name of the class used to create the instance of the given object.
  10632. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10633. * @param object the object to get the class name from
  10634. * @param isType defines if the object is actually a type
  10635. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10636. */
  10637. Tools.GetClassName = function (object, isType) {
  10638. if (isType === void 0) { isType = false; }
  10639. var name = null;
  10640. if (!isType && object.getClassName) {
  10641. name = object.getClassName();
  10642. }
  10643. else {
  10644. if (object instanceof Object) {
  10645. var classObj = isType ? object : Object.getPrototypeOf(object);
  10646. name = classObj.constructor["__bjsclassName__"];
  10647. }
  10648. if (!name) {
  10649. name = typeof object;
  10650. }
  10651. }
  10652. return name;
  10653. };
  10654. /**
  10655. * Gets the first element of an array satisfying a given predicate
  10656. * @param array defines the array to browse
  10657. * @param predicate defines the predicate to use
  10658. * @returns null if not found or the element
  10659. */
  10660. Tools.First = function (array, predicate) {
  10661. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10662. var el = array_1[_i];
  10663. if (predicate(el)) {
  10664. return el;
  10665. }
  10666. }
  10667. return null;
  10668. };
  10669. /**
  10670. * This method will return the name of the full name of the class, including its owning module (if any).
  10671. * 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).
  10672. * @param object the object to get the class name from
  10673. * @param isType defines if the object is actually a type
  10674. * @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.
  10675. * @ignorenaming
  10676. */
  10677. Tools.getFullClassName = function (object, isType) {
  10678. if (isType === void 0) { isType = false; }
  10679. var className = null;
  10680. var moduleName = null;
  10681. if (!isType && object.getClassName) {
  10682. className = object.getClassName();
  10683. }
  10684. else {
  10685. if (object instanceof Object) {
  10686. var classObj = isType ? object : Object.getPrototypeOf(object);
  10687. className = classObj.constructor["__bjsclassName__"];
  10688. moduleName = classObj.constructor["__bjsmoduleName__"];
  10689. }
  10690. if (!className) {
  10691. className = typeof object;
  10692. }
  10693. }
  10694. if (!className) {
  10695. return null;
  10696. }
  10697. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10698. };
  10699. /**
  10700. * Returns a promise that resolves after the given amount of time.
  10701. * @param delay Number of milliseconds to delay
  10702. * @returns Promise that resolves after the given amount of time
  10703. */
  10704. Tools.DelayAsync = function (delay) {
  10705. return new Promise(function (resolve) {
  10706. setTimeout(function () {
  10707. resolve();
  10708. }, delay);
  10709. });
  10710. };
  10711. /**
  10712. * Gets the current gradient from an array of IValueGradient
  10713. * @param ratio defines the current ratio to get
  10714. * @param gradients defines the array of IValueGradient
  10715. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10716. */
  10717. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10718. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10719. var currentGradient = gradients[gradientIndex];
  10720. var nextGradient = gradients[gradientIndex + 1];
  10721. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10722. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10723. updateFunc(currentGradient, nextGradient, scale);
  10724. return;
  10725. }
  10726. }
  10727. // Use last index if over
  10728. var lastIndex = gradients.length - 1;
  10729. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10730. };
  10731. /**
  10732. * Gets or sets the base URL to use to load assets
  10733. */
  10734. Tools.BaseUrl = "";
  10735. /**
  10736. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10737. */
  10738. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10739. /**
  10740. * Default behaviour for cors in the application.
  10741. * It can be a string if the expected behavior is identical in the entire app.
  10742. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10743. */
  10744. Tools.CorsBehavior = "anonymous";
  10745. /**
  10746. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10747. * @ignorenaming
  10748. */
  10749. Tools.UseFallbackTexture = true;
  10750. /**
  10751. * Use this object to register external classes like custom textures or material
  10752. * to allow the laoders to instantiate them
  10753. */
  10754. Tools.RegisteredExternalClasses = {};
  10755. /**
  10756. * Texture content used if a texture cannot loaded
  10757. * @ignorenaming
  10758. */
  10759. 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";
  10760. Tools._tmpFloatArray = new Float32Array(1);
  10761. /**
  10762. * Gets or sets a function used to pre-process url before using them to load assets
  10763. */
  10764. Tools.PreprocessUrl = function (url) {
  10765. return url;
  10766. };
  10767. // Logs
  10768. /**
  10769. * No log
  10770. */
  10771. Tools.NoneLogLevel = 0;
  10772. /**
  10773. * Only message logs
  10774. */
  10775. Tools.MessageLogLevel = 1;
  10776. /**
  10777. * Only warning logs
  10778. */
  10779. Tools.WarningLogLevel = 2;
  10780. /**
  10781. * Only error logs
  10782. */
  10783. Tools.ErrorLogLevel = 4;
  10784. /**
  10785. * All logs
  10786. */
  10787. Tools.AllLogLevel = 7;
  10788. Tools._LogCache = "";
  10789. /**
  10790. * Gets a value indicating the number of loading errors
  10791. * @ignorenaming
  10792. */
  10793. Tools.errorsCount = 0;
  10794. /**
  10795. * Log a message to the console
  10796. */
  10797. Tools.Log = Tools._LogEnabled;
  10798. /**
  10799. * Write a warning message to the console
  10800. */
  10801. Tools.Warn = Tools._WarnEnabled;
  10802. /**
  10803. * Write an error message to the console
  10804. */
  10805. Tools.Error = Tools._ErrorEnabled;
  10806. // Performances
  10807. /**
  10808. * No performance log
  10809. */
  10810. Tools.PerformanceNoneLogLevel = 0;
  10811. /**
  10812. * Use user marks to log performance
  10813. */
  10814. Tools.PerformanceUserMarkLogLevel = 1;
  10815. /**
  10816. * Log performance to the console
  10817. */
  10818. Tools.PerformanceConsoleLogLevel = 2;
  10819. /**
  10820. * Starts a performance counter
  10821. */
  10822. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10823. /**
  10824. * Ends a specific performance coutner
  10825. */
  10826. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10827. return Tools;
  10828. }());
  10829. BABYLON.Tools = Tools;
  10830. /**
  10831. * This class is used to track a performance counter which is number based.
  10832. * The user has access to many properties which give statistics of different nature.
  10833. *
  10834. * The implementer can track two kinds of Performance Counter: time and count.
  10835. * 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.
  10836. * 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.
  10837. */
  10838. var PerfCounter = /** @class */ (function () {
  10839. /**
  10840. * Creates a new counter
  10841. */
  10842. function PerfCounter() {
  10843. this._startMonitoringTime = 0;
  10844. this._min = 0;
  10845. this._max = 0;
  10846. this._average = 0;
  10847. this._lastSecAverage = 0;
  10848. this._current = 0;
  10849. this._totalValueCount = 0;
  10850. this._totalAccumulated = 0;
  10851. this._lastSecAccumulated = 0;
  10852. this._lastSecTime = 0;
  10853. this._lastSecValueCount = 0;
  10854. }
  10855. Object.defineProperty(PerfCounter.prototype, "min", {
  10856. /**
  10857. * Returns the smallest value ever
  10858. */
  10859. get: function () {
  10860. return this._min;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(PerfCounter.prototype, "max", {
  10866. /**
  10867. * Returns the biggest value ever
  10868. */
  10869. get: function () {
  10870. return this._max;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. Object.defineProperty(PerfCounter.prototype, "average", {
  10876. /**
  10877. * Returns the average value since the performance counter is running
  10878. */
  10879. get: function () {
  10880. return this._average;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10886. /**
  10887. * Returns the average value of the last second the counter was monitored
  10888. */
  10889. get: function () {
  10890. return this._lastSecAverage;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(PerfCounter.prototype, "current", {
  10896. /**
  10897. * Returns the current value
  10898. */
  10899. get: function () {
  10900. return this._current;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(PerfCounter.prototype, "total", {
  10906. /**
  10907. * Gets the accumulated total
  10908. */
  10909. get: function () {
  10910. return this._totalAccumulated;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(PerfCounter.prototype, "count", {
  10916. /**
  10917. * Gets the total value count
  10918. */
  10919. get: function () {
  10920. return this._totalValueCount;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. /**
  10926. * Call this method to start monitoring a new frame.
  10927. * 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.
  10928. */
  10929. PerfCounter.prototype.fetchNewFrame = function () {
  10930. this._totalValueCount++;
  10931. this._current = 0;
  10932. this._lastSecValueCount++;
  10933. };
  10934. /**
  10935. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10936. * @param newCount the count value to add to the monitored count
  10937. * @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.
  10938. */
  10939. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10940. if (!PerfCounter.Enabled) {
  10941. return;
  10942. }
  10943. this._current += newCount;
  10944. if (fetchResult) {
  10945. this._fetchResult();
  10946. }
  10947. };
  10948. /**
  10949. * Start monitoring this performance counter
  10950. */
  10951. PerfCounter.prototype.beginMonitoring = function () {
  10952. if (!PerfCounter.Enabled) {
  10953. return;
  10954. }
  10955. this._startMonitoringTime = Tools.Now;
  10956. };
  10957. /**
  10958. * Compute the time lapsed since the previous beginMonitoring() call.
  10959. * @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
  10960. */
  10961. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10962. if (newFrame === void 0) { newFrame = true; }
  10963. if (!PerfCounter.Enabled) {
  10964. return;
  10965. }
  10966. if (newFrame) {
  10967. this.fetchNewFrame();
  10968. }
  10969. var currentTime = Tools.Now;
  10970. this._current = currentTime - this._startMonitoringTime;
  10971. if (newFrame) {
  10972. this._fetchResult();
  10973. }
  10974. };
  10975. PerfCounter.prototype._fetchResult = function () {
  10976. this._totalAccumulated += this._current;
  10977. this._lastSecAccumulated += this._current;
  10978. // Min/Max update
  10979. this._min = Math.min(this._min, this._current);
  10980. this._max = Math.max(this._max, this._current);
  10981. this._average = this._totalAccumulated / this._totalValueCount;
  10982. // Reset last sec?
  10983. var now = Tools.Now;
  10984. if ((now - this._lastSecTime) > 1000) {
  10985. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10986. this._lastSecTime = now;
  10987. this._lastSecAccumulated = 0;
  10988. this._lastSecValueCount = 0;
  10989. }
  10990. };
  10991. /**
  10992. * Gets or sets a global boolean to turn on and off all the counters
  10993. */
  10994. PerfCounter.Enabled = true;
  10995. return PerfCounter;
  10996. }());
  10997. BABYLON.PerfCounter = PerfCounter;
  10998. /**
  10999. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11000. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11001. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11002. * @param name The name of the class, case should be preserved
  11003. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11004. */
  11005. function className(name, module) {
  11006. return function (target) {
  11007. target["__bjsclassName__"] = name;
  11008. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11009. };
  11010. }
  11011. BABYLON.className = className;
  11012. /**
  11013. * An implementation of a loop for asynchronous functions.
  11014. */
  11015. var AsyncLoop = /** @class */ (function () {
  11016. /**
  11017. * Constructor.
  11018. * @param iterations the number of iterations.
  11019. * @param func the function to run each iteration
  11020. * @param successCallback the callback that will be called upon succesful execution
  11021. * @param offset starting offset.
  11022. */
  11023. function AsyncLoop(
  11024. /**
  11025. * Defines the number of iterations for the loop
  11026. */
  11027. iterations, func, successCallback, offset) {
  11028. if (offset === void 0) { offset = 0; }
  11029. this.iterations = iterations;
  11030. this.index = offset - 1;
  11031. this._done = false;
  11032. this._fn = func;
  11033. this._successCallback = successCallback;
  11034. }
  11035. /**
  11036. * Execute the next iteration. Must be called after the last iteration was finished.
  11037. */
  11038. AsyncLoop.prototype.executeNext = function () {
  11039. if (!this._done) {
  11040. if (this.index + 1 < this.iterations) {
  11041. ++this.index;
  11042. this._fn(this);
  11043. }
  11044. else {
  11045. this.breakLoop();
  11046. }
  11047. }
  11048. };
  11049. /**
  11050. * Break the loop and run the success callback.
  11051. */
  11052. AsyncLoop.prototype.breakLoop = function () {
  11053. this._done = true;
  11054. this._successCallback();
  11055. };
  11056. /**
  11057. * Create and run an async loop.
  11058. * @param iterations the number of iterations.
  11059. * @param fn the function to run each iteration
  11060. * @param successCallback the callback that will be called upon succesful execution
  11061. * @param offset starting offset.
  11062. * @returns the created async loop object
  11063. */
  11064. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11065. if (offset === void 0) { offset = 0; }
  11066. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11067. loop.executeNext();
  11068. return loop;
  11069. };
  11070. /**
  11071. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11072. * @param iterations total number of iterations
  11073. * @param syncedIterations number of synchronous iterations in each async iteration.
  11074. * @param fn the function to call each iteration.
  11075. * @param callback a success call back that will be called when iterating stops.
  11076. * @param breakFunction a break condition (optional)
  11077. * @param timeout timeout settings for the setTimeout function. default - 0.
  11078. * @returns the created async loop object
  11079. */
  11080. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11081. if (timeout === void 0) { timeout = 0; }
  11082. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11083. if (breakFunction && breakFunction())
  11084. loop.breakLoop();
  11085. else {
  11086. setTimeout(function () {
  11087. for (var i = 0; i < syncedIterations; ++i) {
  11088. var iteration = (loop.index * syncedIterations) + i;
  11089. if (iteration >= iterations)
  11090. break;
  11091. fn(iteration);
  11092. if (breakFunction && breakFunction()) {
  11093. loop.breakLoop();
  11094. break;
  11095. }
  11096. }
  11097. loop.executeNext();
  11098. }, timeout);
  11099. }
  11100. }, callback);
  11101. };
  11102. return AsyncLoop;
  11103. }());
  11104. BABYLON.AsyncLoop = AsyncLoop;
  11105. })(BABYLON || (BABYLON = {}));
  11106. //# sourceMappingURL=babylon.tools.js.map
  11107. var BABYLON;
  11108. (function (BABYLON) {
  11109. var PromiseStates;
  11110. (function (PromiseStates) {
  11111. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11112. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11113. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11114. })(PromiseStates || (PromiseStates = {}));
  11115. var FulFillmentAgregator = /** @class */ (function () {
  11116. function FulFillmentAgregator() {
  11117. this.count = 0;
  11118. this.target = 0;
  11119. this.results = [];
  11120. }
  11121. return FulFillmentAgregator;
  11122. }());
  11123. var InternalPromise = /** @class */ (function () {
  11124. function InternalPromise(resolver) {
  11125. var _this = this;
  11126. this._state = PromiseStates.Pending;
  11127. this._children = new Array();
  11128. this._rejectWasConsumed = false;
  11129. if (!resolver) {
  11130. return;
  11131. }
  11132. try {
  11133. resolver(function (value) {
  11134. _this._resolve(value);
  11135. }, function (reason) {
  11136. _this._reject(reason);
  11137. });
  11138. }
  11139. catch (e) {
  11140. this._reject(e);
  11141. }
  11142. }
  11143. Object.defineProperty(InternalPromise.prototype, "_result", {
  11144. get: function () {
  11145. return this._resultValue;
  11146. },
  11147. set: function (value) {
  11148. this._resultValue = value;
  11149. if (this._parent && this._parent._result === undefined) {
  11150. this._parent._result = value;
  11151. }
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. InternalPromise.prototype.catch = function (onRejected) {
  11157. return this.then(undefined, onRejected);
  11158. };
  11159. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11160. var _this = this;
  11161. var newPromise = new InternalPromise();
  11162. newPromise._onFulfilled = onFulfilled;
  11163. newPromise._onRejected = onRejected;
  11164. // Composition
  11165. this._children.push(newPromise);
  11166. newPromise._parent = this;
  11167. if (this._state !== PromiseStates.Pending) {
  11168. BABYLON.Tools.SetImmediate(function () {
  11169. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11170. var returnedValue = newPromise._resolve(_this._result);
  11171. if (returnedValue !== undefined && returnedValue !== null) {
  11172. if (returnedValue._state !== undefined) {
  11173. var returnedPromise = returnedValue;
  11174. newPromise._children.push(returnedPromise);
  11175. returnedPromise._parent = newPromise;
  11176. newPromise = returnedPromise;
  11177. }
  11178. else {
  11179. newPromise._result = returnedValue;
  11180. }
  11181. }
  11182. }
  11183. else {
  11184. newPromise._reject(_this._reason);
  11185. }
  11186. });
  11187. }
  11188. return newPromise;
  11189. };
  11190. InternalPromise.prototype._moveChildren = function (children) {
  11191. var _this = this;
  11192. var _a;
  11193. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11194. this._children.forEach(function (child) {
  11195. child._parent = _this;
  11196. });
  11197. if (this._state === PromiseStates.Fulfilled) {
  11198. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11199. var child = _b[_i];
  11200. child._resolve(this._result);
  11201. }
  11202. }
  11203. else if (this._state === PromiseStates.Rejected) {
  11204. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11205. var child = _d[_c];
  11206. child._reject(this._reason);
  11207. }
  11208. }
  11209. };
  11210. InternalPromise.prototype._resolve = function (value) {
  11211. try {
  11212. this._state = PromiseStates.Fulfilled;
  11213. var returnedValue = null;
  11214. if (this._onFulfilled) {
  11215. returnedValue = this._onFulfilled(value);
  11216. }
  11217. if (returnedValue !== undefined && returnedValue !== null) {
  11218. if (returnedValue._state !== undefined) {
  11219. // Transmit children
  11220. var returnedPromise = returnedValue;
  11221. returnedPromise._parent = this;
  11222. returnedPromise._moveChildren(this._children);
  11223. value = returnedPromise._result;
  11224. }
  11225. else {
  11226. value = returnedValue;
  11227. }
  11228. }
  11229. this._result = value;
  11230. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11231. var child = _a[_i];
  11232. child._resolve(value);
  11233. }
  11234. this._children.length = 0;
  11235. delete this._onFulfilled;
  11236. delete this._onRejected;
  11237. }
  11238. catch (e) {
  11239. this._reject(e, true);
  11240. }
  11241. };
  11242. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11243. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11244. this._state = PromiseStates.Rejected;
  11245. this._reason = reason;
  11246. if (this._onRejected && !onLocalThrow) {
  11247. try {
  11248. this._onRejected(reason);
  11249. this._rejectWasConsumed = true;
  11250. }
  11251. catch (e) {
  11252. reason = e;
  11253. }
  11254. }
  11255. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11256. var child = _a[_i];
  11257. if (this._rejectWasConsumed) {
  11258. child._resolve(null);
  11259. }
  11260. else {
  11261. child._reject(reason);
  11262. }
  11263. }
  11264. this._children.length = 0;
  11265. delete this._onFulfilled;
  11266. delete this._onRejected;
  11267. };
  11268. InternalPromise.resolve = function (value) {
  11269. var newPromise = new InternalPromise();
  11270. newPromise._resolve(value);
  11271. return newPromise;
  11272. };
  11273. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11274. promise.then(function (value) {
  11275. agregator.results[index] = value;
  11276. agregator.count++;
  11277. if (agregator.count === agregator.target) {
  11278. agregator.rootPromise._resolve(agregator.results);
  11279. }
  11280. return null;
  11281. }, function (reason) {
  11282. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11283. agregator.rootPromise._reject(reason);
  11284. }
  11285. });
  11286. };
  11287. InternalPromise.all = function (promises) {
  11288. var newPromise = new InternalPromise();
  11289. var agregator = new FulFillmentAgregator();
  11290. agregator.target = promises.length;
  11291. agregator.rootPromise = newPromise;
  11292. if (promises.length) {
  11293. for (var index = 0; index < promises.length; index++) {
  11294. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11295. }
  11296. }
  11297. else {
  11298. newPromise._resolve([]);
  11299. }
  11300. return newPromise;
  11301. };
  11302. InternalPromise.race = function (promises) {
  11303. var newPromise = new InternalPromise();
  11304. if (promises.length) {
  11305. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11306. var promise = promises_1[_i];
  11307. promise.then(function (value) {
  11308. if (newPromise) {
  11309. newPromise._resolve(value);
  11310. newPromise = null;
  11311. }
  11312. return null;
  11313. }, function (reason) {
  11314. if (newPromise) {
  11315. newPromise._reject(reason);
  11316. newPromise = null;
  11317. }
  11318. });
  11319. }
  11320. }
  11321. return newPromise;
  11322. };
  11323. return InternalPromise;
  11324. }());
  11325. /**
  11326. * Helper class that provides a small promise polyfill
  11327. */
  11328. var PromisePolyfill = /** @class */ (function () {
  11329. function PromisePolyfill() {
  11330. }
  11331. /**
  11332. * Static function used to check if the polyfill is required
  11333. * If this is the case then the function will inject the polyfill to window.Promise
  11334. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11335. */
  11336. PromisePolyfill.Apply = function (force) {
  11337. if (force === void 0) { force = false; }
  11338. if (force || typeof Promise === 'undefined') {
  11339. var root = window;
  11340. root.Promise = InternalPromise;
  11341. }
  11342. };
  11343. return PromisePolyfill;
  11344. }());
  11345. BABYLON.PromisePolyfill = PromisePolyfill;
  11346. })(BABYLON || (BABYLON = {}));
  11347. //# sourceMappingURL=babylon.promise.js.map
  11348. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11349. var BABYLON;
  11350. (function (BABYLON) {
  11351. /**
  11352. * Helper class to push actions to a pool of workers.
  11353. */
  11354. var WorkerPool = /** @class */ (function () {
  11355. /**
  11356. * Constructor
  11357. * @param workers Array of workers to use for actions
  11358. */
  11359. function WorkerPool(workers) {
  11360. this._pendingActions = new Array();
  11361. this._workerInfos = workers.map(function (worker) { return ({
  11362. worker: worker,
  11363. active: false
  11364. }); });
  11365. }
  11366. /**
  11367. * Terminates all workers and clears any pending actions.
  11368. */
  11369. WorkerPool.prototype.dispose = function () {
  11370. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11371. var workerInfo = _a[_i];
  11372. workerInfo.worker.terminate();
  11373. }
  11374. delete this._workerInfos;
  11375. delete this._pendingActions;
  11376. };
  11377. /**
  11378. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11379. * pended until a worker has completed its action.
  11380. * @param action The action to perform. Call onComplete when the action is complete.
  11381. */
  11382. WorkerPool.prototype.push = function (action) {
  11383. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11384. var workerInfo = _a[_i];
  11385. if (!workerInfo.active) {
  11386. this._execute(workerInfo, action);
  11387. return;
  11388. }
  11389. }
  11390. this._pendingActions.push(action);
  11391. };
  11392. WorkerPool.prototype._execute = function (workerInfo, action) {
  11393. var _this = this;
  11394. workerInfo.active = true;
  11395. action(workerInfo.worker, function () {
  11396. workerInfo.active = false;
  11397. var nextAction = _this._pendingActions.shift();
  11398. if (nextAction) {
  11399. _this._execute(workerInfo, nextAction);
  11400. }
  11401. });
  11402. };
  11403. return WorkerPool;
  11404. }());
  11405. BABYLON.WorkerPool = WorkerPool;
  11406. })(BABYLON || (BABYLON = {}));
  11407. //# sourceMappingURL=babylon.workerPool.js.map
  11408. var BABYLON;
  11409. (function (BABYLON) {
  11410. /**
  11411. * @hidden
  11412. **/
  11413. var _AlphaState = /** @class */ (function () {
  11414. /**
  11415. * Initializes the state.
  11416. */
  11417. function _AlphaState() {
  11418. this._isAlphaBlendDirty = false;
  11419. this._isBlendFunctionParametersDirty = false;
  11420. this._isBlendEquationParametersDirty = false;
  11421. this._isBlendConstantsDirty = false;
  11422. this._alphaBlend = false;
  11423. this._blendFunctionParameters = new Array(4);
  11424. this._blendEquationParameters = new Array(2);
  11425. this._blendConstants = new Array(4);
  11426. this.reset();
  11427. }
  11428. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11429. get: function () {
  11430. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11431. },
  11432. enumerable: true,
  11433. configurable: true
  11434. });
  11435. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11436. get: function () {
  11437. return this._alphaBlend;
  11438. },
  11439. set: function (value) {
  11440. if (this._alphaBlend === value) {
  11441. return;
  11442. }
  11443. this._alphaBlend = value;
  11444. this._isAlphaBlendDirty = true;
  11445. },
  11446. enumerable: true,
  11447. configurable: true
  11448. });
  11449. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11450. if (this._blendConstants[0] === r &&
  11451. this._blendConstants[1] === g &&
  11452. this._blendConstants[2] === b &&
  11453. this._blendConstants[3] === a) {
  11454. return;
  11455. }
  11456. this._blendConstants[0] = r;
  11457. this._blendConstants[1] = g;
  11458. this._blendConstants[2] = b;
  11459. this._blendConstants[3] = a;
  11460. this._isBlendConstantsDirty = true;
  11461. };
  11462. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11463. if (this._blendFunctionParameters[0] === value0 &&
  11464. this._blendFunctionParameters[1] === value1 &&
  11465. this._blendFunctionParameters[2] === value2 &&
  11466. this._blendFunctionParameters[3] === value3) {
  11467. return;
  11468. }
  11469. this._blendFunctionParameters[0] = value0;
  11470. this._blendFunctionParameters[1] = value1;
  11471. this._blendFunctionParameters[2] = value2;
  11472. this._blendFunctionParameters[3] = value3;
  11473. this._isBlendFunctionParametersDirty = true;
  11474. };
  11475. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11476. if (this._blendEquationParameters[0] === rgb &&
  11477. this._blendEquationParameters[1] === alpha) {
  11478. return;
  11479. }
  11480. this._blendEquationParameters[0] = rgb;
  11481. this._blendEquationParameters[1] = alpha;
  11482. this._isBlendEquationParametersDirty = true;
  11483. };
  11484. _AlphaState.prototype.reset = function () {
  11485. this._alphaBlend = false;
  11486. this._blendFunctionParameters[0] = null;
  11487. this._blendFunctionParameters[1] = null;
  11488. this._blendFunctionParameters[2] = null;
  11489. this._blendFunctionParameters[3] = null;
  11490. this._blendEquationParameters[0] = null;
  11491. this._blendEquationParameters[1] = null;
  11492. this._blendConstants[0] = null;
  11493. this._blendConstants[1] = null;
  11494. this._blendConstants[2] = null;
  11495. this._blendConstants[3] = null;
  11496. this._isAlphaBlendDirty = true;
  11497. this._isBlendFunctionParametersDirty = false;
  11498. this._isBlendEquationParametersDirty = false;
  11499. this._isBlendConstantsDirty = false;
  11500. };
  11501. _AlphaState.prototype.apply = function (gl) {
  11502. if (!this.isDirty) {
  11503. return;
  11504. }
  11505. // Alpha blend
  11506. if (this._isAlphaBlendDirty) {
  11507. if (this._alphaBlend) {
  11508. gl.enable(gl.BLEND);
  11509. }
  11510. else {
  11511. gl.disable(gl.BLEND);
  11512. }
  11513. this._isAlphaBlendDirty = false;
  11514. }
  11515. // Alpha function
  11516. if (this._isBlendFunctionParametersDirty) {
  11517. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11518. this._isBlendFunctionParametersDirty = false;
  11519. }
  11520. // Alpha equation
  11521. if (this._isBlendEquationParametersDirty) {
  11522. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11523. this._isBlendEquationParametersDirty = false;
  11524. }
  11525. // Constants
  11526. if (this._isBlendConstantsDirty) {
  11527. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11528. this._isBlendConstantsDirty = false;
  11529. }
  11530. };
  11531. return _AlphaState;
  11532. }());
  11533. BABYLON._AlphaState = _AlphaState;
  11534. })(BABYLON || (BABYLON = {}));
  11535. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11536. var BABYLON;
  11537. (function (BABYLON) {
  11538. /**
  11539. * @hidden
  11540. **/
  11541. var _DepthCullingState = /** @class */ (function () {
  11542. /**
  11543. * Initializes the state.
  11544. */
  11545. function _DepthCullingState() {
  11546. this._isDepthTestDirty = false;
  11547. this._isDepthMaskDirty = false;
  11548. this._isDepthFuncDirty = false;
  11549. this._isCullFaceDirty = false;
  11550. this._isCullDirty = false;
  11551. this._isZOffsetDirty = false;
  11552. this._isFrontFaceDirty = false;
  11553. this.reset();
  11554. }
  11555. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11556. get: function () {
  11557. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11558. },
  11559. enumerable: true,
  11560. configurable: true
  11561. });
  11562. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11563. get: function () {
  11564. return this._zOffset;
  11565. },
  11566. set: function (value) {
  11567. if (this._zOffset === value) {
  11568. return;
  11569. }
  11570. this._zOffset = value;
  11571. this._isZOffsetDirty = true;
  11572. },
  11573. enumerable: true,
  11574. configurable: true
  11575. });
  11576. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11577. get: function () {
  11578. return this._cullFace;
  11579. },
  11580. set: function (value) {
  11581. if (this._cullFace === value) {
  11582. return;
  11583. }
  11584. this._cullFace = value;
  11585. this._isCullFaceDirty = true;
  11586. },
  11587. enumerable: true,
  11588. configurable: true
  11589. });
  11590. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11591. get: function () {
  11592. return this._cull;
  11593. },
  11594. set: function (value) {
  11595. if (this._cull === value) {
  11596. return;
  11597. }
  11598. this._cull = value;
  11599. this._isCullDirty = true;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11605. get: function () {
  11606. return this._depthFunc;
  11607. },
  11608. set: function (value) {
  11609. if (this._depthFunc === value) {
  11610. return;
  11611. }
  11612. this._depthFunc = value;
  11613. this._isDepthFuncDirty = true;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11619. get: function () {
  11620. return this._depthMask;
  11621. },
  11622. set: function (value) {
  11623. if (this._depthMask === value) {
  11624. return;
  11625. }
  11626. this._depthMask = value;
  11627. this._isDepthMaskDirty = true;
  11628. },
  11629. enumerable: true,
  11630. configurable: true
  11631. });
  11632. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11633. get: function () {
  11634. return this._depthTest;
  11635. },
  11636. set: function (value) {
  11637. if (this._depthTest === value) {
  11638. return;
  11639. }
  11640. this._depthTest = value;
  11641. this._isDepthTestDirty = true;
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11647. get: function () {
  11648. return this._frontFace;
  11649. },
  11650. set: function (value) {
  11651. if (this._frontFace === value) {
  11652. return;
  11653. }
  11654. this._frontFace = value;
  11655. this._isFrontFaceDirty = true;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. _DepthCullingState.prototype.reset = function () {
  11661. this._depthMask = true;
  11662. this._depthTest = true;
  11663. this._depthFunc = null;
  11664. this._cullFace = null;
  11665. this._cull = null;
  11666. this._zOffset = 0;
  11667. this._frontFace = null;
  11668. this._isDepthTestDirty = true;
  11669. this._isDepthMaskDirty = true;
  11670. this._isDepthFuncDirty = false;
  11671. this._isCullFaceDirty = false;
  11672. this._isCullDirty = false;
  11673. this._isZOffsetDirty = false;
  11674. this._isFrontFaceDirty = false;
  11675. };
  11676. _DepthCullingState.prototype.apply = function (gl) {
  11677. if (!this.isDirty) {
  11678. return;
  11679. }
  11680. // Cull
  11681. if (this._isCullDirty) {
  11682. if (this.cull) {
  11683. gl.enable(gl.CULL_FACE);
  11684. }
  11685. else {
  11686. gl.disable(gl.CULL_FACE);
  11687. }
  11688. this._isCullDirty = false;
  11689. }
  11690. // Cull face
  11691. if (this._isCullFaceDirty) {
  11692. gl.cullFace(this.cullFace);
  11693. this._isCullFaceDirty = false;
  11694. }
  11695. // Depth mask
  11696. if (this._isDepthMaskDirty) {
  11697. gl.depthMask(this.depthMask);
  11698. this._isDepthMaskDirty = false;
  11699. }
  11700. // Depth test
  11701. if (this._isDepthTestDirty) {
  11702. if (this.depthTest) {
  11703. gl.enable(gl.DEPTH_TEST);
  11704. }
  11705. else {
  11706. gl.disable(gl.DEPTH_TEST);
  11707. }
  11708. this._isDepthTestDirty = false;
  11709. }
  11710. // Depth func
  11711. if (this._isDepthFuncDirty) {
  11712. gl.depthFunc(this.depthFunc);
  11713. this._isDepthFuncDirty = false;
  11714. }
  11715. // zOffset
  11716. if (this._isZOffsetDirty) {
  11717. if (this.zOffset) {
  11718. gl.enable(gl.POLYGON_OFFSET_FILL);
  11719. gl.polygonOffset(this.zOffset, 0);
  11720. }
  11721. else {
  11722. gl.disable(gl.POLYGON_OFFSET_FILL);
  11723. }
  11724. this._isZOffsetDirty = false;
  11725. }
  11726. // Front face
  11727. if (this._isFrontFaceDirty) {
  11728. gl.frontFace(this.frontFace);
  11729. this._isFrontFaceDirty = false;
  11730. }
  11731. };
  11732. return _DepthCullingState;
  11733. }());
  11734. BABYLON._DepthCullingState = _DepthCullingState;
  11735. })(BABYLON || (BABYLON = {}));
  11736. //# sourceMappingURL=babylon.depthCullingState.js.map
  11737. var BABYLON;
  11738. (function (BABYLON) {
  11739. /**
  11740. * @hidden
  11741. **/
  11742. var _StencilState = /** @class */ (function () {
  11743. function _StencilState() {
  11744. this._isStencilTestDirty = false;
  11745. this._isStencilMaskDirty = false;
  11746. this._isStencilFuncDirty = false;
  11747. this._isStencilOpDirty = false;
  11748. this.reset();
  11749. }
  11750. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11751. get: function () {
  11752. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11758. get: function () {
  11759. return this._stencilFunc;
  11760. },
  11761. set: function (value) {
  11762. if (this._stencilFunc === value) {
  11763. return;
  11764. }
  11765. this._stencilFunc = value;
  11766. this._isStencilFuncDirty = true;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11772. get: function () {
  11773. return this._stencilFuncRef;
  11774. },
  11775. set: function (value) {
  11776. if (this._stencilFuncRef === value) {
  11777. return;
  11778. }
  11779. this._stencilFuncRef = value;
  11780. this._isStencilFuncDirty = true;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11786. get: function () {
  11787. return this._stencilFuncMask;
  11788. },
  11789. set: function (value) {
  11790. if (this._stencilFuncMask === value) {
  11791. return;
  11792. }
  11793. this._stencilFuncMask = value;
  11794. this._isStencilFuncDirty = true;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11800. get: function () {
  11801. return this._stencilOpStencilFail;
  11802. },
  11803. set: function (value) {
  11804. if (this._stencilOpStencilFail === value) {
  11805. return;
  11806. }
  11807. this._stencilOpStencilFail = value;
  11808. this._isStencilOpDirty = true;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11814. get: function () {
  11815. return this._stencilOpDepthFail;
  11816. },
  11817. set: function (value) {
  11818. if (this._stencilOpDepthFail === value) {
  11819. return;
  11820. }
  11821. this._stencilOpDepthFail = value;
  11822. this._isStencilOpDirty = true;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11828. get: function () {
  11829. return this._stencilOpStencilDepthPass;
  11830. },
  11831. set: function (value) {
  11832. if (this._stencilOpStencilDepthPass === value) {
  11833. return;
  11834. }
  11835. this._stencilOpStencilDepthPass = value;
  11836. this._isStencilOpDirty = true;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11842. get: function () {
  11843. return this._stencilMask;
  11844. },
  11845. set: function (value) {
  11846. if (this._stencilMask === value) {
  11847. return;
  11848. }
  11849. this._stencilMask = value;
  11850. this._isStencilMaskDirty = true;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11856. get: function () {
  11857. return this._stencilTest;
  11858. },
  11859. set: function (value) {
  11860. if (this._stencilTest === value) {
  11861. return;
  11862. }
  11863. this._stencilTest = value;
  11864. this._isStencilTestDirty = true;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. _StencilState.prototype.reset = function () {
  11870. this._stencilTest = false;
  11871. this._stencilMask = 0xFF;
  11872. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11873. this._stencilFuncRef = 1;
  11874. this._stencilFuncMask = 0xFF;
  11875. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11876. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11877. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11878. this._isStencilTestDirty = true;
  11879. this._isStencilMaskDirty = true;
  11880. this._isStencilFuncDirty = true;
  11881. this._isStencilOpDirty = true;
  11882. };
  11883. _StencilState.prototype.apply = function (gl) {
  11884. if (!this.isDirty) {
  11885. return;
  11886. }
  11887. // Stencil test
  11888. if (this._isStencilTestDirty) {
  11889. if (this.stencilTest) {
  11890. gl.enable(gl.STENCIL_TEST);
  11891. }
  11892. else {
  11893. gl.disable(gl.STENCIL_TEST);
  11894. }
  11895. this._isStencilTestDirty = false;
  11896. }
  11897. // Stencil mask
  11898. if (this._isStencilMaskDirty) {
  11899. gl.stencilMask(this.stencilMask);
  11900. this._isStencilMaskDirty = false;
  11901. }
  11902. // Stencil func
  11903. if (this._isStencilFuncDirty) {
  11904. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11905. this._isStencilFuncDirty = false;
  11906. }
  11907. // Stencil op
  11908. if (this._isStencilOpDirty) {
  11909. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11910. this._isStencilOpDirty = false;
  11911. }
  11912. };
  11913. return _StencilState;
  11914. }());
  11915. BABYLON._StencilState = _StencilState;
  11916. })(BABYLON || (BABYLON = {}));
  11917. //# sourceMappingURL=babylon.stencilState.js.map
  11918. var __assign = (this && this.__assign) || function () {
  11919. __assign = Object.assign || function(t) {
  11920. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11921. s = arguments[i];
  11922. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11923. t[p] = s[p];
  11924. }
  11925. return t;
  11926. };
  11927. return __assign.apply(this, arguments);
  11928. };
  11929. var BABYLON;
  11930. (function (BABYLON) {
  11931. /**
  11932. * Keeps track of all the buffer info used in engine.
  11933. */
  11934. var BufferPointer = /** @class */ (function () {
  11935. function BufferPointer() {
  11936. }
  11937. return BufferPointer;
  11938. }());
  11939. /**
  11940. * Interface for attribute information associated with buffer instanciation
  11941. */
  11942. var InstancingAttributeInfo = /** @class */ (function () {
  11943. function InstancingAttributeInfo() {
  11944. }
  11945. return InstancingAttributeInfo;
  11946. }());
  11947. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11948. /**
  11949. * Define options used to create a render target texture
  11950. */
  11951. var RenderTargetCreationOptions = /** @class */ (function () {
  11952. function RenderTargetCreationOptions() {
  11953. }
  11954. return RenderTargetCreationOptions;
  11955. }());
  11956. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11957. /**
  11958. * Define options used to create a depth texture
  11959. */
  11960. var DepthTextureCreationOptions = /** @class */ (function () {
  11961. function DepthTextureCreationOptions() {
  11962. }
  11963. return DepthTextureCreationOptions;
  11964. }());
  11965. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11966. /**
  11967. * Class used to describe the capabilities of the engine relatively to the current browser
  11968. */
  11969. var EngineCapabilities = /** @class */ (function () {
  11970. function EngineCapabilities() {
  11971. }
  11972. return EngineCapabilities;
  11973. }());
  11974. BABYLON.EngineCapabilities = EngineCapabilities;
  11975. /**
  11976. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11977. */
  11978. var Engine = /** @class */ (function () {
  11979. /**
  11980. * Creates a new engine
  11981. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11982. * @param antialias defines enable antialiasing (default: false)
  11983. * @param options defines further options to be sent to the getContext() function
  11984. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11985. */
  11986. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11987. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11988. var _this = this;
  11989. // Public members
  11990. /**
  11991. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11992. */
  11993. this.forcePOTTextures = false;
  11994. /**
  11995. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11996. */
  11997. this.isFullscreen = false;
  11998. /**
  11999. * Gets a boolean indicating if the pointer is currently locked
  12000. */
  12001. this.isPointerLock = false;
  12002. /**
  12003. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12004. */
  12005. this.cullBackFaces = true;
  12006. /**
  12007. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12008. */
  12009. this.renderEvenInBackground = true;
  12010. /**
  12011. * Gets or sets a boolean indicating that cache can be kept between frames
  12012. */
  12013. this.preventCacheWipeBetweenFrames = false;
  12014. /**
  12015. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12016. **/
  12017. this.enableOfflineSupport = false;
  12018. /**
  12019. * 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)
  12020. **/
  12021. this.disableManifestCheck = false;
  12022. /**
  12023. * Gets the list of created scenes
  12024. */
  12025. this.scenes = new Array();
  12026. /**
  12027. * Gets the list of created postprocesses
  12028. */
  12029. this.postProcesses = new Array();
  12030. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12031. this.validateShaderPrograms = false;
  12032. // Observables
  12033. /**
  12034. * Observable event triggered each time the rendering canvas is resized
  12035. */
  12036. this.onResizeObservable = new BABYLON.Observable();
  12037. /**
  12038. * Observable event triggered each time the canvas loses focus
  12039. */
  12040. this.onCanvasBlurObservable = new BABYLON.Observable();
  12041. /**
  12042. * Observable event triggered each time the canvas gains focus
  12043. */
  12044. this.onCanvasFocusObservable = new BABYLON.Observable();
  12045. /**
  12046. * Observable event triggered each time the canvas receives pointerout event
  12047. */
  12048. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12049. /**
  12050. * Observable event triggered before each texture is initialized
  12051. */
  12052. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12053. //WebVR
  12054. this._vrDisplay = undefined;
  12055. this._vrSupported = false;
  12056. this._vrExclusivePointerMode = false;
  12057. // Uniform buffers list
  12058. /**
  12059. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12060. */
  12061. this.disableUniformBuffers = false;
  12062. /** @hidden */
  12063. this._uniformBuffers = new Array();
  12064. // Observables
  12065. /**
  12066. * Observable raised when the engine begins a new frame
  12067. */
  12068. this.onBeginFrameObservable = new BABYLON.Observable();
  12069. /**
  12070. * Observable raised when the engine ends the current frame
  12071. */
  12072. this.onEndFrameObservable = new BABYLON.Observable();
  12073. /**
  12074. * Observable raised when the engine is about to compile a shader
  12075. */
  12076. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12077. /**
  12078. * Observable raised when the engine has jsut compiled a shader
  12079. */
  12080. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12081. this._windowIsBackground = false;
  12082. this._webGLVersion = 1.0;
  12083. /** @hidden */
  12084. this._badOS = false;
  12085. /** @hidden */
  12086. this._badDesktopOS = false;
  12087. /**
  12088. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12089. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12090. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12091. */
  12092. this.disableTextureBindingOptimization = false;
  12093. /**
  12094. * Observable signaled when VR display mode changes
  12095. */
  12096. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12097. /**
  12098. * Observable signaled when VR request present is complete
  12099. */
  12100. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12101. /**
  12102. * Observable signaled when VR request present starts
  12103. */
  12104. this.onVRRequestPresentStart = new BABYLON.Observable();
  12105. this._colorWrite = true;
  12106. /** @hidden */
  12107. this._drawCalls = new BABYLON.PerfCounter();
  12108. /** @hidden */
  12109. this._textureCollisions = new BABYLON.PerfCounter();
  12110. this._renderingQueueLaunched = false;
  12111. this._activeRenderLoops = new Array();
  12112. // Deterministic lockstepMaxSteps
  12113. this._deterministicLockstep = false;
  12114. this._lockstepMaxSteps = 4;
  12115. // Lost context
  12116. /**
  12117. * Observable signaled when a context lost event is raised
  12118. */
  12119. this.onContextLostObservable = new BABYLON.Observable();
  12120. /**
  12121. * Observable signaled when a context restored event is raised
  12122. */
  12123. this.onContextRestoredObservable = new BABYLON.Observable();
  12124. this._contextWasLost = false;
  12125. this._doNotHandleContextLost = false;
  12126. // FPS
  12127. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12128. this._fps = 60;
  12129. this._deltaTime = 0;
  12130. /**
  12131. * Turn this value on if you want to pause FPS computation when in background
  12132. */
  12133. this.disablePerformanceMonitorInBackground = false;
  12134. // States
  12135. /** @hidden */
  12136. this._depthCullingState = new BABYLON._DepthCullingState();
  12137. /** @hidden */
  12138. this._stencilState = new BABYLON._StencilState();
  12139. /** @hidden */
  12140. this._alphaState = new BABYLON._AlphaState();
  12141. /** @hidden */
  12142. this._alphaMode = Engine.ALPHA_DISABLE;
  12143. // Cache
  12144. this._internalTexturesCache = new Array();
  12145. /** @hidden */
  12146. this._activeChannel = 0;
  12147. this._currentTextureChannel = -1;
  12148. /** @hidden */
  12149. this._boundTexturesCache = {};
  12150. this._compiledEffects = {};
  12151. this._vertexAttribArraysEnabled = [];
  12152. this._uintIndicesCurrentlySet = false;
  12153. this._currentBoundBuffer = new Array();
  12154. /** @hidden */
  12155. this._currentFramebuffer = null;
  12156. this._currentBufferPointers = new Array();
  12157. this._currentInstanceLocations = new Array();
  12158. this._currentInstanceBuffers = new Array();
  12159. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12160. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12161. this._vaoRecordInProgress = false;
  12162. this._mustWipeVertexAttributes = false;
  12163. this._nextFreeTextureSlots = new Array();
  12164. this._maxSimultaneousTextures = 0;
  12165. this._activeRequests = new Array();
  12166. // Hardware supported Compressed Textures
  12167. this._texturesSupported = new Array();
  12168. /**
  12169. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12170. */
  12171. this.premultipliedAlpha = true;
  12172. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12173. this._onVRFullScreenTriggered = function () {
  12174. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12175. //get the old size before we change
  12176. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12177. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12178. //get the width and height, change the render size
  12179. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12180. _this.setHardwareScalingLevel(1);
  12181. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12182. }
  12183. else {
  12184. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12185. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12186. }
  12187. };
  12188. this._unpackFlipYCached = null;
  12189. /**
  12190. * In case you are sharing the context with other applications, it might
  12191. * be interested to not cache the unpack flip y state to ensure a consistent
  12192. * value would be set.
  12193. */
  12194. this.enableUnpackFlipYCached = true;
  12195. this._boundUniforms = {};
  12196. // Register promises
  12197. BABYLON.PromisePolyfill.Apply();
  12198. var canvas = null;
  12199. Engine.Instances.push(this);
  12200. if (!canvasOrContext) {
  12201. return;
  12202. }
  12203. options = options || {};
  12204. if (canvasOrContext.getContext) {
  12205. canvas = canvasOrContext;
  12206. this._renderingCanvas = canvas;
  12207. if (antialias != null) {
  12208. options.antialias = antialias;
  12209. }
  12210. if (options.deterministicLockstep === undefined) {
  12211. options.deterministicLockstep = false;
  12212. }
  12213. if (options.lockstepMaxSteps === undefined) {
  12214. options.lockstepMaxSteps = 4;
  12215. }
  12216. if (options.preserveDrawingBuffer === undefined) {
  12217. options.preserveDrawingBuffer = false;
  12218. }
  12219. if (options.audioEngine === undefined) {
  12220. options.audioEngine = true;
  12221. }
  12222. if (options.stencil === undefined) {
  12223. options.stencil = true;
  12224. }
  12225. if (options.premultipliedAlpha === false) {
  12226. this.premultipliedAlpha = false;
  12227. }
  12228. this._deterministicLockstep = options.deterministicLockstep;
  12229. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12230. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12231. // Exceptions
  12232. if (navigator && navigator.userAgent) {
  12233. var ua = navigator.userAgent;
  12234. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12235. var exception = _a[_i];
  12236. var key = exception.key;
  12237. var targets = exception.targets;
  12238. if (ua.indexOf(key) > -1) {
  12239. if (exception.capture && exception.captureConstraint) {
  12240. var capture = exception.capture;
  12241. var constraint = exception.captureConstraint;
  12242. var regex = new RegExp(capture);
  12243. var matches = regex.exec(ua);
  12244. if (matches && matches.length > 0) {
  12245. var capturedValue = parseInt(matches[matches.length - 1]);
  12246. if (capturedValue >= constraint) {
  12247. continue;
  12248. }
  12249. }
  12250. }
  12251. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12252. var target = targets_1[_b];
  12253. switch (target) {
  12254. case "uniformBuffer":
  12255. this.disableUniformBuffers = true;
  12256. break;
  12257. case "textureBindingOptimization":
  12258. this.disableTextureBindingOptimization = true;
  12259. break;
  12260. }
  12261. }
  12262. }
  12263. }
  12264. }
  12265. // GL
  12266. if (!options.disableWebGL2Support) {
  12267. try {
  12268. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12269. if (this._gl) {
  12270. this._webGLVersion = 2.0;
  12271. }
  12272. }
  12273. catch (e) {
  12274. // Do nothing
  12275. }
  12276. }
  12277. if (!this._gl) {
  12278. if (!canvas) {
  12279. throw new Error("The provided canvas is null or undefined.");
  12280. }
  12281. try {
  12282. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12283. }
  12284. catch (e) {
  12285. throw new Error("WebGL not supported");
  12286. }
  12287. }
  12288. if (!this._gl) {
  12289. throw new Error("WebGL not supported");
  12290. }
  12291. this._onCanvasFocus = function () {
  12292. _this.onCanvasFocusObservable.notifyObservers(_this);
  12293. };
  12294. this._onCanvasBlur = function () {
  12295. _this.onCanvasBlurObservable.notifyObservers(_this);
  12296. };
  12297. canvas.addEventListener("focus", this._onCanvasFocus);
  12298. canvas.addEventListener("blur", this._onCanvasBlur);
  12299. this._onBlur = function () {
  12300. if (_this.disablePerformanceMonitorInBackground) {
  12301. _this._performanceMonitor.disable();
  12302. }
  12303. _this._windowIsBackground = true;
  12304. };
  12305. this._onFocus = function () {
  12306. if (_this.disablePerformanceMonitorInBackground) {
  12307. _this._performanceMonitor.enable();
  12308. }
  12309. _this._windowIsBackground = false;
  12310. };
  12311. this._onCanvasPointerOut = function (ev) {
  12312. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12313. };
  12314. window.addEventListener("blur", this._onBlur);
  12315. window.addEventListener("focus", this._onFocus);
  12316. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12317. // Context lost
  12318. if (!this._doNotHandleContextLost) {
  12319. this._onContextLost = function (evt) {
  12320. evt.preventDefault();
  12321. _this._contextWasLost = true;
  12322. BABYLON.Tools.Warn("WebGL context lost.");
  12323. _this.onContextLostObservable.notifyObservers(_this);
  12324. };
  12325. this._onContextRestored = function (evt) {
  12326. // Adding a timeout to avoid race condition at browser level
  12327. setTimeout(function () {
  12328. // Rebuild gl context
  12329. _this._initGLContext();
  12330. // Rebuild effects
  12331. _this._rebuildEffects();
  12332. // Rebuild textures
  12333. _this._rebuildInternalTextures();
  12334. // Rebuild buffers
  12335. _this._rebuildBuffers();
  12336. // Cache
  12337. _this.wipeCaches(true);
  12338. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12339. _this.onContextRestoredObservable.notifyObservers(_this);
  12340. _this._contextWasLost = false;
  12341. }, 0);
  12342. };
  12343. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12344. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12345. }
  12346. }
  12347. else {
  12348. this._gl = canvasOrContext;
  12349. this._renderingCanvas = this._gl.canvas;
  12350. if (this._gl.renderbufferStorageMultisample) {
  12351. this._webGLVersion = 2.0;
  12352. }
  12353. options.stencil = this._gl.getContextAttributes().stencil;
  12354. }
  12355. // Viewport
  12356. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12357. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12358. this.resize();
  12359. this._isStencilEnable = options.stencil ? true : false;
  12360. this._initGLContext();
  12361. if (canvas) {
  12362. // Fullscreen
  12363. this._onFullscreenChange = function () {
  12364. if (document.fullscreen !== undefined) {
  12365. _this.isFullscreen = document.fullscreen;
  12366. }
  12367. else if (document.mozFullScreen !== undefined) {
  12368. _this.isFullscreen = document.mozFullScreen;
  12369. }
  12370. else if (document.webkitIsFullScreen !== undefined) {
  12371. _this.isFullscreen = document.webkitIsFullScreen;
  12372. }
  12373. else if (document.msIsFullScreen !== undefined) {
  12374. _this.isFullscreen = document.msIsFullScreen;
  12375. }
  12376. // Pointer lock
  12377. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12378. canvas.requestPointerLock = canvas.requestPointerLock ||
  12379. canvas.msRequestPointerLock ||
  12380. canvas.mozRequestPointerLock ||
  12381. canvas.webkitRequestPointerLock;
  12382. if (canvas.requestPointerLock) {
  12383. canvas.requestPointerLock();
  12384. }
  12385. }
  12386. };
  12387. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12388. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12389. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12390. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12391. // Pointer lock
  12392. this._onPointerLockChange = function () {
  12393. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12394. document.webkitPointerLockElement === canvas ||
  12395. document.msPointerLockElement === canvas ||
  12396. document.pointerLockElement === canvas);
  12397. };
  12398. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12399. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12400. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12401. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12402. this._onVRDisplayPointerRestricted = function () {
  12403. if (canvas) {
  12404. canvas.requestPointerLock();
  12405. }
  12406. };
  12407. this._onVRDisplayPointerUnrestricted = function () {
  12408. document.exitPointerLock();
  12409. };
  12410. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12411. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12412. }
  12413. // Create Audio Engine if needed.
  12414. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12415. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12416. }
  12417. // Prepare buffer pointers
  12418. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12419. this._currentBufferPointers[i] = new BufferPointer();
  12420. }
  12421. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12422. // Load WebVR Devices
  12423. if (options.autoEnableWebVR) {
  12424. this.initWebVR();
  12425. }
  12426. // Detect if we are running on a faulty buggy OS.
  12427. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12428. // Detect if we are running on a faulty buggy desktop OS.
  12429. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12430. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12431. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12432. }
  12433. Object.defineProperty(Engine, "LastCreatedEngine", {
  12434. /**
  12435. * Gets the latest created engine
  12436. */
  12437. get: function () {
  12438. if (Engine.Instances.length === 0) {
  12439. return null;
  12440. }
  12441. return Engine.Instances[Engine.Instances.length - 1];
  12442. },
  12443. enumerable: true,
  12444. configurable: true
  12445. });
  12446. Object.defineProperty(Engine, "LastCreatedScene", {
  12447. /**
  12448. * Gets the latest created scene
  12449. */
  12450. get: function () {
  12451. var lastCreatedEngine = Engine.LastCreatedEngine;
  12452. if (!lastCreatedEngine) {
  12453. return null;
  12454. }
  12455. if (lastCreatedEngine.scenes.length === 0) {
  12456. return null;
  12457. }
  12458. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12459. },
  12460. enumerable: true,
  12461. configurable: true
  12462. });
  12463. /**
  12464. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12465. * @param flag defines which part of the materials must be marked as dirty
  12466. * @param predicate defines a predicate used to filter which materials should be affected
  12467. */
  12468. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12469. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12470. var engine = Engine.Instances[engineIndex];
  12471. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12472. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12473. }
  12474. }
  12475. };
  12476. Object.defineProperty(Engine, "Version", {
  12477. /**
  12478. * Returns the current version of the framework
  12479. */
  12480. get: function () {
  12481. return "3.3.0-rc.2";
  12482. },
  12483. enumerable: true,
  12484. configurable: true
  12485. });
  12486. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12487. /**
  12488. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12489. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12490. */
  12491. get: function () {
  12492. return this._vrExclusivePointerMode;
  12493. },
  12494. enumerable: true,
  12495. configurable: true
  12496. });
  12497. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12498. /**
  12499. * Gets a boolean indicating that the engine supports uniform buffers
  12500. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12501. */
  12502. get: function () {
  12503. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12504. },
  12505. enumerable: true,
  12506. configurable: true
  12507. });
  12508. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12509. /**
  12510. * Gets a boolean indicating that only power of 2 textures are supported
  12511. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12512. */
  12513. get: function () {
  12514. return this._webGLVersion < 2 || this.forcePOTTextures;
  12515. },
  12516. enumerable: true,
  12517. configurable: true
  12518. });
  12519. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12520. /**
  12521. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12522. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12523. */
  12524. get: function () {
  12525. return this._doNotHandleContextLost;
  12526. },
  12527. set: function (value) {
  12528. this._doNotHandleContextLost = value;
  12529. },
  12530. enumerable: true,
  12531. configurable: true
  12532. });
  12533. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12534. /**
  12535. * Gets the performance monitor attached to this engine
  12536. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12537. */
  12538. get: function () {
  12539. return this._performanceMonitor;
  12540. },
  12541. enumerable: true,
  12542. configurable: true
  12543. });
  12544. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12545. /**
  12546. * Gets the list of texture formats supported
  12547. */
  12548. get: function () {
  12549. return this._texturesSupported;
  12550. },
  12551. enumerable: true,
  12552. configurable: true
  12553. });
  12554. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12555. /**
  12556. * Gets the list of texture formats in use
  12557. */
  12558. get: function () {
  12559. return this._textureFormatInUse;
  12560. },
  12561. enumerable: true,
  12562. configurable: true
  12563. });
  12564. Object.defineProperty(Engine.prototype, "currentViewport", {
  12565. /**
  12566. * Gets the current viewport
  12567. */
  12568. get: function () {
  12569. return this._cachedViewport;
  12570. },
  12571. enumerable: true,
  12572. configurable: true
  12573. });
  12574. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12575. /**
  12576. * Gets the default empty texture
  12577. */
  12578. get: function () {
  12579. if (!this._emptyTexture) {
  12580. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12581. }
  12582. return this._emptyTexture;
  12583. },
  12584. enumerable: true,
  12585. configurable: true
  12586. });
  12587. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12588. /**
  12589. * Gets the default empty 3D texture
  12590. */
  12591. get: function () {
  12592. if (!this._emptyTexture3D) {
  12593. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12594. }
  12595. return this._emptyTexture3D;
  12596. },
  12597. enumerable: true,
  12598. configurable: true
  12599. });
  12600. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12601. /**
  12602. * Gets the default empty cube texture
  12603. */
  12604. get: function () {
  12605. if (!this._emptyCubeTexture) {
  12606. var faceData = new Uint8Array(4);
  12607. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12608. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12609. }
  12610. return this._emptyCubeTexture;
  12611. },
  12612. enumerable: true,
  12613. configurable: true
  12614. });
  12615. Engine.prototype._rebuildInternalTextures = function () {
  12616. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12617. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12618. var internalTexture = currentState_1[_i];
  12619. internalTexture._rebuild();
  12620. }
  12621. };
  12622. Engine.prototype._rebuildEffects = function () {
  12623. for (var key in this._compiledEffects) {
  12624. var effect = this._compiledEffects[key];
  12625. effect._prepareEffect();
  12626. }
  12627. BABYLON.Effect.ResetCache();
  12628. };
  12629. Engine.prototype._rebuildBuffers = function () {
  12630. // Index / Vertex
  12631. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12632. var scene = _a[_i];
  12633. scene.resetCachedMaterial();
  12634. scene._rebuildGeometries();
  12635. scene._rebuildTextures();
  12636. }
  12637. // Uniforms
  12638. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12639. var uniformBuffer = _c[_b];
  12640. uniformBuffer._rebuild();
  12641. }
  12642. };
  12643. Engine.prototype._initGLContext = function () {
  12644. // Caps
  12645. this._caps = new EngineCapabilities();
  12646. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12647. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12648. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12649. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12650. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12651. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12652. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12653. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12654. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12655. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12656. // Infos
  12657. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12658. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12659. if (rendererInfo != null) {
  12660. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12661. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12662. }
  12663. if (!this._glVendor) {
  12664. this._glVendor = "Unknown vendor";
  12665. }
  12666. if (!this._glRenderer) {
  12667. this._glRenderer = "Unknown renderer";
  12668. }
  12669. // Constants
  12670. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12671. if (this._gl.RGBA16F !== 0x881A) {
  12672. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12673. }
  12674. if (this._gl.RGBA32F !== 0x8814) {
  12675. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12676. }
  12677. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12678. this._gl.DEPTH24_STENCIL8 = 35056;
  12679. }
  12680. // Extensions
  12681. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12682. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12683. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12684. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12685. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12686. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12687. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12688. 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');
  12689. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12690. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12691. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12692. this._caps.highPrecisionShaderSupported = true;
  12693. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12694. if (this._caps.timerQuery) {
  12695. if (this._webGLVersion === 1) {
  12696. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12697. }
  12698. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12699. }
  12700. // Checks if some of the format renders first to allow the use of webgl inspector.
  12701. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12702. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12703. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12704. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12705. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12706. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12707. if (this._webGLVersion > 1) {
  12708. this._gl.HALF_FLOAT_OES = 0x140B;
  12709. }
  12710. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12711. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12712. // Draw buffers
  12713. if (this._webGLVersion > 1) {
  12714. this._caps.drawBuffersExtension = true;
  12715. }
  12716. else {
  12717. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12718. if (drawBuffersExtension !== null) {
  12719. this._caps.drawBuffersExtension = true;
  12720. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12721. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12722. for (var i = 0; i < 16; i++) {
  12723. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12724. }
  12725. }
  12726. else {
  12727. this._caps.drawBuffersExtension = false;
  12728. }
  12729. }
  12730. // Depth Texture
  12731. if (this._webGLVersion > 1) {
  12732. this._caps.depthTextureExtension = true;
  12733. }
  12734. else {
  12735. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12736. if (depthTextureExtension != null) {
  12737. this._caps.depthTextureExtension = true;
  12738. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12739. }
  12740. }
  12741. // Vertex array object
  12742. if (this._webGLVersion > 1) {
  12743. this._caps.vertexArrayObject = true;
  12744. }
  12745. else {
  12746. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12747. if (vertexArrayObjectExtension != null) {
  12748. this._caps.vertexArrayObject = true;
  12749. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12750. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12751. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12752. }
  12753. else {
  12754. this._caps.vertexArrayObject = false;
  12755. }
  12756. }
  12757. // Instances count
  12758. if (this._webGLVersion > 1) {
  12759. this._caps.instancedArrays = true;
  12760. }
  12761. else {
  12762. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12763. if (instanceExtension != null) {
  12764. this._caps.instancedArrays = true;
  12765. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12766. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12767. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12768. }
  12769. else {
  12770. this._caps.instancedArrays = false;
  12771. }
  12772. }
  12773. // Intelligently add supported compressed formats in order to check for.
  12774. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12775. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12776. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12777. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12778. if (this._caps.astc)
  12779. this.texturesSupported.push('-astc.ktx');
  12780. if (this._caps.s3tc)
  12781. this.texturesSupported.push('-dxt.ktx');
  12782. if (this._caps.pvrtc)
  12783. this.texturesSupported.push('-pvrtc.ktx');
  12784. if (this._caps.etc2)
  12785. this.texturesSupported.push('-etc2.ktx');
  12786. if (this._caps.etc1)
  12787. this.texturesSupported.push('-etc1.ktx');
  12788. if (this._gl.getShaderPrecisionFormat) {
  12789. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12790. if (highp) {
  12791. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12792. }
  12793. }
  12794. // Depth buffer
  12795. this.setDepthBuffer(true);
  12796. this.setDepthFunctionToLessOrEqual();
  12797. this.setDepthWrite(true);
  12798. // Texture maps
  12799. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12800. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12801. this._nextFreeTextureSlots.push(slot);
  12802. }
  12803. };
  12804. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12805. /**
  12806. * Gets version of the current webGL context
  12807. */
  12808. get: function () {
  12809. return this._webGLVersion;
  12810. },
  12811. enumerable: true,
  12812. configurable: true
  12813. });
  12814. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12815. /**
  12816. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12817. */
  12818. get: function () {
  12819. return this._isStencilEnable;
  12820. },
  12821. enumerable: true,
  12822. configurable: true
  12823. });
  12824. Engine.prototype._prepareWorkingCanvas = function () {
  12825. if (this._workingCanvas) {
  12826. return;
  12827. }
  12828. this._workingCanvas = document.createElement("canvas");
  12829. var context = this._workingCanvas.getContext("2d");
  12830. if (context) {
  12831. this._workingContext = context;
  12832. }
  12833. };
  12834. /**
  12835. * Reset the texture cache to empty state
  12836. */
  12837. Engine.prototype.resetTextureCache = function () {
  12838. for (var key in this._boundTexturesCache) {
  12839. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12840. continue;
  12841. }
  12842. var boundTexture = this._boundTexturesCache[key];
  12843. if (boundTexture) {
  12844. this._removeDesignatedSlot(boundTexture);
  12845. }
  12846. this._boundTexturesCache[key] = null;
  12847. }
  12848. if (!this.disableTextureBindingOptimization) {
  12849. this._nextFreeTextureSlots = [];
  12850. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12851. this._nextFreeTextureSlots.push(slot);
  12852. }
  12853. }
  12854. this._currentTextureChannel = -1;
  12855. };
  12856. /**
  12857. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12858. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12859. * @returns true if engine is in deterministic lock step mode
  12860. */
  12861. Engine.prototype.isDeterministicLockStep = function () {
  12862. return this._deterministicLockstep;
  12863. };
  12864. /**
  12865. * Gets the max steps when engine is running in deterministic lock step
  12866. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12867. * @returns the max steps
  12868. */
  12869. Engine.prototype.getLockstepMaxSteps = function () {
  12870. return this._lockstepMaxSteps;
  12871. };
  12872. /**
  12873. * Gets an object containing information about the current webGL context
  12874. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12875. */
  12876. Engine.prototype.getGlInfo = function () {
  12877. return {
  12878. vendor: this._glVendor,
  12879. renderer: this._glRenderer,
  12880. version: this._glVersion
  12881. };
  12882. };
  12883. /**
  12884. * Gets current aspect ratio
  12885. * @param camera defines the camera to use to get the aspect ratio
  12886. * @param useScreen defines if screen size must be used (or the current render target if any)
  12887. * @returns a number defining the aspect ratio
  12888. */
  12889. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12890. if (useScreen === void 0) { useScreen = false; }
  12891. var viewport = camera.viewport;
  12892. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12893. };
  12894. /**
  12895. * Gets current screen aspect ratio
  12896. * @returns a number defining the aspect ratio
  12897. */
  12898. Engine.prototype.getScreenAspectRatio = function () {
  12899. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12900. };
  12901. /**
  12902. * Gets the current render width
  12903. * @param useScreen defines if screen size must be used (or the current render target if any)
  12904. * @returns a number defining the current render width
  12905. */
  12906. Engine.prototype.getRenderWidth = function (useScreen) {
  12907. if (useScreen === void 0) { useScreen = false; }
  12908. if (!useScreen && this._currentRenderTarget) {
  12909. return this._currentRenderTarget.width;
  12910. }
  12911. return this._gl.drawingBufferWidth;
  12912. };
  12913. /**
  12914. * Gets the current render height
  12915. * @param useScreen defines if screen size must be used (or the current render target if any)
  12916. * @returns a number defining the current render height
  12917. */
  12918. Engine.prototype.getRenderHeight = function (useScreen) {
  12919. if (useScreen === void 0) { useScreen = false; }
  12920. if (!useScreen && this._currentRenderTarget) {
  12921. return this._currentRenderTarget.height;
  12922. }
  12923. return this._gl.drawingBufferHeight;
  12924. };
  12925. /**
  12926. * Gets the HTML canvas attached with the current webGL context
  12927. * @returns a HTML canvas
  12928. */
  12929. Engine.prototype.getRenderingCanvas = function () {
  12930. return this._renderingCanvas;
  12931. };
  12932. /**
  12933. * Gets the client rect of the HTML canvas attached with the current webGL context
  12934. * @returns a client rectanglee
  12935. */
  12936. Engine.prototype.getRenderingCanvasClientRect = function () {
  12937. if (!this._renderingCanvas) {
  12938. return null;
  12939. }
  12940. return this._renderingCanvas.getBoundingClientRect();
  12941. };
  12942. /**
  12943. * Defines the hardware scaling level.
  12944. * By default the hardware scaling level is computed from the window device ratio.
  12945. * 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.
  12946. * @param level defines the level to use
  12947. */
  12948. Engine.prototype.setHardwareScalingLevel = function (level) {
  12949. this._hardwareScalingLevel = level;
  12950. this.resize();
  12951. };
  12952. /**
  12953. * Gets the current hardware scaling level.
  12954. * By default the hardware scaling level is computed from the window device ratio.
  12955. * 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.
  12956. * @returns a number indicating the current hardware scaling level
  12957. */
  12958. Engine.prototype.getHardwareScalingLevel = function () {
  12959. return this._hardwareScalingLevel;
  12960. };
  12961. /**
  12962. * Gets the list of loaded textures
  12963. * @returns an array containing all loaded textures
  12964. */
  12965. Engine.prototype.getLoadedTexturesCache = function () {
  12966. return this._internalTexturesCache;
  12967. };
  12968. /**
  12969. * Gets the object containing all engine capabilities
  12970. * @returns the EngineCapabilities object
  12971. */
  12972. Engine.prototype.getCaps = function () {
  12973. return this._caps;
  12974. };
  12975. Object.defineProperty(Engine.prototype, "drawCalls", {
  12976. /** @hidden */
  12977. get: function () {
  12978. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12979. return 0;
  12980. },
  12981. enumerable: true,
  12982. configurable: true
  12983. });
  12984. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12985. /** @hidden */
  12986. get: function () {
  12987. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12988. return null;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. /**
  12994. * Gets the current depth function
  12995. * @returns a number defining the depth function
  12996. */
  12997. Engine.prototype.getDepthFunction = function () {
  12998. return this._depthCullingState.depthFunc;
  12999. };
  13000. /**
  13001. * Sets the current depth function
  13002. * @param depthFunc defines the function to use
  13003. */
  13004. Engine.prototype.setDepthFunction = function (depthFunc) {
  13005. this._depthCullingState.depthFunc = depthFunc;
  13006. };
  13007. /**
  13008. * Sets the current depth function to GREATER
  13009. */
  13010. Engine.prototype.setDepthFunctionToGreater = function () {
  13011. this._depthCullingState.depthFunc = this._gl.GREATER;
  13012. };
  13013. /**
  13014. * Sets the current depth function to GEQUAL
  13015. */
  13016. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13017. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13018. };
  13019. /**
  13020. * Sets the current depth function to LESS
  13021. */
  13022. Engine.prototype.setDepthFunctionToLess = function () {
  13023. this._depthCullingState.depthFunc = this._gl.LESS;
  13024. };
  13025. /**
  13026. * Sets the current depth function to LEQUAL
  13027. */
  13028. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13029. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13030. };
  13031. /**
  13032. * Gets a boolean indicating if stencil buffer is enabled
  13033. * @returns the current stencil buffer state
  13034. */
  13035. Engine.prototype.getStencilBuffer = function () {
  13036. return this._stencilState.stencilTest;
  13037. };
  13038. /**
  13039. * Enable or disable the stencil buffer
  13040. * @param enable defines if the stencil buffer must be enabled or disabled
  13041. */
  13042. Engine.prototype.setStencilBuffer = function (enable) {
  13043. this._stencilState.stencilTest = enable;
  13044. };
  13045. /**
  13046. * Gets the current stencil mask
  13047. * @returns a number defining the new stencil mask to use
  13048. */
  13049. Engine.prototype.getStencilMask = function () {
  13050. return this._stencilState.stencilMask;
  13051. };
  13052. /**
  13053. * Sets the current stencil mask
  13054. * @param mask defines the new stencil mask to use
  13055. */
  13056. Engine.prototype.setStencilMask = function (mask) {
  13057. this._stencilState.stencilMask = mask;
  13058. };
  13059. /**
  13060. * Gets the current stencil function
  13061. * @returns a number defining the stencil function to use
  13062. */
  13063. Engine.prototype.getStencilFunction = function () {
  13064. return this._stencilState.stencilFunc;
  13065. };
  13066. /**
  13067. * Gets the current stencil reference value
  13068. * @returns a number defining the stencil reference value to use
  13069. */
  13070. Engine.prototype.getStencilFunctionReference = function () {
  13071. return this._stencilState.stencilFuncRef;
  13072. };
  13073. /**
  13074. * Gets the current stencil mask
  13075. * @returns a number defining the stencil mask to use
  13076. */
  13077. Engine.prototype.getStencilFunctionMask = function () {
  13078. return this._stencilState.stencilFuncMask;
  13079. };
  13080. /**
  13081. * Sets the current stencil function
  13082. * @param stencilFunc defines the new stencil function to use
  13083. */
  13084. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13085. this._stencilState.stencilFunc = stencilFunc;
  13086. };
  13087. /**
  13088. * Sets the current stencil reference
  13089. * @param reference defines the new stencil reference to use
  13090. */
  13091. Engine.prototype.setStencilFunctionReference = function (reference) {
  13092. this._stencilState.stencilFuncRef = reference;
  13093. };
  13094. /**
  13095. * Sets the current stencil mask
  13096. * @param mask defines the new stencil mask to use
  13097. */
  13098. Engine.prototype.setStencilFunctionMask = function (mask) {
  13099. this._stencilState.stencilFuncMask = mask;
  13100. };
  13101. /**
  13102. * Gets the current stencil operation when stencil fails
  13103. * @returns a number defining stencil operation to use when stencil fails
  13104. */
  13105. Engine.prototype.getStencilOperationFail = function () {
  13106. return this._stencilState.stencilOpStencilFail;
  13107. };
  13108. /**
  13109. * Gets the current stencil operation when depth fails
  13110. * @returns a number defining stencil operation to use when depth fails
  13111. */
  13112. Engine.prototype.getStencilOperationDepthFail = function () {
  13113. return this._stencilState.stencilOpDepthFail;
  13114. };
  13115. /**
  13116. * Gets the current stencil operation when stencil passes
  13117. * @returns a number defining stencil operation to use when stencil passes
  13118. */
  13119. Engine.prototype.getStencilOperationPass = function () {
  13120. return this._stencilState.stencilOpStencilDepthPass;
  13121. };
  13122. /**
  13123. * Sets the stencil operation to use when stencil fails
  13124. * @param operation defines the stencil operation to use when stencil fails
  13125. */
  13126. Engine.prototype.setStencilOperationFail = function (operation) {
  13127. this._stencilState.stencilOpStencilFail = operation;
  13128. };
  13129. /**
  13130. * Sets the stencil operation to use when depth fails
  13131. * @param operation defines the stencil operation to use when depth fails
  13132. */
  13133. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13134. this._stencilState.stencilOpDepthFail = operation;
  13135. };
  13136. /**
  13137. * Sets the stencil operation to use when stencil passes
  13138. * @param operation defines the stencil operation to use when stencil passes
  13139. */
  13140. Engine.prototype.setStencilOperationPass = function (operation) {
  13141. this._stencilState.stencilOpStencilDepthPass = operation;
  13142. };
  13143. /**
  13144. * Sets a boolean indicating if the dithering state is enabled or disabled
  13145. * @param value defines the dithering state
  13146. */
  13147. Engine.prototype.setDitheringState = function (value) {
  13148. if (value) {
  13149. this._gl.enable(this._gl.DITHER);
  13150. }
  13151. else {
  13152. this._gl.disable(this._gl.DITHER);
  13153. }
  13154. };
  13155. /**
  13156. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13157. * @param value defines the rasterizer state
  13158. */
  13159. Engine.prototype.setRasterizerState = function (value) {
  13160. if (value) {
  13161. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13162. }
  13163. else {
  13164. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13165. }
  13166. };
  13167. /**
  13168. * stop executing a render loop function and remove it from the execution array
  13169. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13170. */
  13171. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13172. if (!renderFunction) {
  13173. this._activeRenderLoops = [];
  13174. return;
  13175. }
  13176. var index = this._activeRenderLoops.indexOf(renderFunction);
  13177. if (index >= 0) {
  13178. this._activeRenderLoops.splice(index, 1);
  13179. }
  13180. };
  13181. /** @hidden */
  13182. Engine.prototype._renderLoop = function () {
  13183. if (!this._contextWasLost) {
  13184. var shouldRender = true;
  13185. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13186. shouldRender = false;
  13187. }
  13188. if (shouldRender) {
  13189. // Start new frame
  13190. this.beginFrame();
  13191. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13192. var renderFunction = this._activeRenderLoops[index];
  13193. renderFunction();
  13194. }
  13195. // Present
  13196. this.endFrame();
  13197. }
  13198. }
  13199. if (this._activeRenderLoops.length > 0) {
  13200. // Register new frame
  13201. var requester = null;
  13202. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13203. requester = this._vrDisplay;
  13204. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13205. }
  13206. else {
  13207. this._renderingQueueLaunched = false;
  13208. }
  13209. };
  13210. /**
  13211. * Register and execute a render loop. The engine can have more than one render function
  13212. * @param renderFunction defines the function to continuously execute
  13213. */
  13214. Engine.prototype.runRenderLoop = function (renderFunction) {
  13215. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13216. return;
  13217. }
  13218. this._activeRenderLoops.push(renderFunction);
  13219. if (!this._renderingQueueLaunched) {
  13220. this._renderingQueueLaunched = true;
  13221. this._bindedRenderFunction = this._renderLoop.bind(this);
  13222. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13223. }
  13224. };
  13225. /**
  13226. * Toggle full screen mode
  13227. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13228. */
  13229. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13230. if (this.isFullscreen) {
  13231. BABYLON.Tools.ExitFullscreen();
  13232. }
  13233. else {
  13234. this._pointerLockRequested = requestPointerLock;
  13235. if (this._renderingCanvas) {
  13236. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13237. }
  13238. }
  13239. };
  13240. /**
  13241. * Clear the current render buffer or the current render target (if any is set up)
  13242. * @param color defines the color to use
  13243. * @param backBuffer defines if the back buffer must be cleared
  13244. * @param depth defines if the depth buffer must be cleared
  13245. * @param stencil defines if the stencil buffer must be cleared
  13246. */
  13247. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13248. if (stencil === void 0) { stencil = false; }
  13249. this.applyStates();
  13250. var mode = 0;
  13251. if (backBuffer && color) {
  13252. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13253. mode |= this._gl.COLOR_BUFFER_BIT;
  13254. }
  13255. if (depth) {
  13256. this._gl.clearDepth(1.0);
  13257. mode |= this._gl.DEPTH_BUFFER_BIT;
  13258. }
  13259. if (stencil) {
  13260. this._gl.clearStencil(0);
  13261. mode |= this._gl.STENCIL_BUFFER_BIT;
  13262. }
  13263. this._gl.clear(mode);
  13264. };
  13265. /**
  13266. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13267. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13268. * @param y defines the y-coordinate of the corner of the clear rectangle
  13269. * @param width defines the width of the clear rectangle
  13270. * @param height defines the height of the clear rectangle
  13271. * @param clearColor defines the clear color
  13272. */
  13273. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13274. var gl = this._gl;
  13275. // Save state
  13276. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13277. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13278. // Change state
  13279. gl.enable(gl.SCISSOR_TEST);
  13280. gl.scissor(x, y, width, height);
  13281. // Clear
  13282. this.clear(clearColor, true, true, true);
  13283. // Restore state
  13284. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13285. if (curScissor === true) {
  13286. gl.enable(gl.SCISSOR_TEST);
  13287. }
  13288. else {
  13289. gl.disable(gl.SCISSOR_TEST);
  13290. }
  13291. };
  13292. /** @hidden */
  13293. Engine.prototype._viewport = function (x, y, width, height) {
  13294. if (x !== this._viewportCached.x ||
  13295. y !== this._viewportCached.y ||
  13296. width !== this._viewportCached.z ||
  13297. height !== this._viewportCached.w) {
  13298. this._viewportCached.x = x;
  13299. this._viewportCached.y = y;
  13300. this._viewportCached.z = width;
  13301. this._viewportCached.w = height;
  13302. this._gl.viewport(x, y, width, height);
  13303. }
  13304. };
  13305. /**
  13306. * Set the WebGL's viewport
  13307. * @param viewport defines the viewport element to be used
  13308. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13309. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13310. */
  13311. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13312. var width = requiredWidth || this.getRenderWidth();
  13313. var height = requiredHeight || this.getRenderHeight();
  13314. var x = viewport.x || 0;
  13315. var y = viewport.y || 0;
  13316. this._cachedViewport = viewport;
  13317. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13318. };
  13319. /**
  13320. * Directly set the WebGL Viewport
  13321. * @param x defines the x coordinate of the viewport (in screen space)
  13322. * @param y defines the y coordinate of the viewport (in screen space)
  13323. * @param width defines the width of the viewport (in screen space)
  13324. * @param height defines the height of the viewport (in screen space)
  13325. * @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
  13326. */
  13327. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13328. var currentViewport = this._cachedViewport;
  13329. this._cachedViewport = null;
  13330. this._viewport(x, y, width, height);
  13331. return currentViewport;
  13332. };
  13333. /**
  13334. * Begin a new frame
  13335. */
  13336. Engine.prototype.beginFrame = function () {
  13337. this.onBeginFrameObservable.notifyObservers(this);
  13338. this._measureFps();
  13339. };
  13340. /**
  13341. * Enf the current frame
  13342. */
  13343. Engine.prototype.endFrame = function () {
  13344. // Force a flush in case we are using a bad OS.
  13345. if (this._badOS) {
  13346. this.flushFramebuffer();
  13347. }
  13348. // Submit frame to the vr device, if enabled
  13349. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13350. // TODO: We should only submit the frame if we read frameData successfully.
  13351. this._vrDisplay.submitFrame();
  13352. }
  13353. this.onEndFrameObservable.notifyObservers(this);
  13354. };
  13355. /**
  13356. * Resize the view according to the canvas' size
  13357. */
  13358. Engine.prototype.resize = function () {
  13359. // We're not resizing the size of the canvas while in VR mode & presenting
  13360. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13361. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13362. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13363. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13364. }
  13365. };
  13366. /**
  13367. * Force a specific size of the canvas
  13368. * @param width defines the new canvas' width
  13369. * @param height defines the new canvas' height
  13370. */
  13371. Engine.prototype.setSize = function (width, height) {
  13372. if (!this._renderingCanvas) {
  13373. return;
  13374. }
  13375. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13376. return;
  13377. }
  13378. this._renderingCanvas.width = width;
  13379. this._renderingCanvas.height = height;
  13380. for (var index = 0; index < this.scenes.length; index++) {
  13381. var scene = this.scenes[index];
  13382. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13383. var cam = scene.cameras[camIndex];
  13384. cam._currentRenderId = 0;
  13385. }
  13386. }
  13387. if (this.onResizeObservable.hasObservers) {
  13388. this.onResizeObservable.notifyObservers(this);
  13389. }
  13390. };
  13391. // WebVR functions
  13392. /**
  13393. * Gets a boolean indicating if a webVR device was detected
  13394. * @returns true if a webVR device was detected
  13395. */
  13396. Engine.prototype.isVRDevicePresent = function () {
  13397. return !!this._vrDisplay;
  13398. };
  13399. /**
  13400. * Gets the current webVR device
  13401. * @returns the current webVR device (or null)
  13402. */
  13403. Engine.prototype.getVRDevice = function () {
  13404. return this._vrDisplay;
  13405. };
  13406. /**
  13407. * Initializes a webVR display and starts listening to display change events
  13408. * The onVRDisplayChangedObservable will be notified upon these changes
  13409. * @returns The onVRDisplayChangedObservable
  13410. */
  13411. Engine.prototype.initWebVR = function () {
  13412. this.initWebVRAsync();
  13413. return this.onVRDisplayChangedObservable;
  13414. };
  13415. /**
  13416. * Initializes a webVR display and starts listening to display change events
  13417. * The onVRDisplayChangedObservable will be notified upon these changes
  13418. * @returns A promise containing a VRDisplay and if vr is supported
  13419. */
  13420. Engine.prototype.initWebVRAsync = function () {
  13421. var _this = this;
  13422. var notifyObservers = function () {
  13423. var eventArgs = {
  13424. vrDisplay: _this._vrDisplay,
  13425. vrSupported: _this._vrSupported
  13426. };
  13427. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13428. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13429. };
  13430. if (!this._onVrDisplayConnect) {
  13431. this._onVrDisplayConnect = function (event) {
  13432. _this._vrDisplay = event.display;
  13433. notifyObservers();
  13434. };
  13435. this._onVrDisplayDisconnect = function () {
  13436. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13437. _this._vrDisplay = undefined;
  13438. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13439. notifyObservers();
  13440. };
  13441. this._onVrDisplayPresentChange = function () {
  13442. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13443. };
  13444. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13445. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13446. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13447. }
  13448. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13449. this._webVRInitPromise.then(notifyObservers);
  13450. return this._webVRInitPromise;
  13451. };
  13452. /**
  13453. * Call this function to switch to webVR mode
  13454. * Will do nothing if webVR is not supported or if there is no webVR device
  13455. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13456. */
  13457. Engine.prototype.enableVR = function () {
  13458. var _this = this;
  13459. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13460. var onResolved = function () {
  13461. _this.onVRRequestPresentComplete.notifyObservers(true);
  13462. _this._onVRFullScreenTriggered();
  13463. };
  13464. var onRejected = function () {
  13465. _this.onVRRequestPresentComplete.notifyObservers(false);
  13466. };
  13467. this.onVRRequestPresentStart.notifyObservers(this);
  13468. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13469. }
  13470. };
  13471. /**
  13472. * Call this function to leave webVR mode
  13473. * Will do nothing if webVR is not supported or if there is no webVR device
  13474. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13475. */
  13476. Engine.prototype.disableVR = function () {
  13477. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13478. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13479. }
  13480. };
  13481. Engine.prototype._getVRDisplaysAsync = function () {
  13482. var _this = this;
  13483. return new Promise(function (res, rej) {
  13484. if (navigator.getVRDisplays) {
  13485. navigator.getVRDisplays().then(function (devices) {
  13486. _this._vrSupported = true;
  13487. // note that devices may actually be an empty array. This is fine;
  13488. // we expect this._vrDisplay to be undefined in this case.
  13489. _this._vrDisplay = devices[0];
  13490. res({
  13491. vrDisplay: _this._vrDisplay,
  13492. vrSupported: _this._vrSupported
  13493. });
  13494. });
  13495. }
  13496. else {
  13497. _this._vrDisplay = undefined;
  13498. _this._vrSupported = false;
  13499. res({
  13500. vrDisplay: _this._vrDisplay,
  13501. vrSupported: _this._vrSupported
  13502. });
  13503. }
  13504. });
  13505. };
  13506. /**
  13507. * Binds the frame buffer to the specified texture.
  13508. * @param texture The texture to render to or null for the default canvas
  13509. * @param faceIndex The face of the texture to render to in case of cube texture
  13510. * @param requiredWidth The width of the target to render to
  13511. * @param requiredHeight The height of the target to render to
  13512. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13513. * @param depthStencilTexture The depth stencil texture to use to render
  13514. * @param lodLevel defines le lod level to bind to the frame buffer
  13515. */
  13516. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13517. if (lodLevel === void 0) { lodLevel = 0; }
  13518. if (this._currentRenderTarget) {
  13519. this.unBindFramebuffer(this._currentRenderTarget);
  13520. }
  13521. this._currentRenderTarget = texture;
  13522. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13523. var gl = this._gl;
  13524. if (texture.isCube) {
  13525. if (faceIndex === undefined) {
  13526. faceIndex = 0;
  13527. }
  13528. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13529. if (depthStencilTexture) {
  13530. if (depthStencilTexture._generateStencilBuffer) {
  13531. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13532. }
  13533. else {
  13534. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13535. }
  13536. }
  13537. }
  13538. if (this._cachedViewport && !forceFullscreenViewport) {
  13539. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13540. }
  13541. else {
  13542. if (!requiredWidth) {
  13543. requiredWidth = texture.width;
  13544. if (lodLevel) {
  13545. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13546. }
  13547. }
  13548. if (!requiredHeight) {
  13549. requiredHeight = texture.height;
  13550. if (lodLevel) {
  13551. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13552. }
  13553. }
  13554. this._viewport(0, 0, requiredWidth, requiredHeight);
  13555. }
  13556. this.wipeCaches();
  13557. };
  13558. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13559. if (this._currentFramebuffer !== framebuffer) {
  13560. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13561. this._currentFramebuffer = framebuffer;
  13562. }
  13563. };
  13564. /**
  13565. * Unbind the current render target texture from the webGL context
  13566. * @param texture defines the render target texture to unbind
  13567. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13568. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13569. */
  13570. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13571. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13572. this._currentRenderTarget = null;
  13573. // If MSAA, we need to bitblt back to main texture
  13574. var gl = this._gl;
  13575. if (texture._MSAAFramebuffer) {
  13576. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13577. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13578. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13579. }
  13580. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13581. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13582. gl.generateMipmap(gl.TEXTURE_2D);
  13583. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13584. }
  13585. if (onBeforeUnbind) {
  13586. if (texture._MSAAFramebuffer) {
  13587. // Bind the correct framebuffer
  13588. this.bindUnboundFramebuffer(texture._framebuffer);
  13589. }
  13590. onBeforeUnbind();
  13591. }
  13592. this.bindUnboundFramebuffer(null);
  13593. };
  13594. /**
  13595. * Unbind a list of render target textures from the webGL context
  13596. * This is used only when drawBuffer extension or webGL2 are active
  13597. * @param textures defines the render target textures to unbind
  13598. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13599. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13600. */
  13601. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13602. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13603. this._currentRenderTarget = null;
  13604. // If MSAA, we need to bitblt back to main texture
  13605. var gl = this._gl;
  13606. if (textures[0]._MSAAFramebuffer) {
  13607. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13608. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13609. var attachments = textures[0]._attachments;
  13610. if (!attachments) {
  13611. attachments = new Array(textures.length);
  13612. textures[0]._attachments = attachments;
  13613. }
  13614. for (var i = 0; i < textures.length; i++) {
  13615. var texture = textures[i];
  13616. for (var j = 0; j < attachments.length; j++) {
  13617. attachments[j] = gl.NONE;
  13618. }
  13619. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13620. gl.readBuffer(attachments[i]);
  13621. gl.drawBuffers(attachments);
  13622. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13623. }
  13624. for (var i = 0; i < attachments.length; i++) {
  13625. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13626. }
  13627. gl.drawBuffers(attachments);
  13628. }
  13629. for (var i = 0; i < textures.length; i++) {
  13630. var texture = textures[i];
  13631. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13632. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13633. gl.generateMipmap(gl.TEXTURE_2D);
  13634. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13635. }
  13636. }
  13637. if (onBeforeUnbind) {
  13638. if (textures[0]._MSAAFramebuffer) {
  13639. // Bind the correct framebuffer
  13640. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13641. }
  13642. onBeforeUnbind();
  13643. }
  13644. this.bindUnboundFramebuffer(null);
  13645. };
  13646. /**
  13647. * Force the mipmap generation for the given render target texture
  13648. * @param texture defines the render target texture to use
  13649. */
  13650. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13651. if (texture.generateMipMaps) {
  13652. var gl = this._gl;
  13653. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13654. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13655. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13656. }
  13657. };
  13658. /**
  13659. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13660. */
  13661. Engine.prototype.flushFramebuffer = function () {
  13662. this._gl.flush();
  13663. };
  13664. /**
  13665. * Unbind the current render target and bind the default framebuffer
  13666. */
  13667. Engine.prototype.restoreDefaultFramebuffer = function () {
  13668. if (this._currentRenderTarget) {
  13669. this.unBindFramebuffer(this._currentRenderTarget);
  13670. }
  13671. else {
  13672. this.bindUnboundFramebuffer(null);
  13673. }
  13674. if (this._cachedViewport) {
  13675. this.setViewport(this._cachedViewport);
  13676. }
  13677. this.wipeCaches();
  13678. };
  13679. // UBOs
  13680. /**
  13681. * Create an uniform buffer
  13682. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13683. * @param elements defines the content of the uniform buffer
  13684. * @returns the webGL uniform buffer
  13685. */
  13686. Engine.prototype.createUniformBuffer = function (elements) {
  13687. var ubo = this._gl.createBuffer();
  13688. if (!ubo) {
  13689. throw new Error("Unable to create uniform buffer");
  13690. }
  13691. this.bindUniformBuffer(ubo);
  13692. if (elements instanceof Float32Array) {
  13693. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13694. }
  13695. else {
  13696. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13697. }
  13698. this.bindUniformBuffer(null);
  13699. ubo.references = 1;
  13700. return ubo;
  13701. };
  13702. /**
  13703. * Create a dynamic uniform buffer
  13704. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13705. * @param elements defines the content of the uniform buffer
  13706. * @returns the webGL uniform buffer
  13707. */
  13708. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13709. var ubo = this._gl.createBuffer();
  13710. if (!ubo) {
  13711. throw new Error("Unable to create dynamic uniform buffer");
  13712. }
  13713. this.bindUniformBuffer(ubo);
  13714. if (elements instanceof Float32Array) {
  13715. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13716. }
  13717. else {
  13718. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13719. }
  13720. this.bindUniformBuffer(null);
  13721. ubo.references = 1;
  13722. return ubo;
  13723. };
  13724. /**
  13725. * Update an existing uniform buffer
  13726. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13727. * @param uniformBuffer defines the target uniform buffer
  13728. * @param elements defines the content to update
  13729. * @param offset defines the offset in the uniform buffer where update should start
  13730. * @param count defines the size of the data to update
  13731. */
  13732. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13733. this.bindUniformBuffer(uniformBuffer);
  13734. if (offset === undefined) {
  13735. offset = 0;
  13736. }
  13737. if (count === undefined) {
  13738. if (elements instanceof Float32Array) {
  13739. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13740. }
  13741. else {
  13742. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13743. }
  13744. }
  13745. else {
  13746. if (elements instanceof Float32Array) {
  13747. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13748. }
  13749. else {
  13750. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13751. }
  13752. }
  13753. this.bindUniformBuffer(null);
  13754. };
  13755. // VBOs
  13756. Engine.prototype._resetVertexBufferBinding = function () {
  13757. this.bindArrayBuffer(null);
  13758. this._cachedVertexBuffers = null;
  13759. };
  13760. /**
  13761. * Creates a vertex buffer
  13762. * @param data the data for the vertex buffer
  13763. * @returns the new WebGL static buffer
  13764. */
  13765. Engine.prototype.createVertexBuffer = function (data) {
  13766. var vbo = this._gl.createBuffer();
  13767. if (!vbo) {
  13768. throw new Error("Unable to create vertex buffer");
  13769. }
  13770. this.bindArrayBuffer(vbo);
  13771. if (data instanceof Array) {
  13772. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13773. }
  13774. else {
  13775. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13776. }
  13777. this._resetVertexBufferBinding();
  13778. vbo.references = 1;
  13779. return vbo;
  13780. };
  13781. /**
  13782. * Creates a dynamic vertex buffer
  13783. * @param data the data for the dynamic vertex buffer
  13784. * @returns the new WebGL dynamic buffer
  13785. */
  13786. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13787. var vbo = this._gl.createBuffer();
  13788. if (!vbo) {
  13789. throw new Error("Unable to create dynamic vertex buffer");
  13790. }
  13791. this.bindArrayBuffer(vbo);
  13792. if (data instanceof Array) {
  13793. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13794. }
  13795. else {
  13796. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13797. }
  13798. this._resetVertexBufferBinding();
  13799. vbo.references = 1;
  13800. return vbo;
  13801. };
  13802. /**
  13803. * Update a dynamic index buffer
  13804. * @param indexBuffer defines the target index buffer
  13805. * @param indices defines the data to update
  13806. * @param offset defines the offset in the target index buffer where update should start
  13807. */
  13808. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13809. if (offset === void 0) { offset = 0; }
  13810. // Force cache update
  13811. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13812. this.bindIndexBuffer(indexBuffer);
  13813. var arrayBuffer;
  13814. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13815. arrayBuffer = indices;
  13816. }
  13817. else {
  13818. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13819. }
  13820. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13821. this._resetIndexBufferBinding();
  13822. };
  13823. /**
  13824. * Updates a dynamic vertex buffer.
  13825. * @param vertexBuffer the vertex buffer to update
  13826. * @param data the data used to update the vertex buffer
  13827. * @param byteOffset the byte offset of the data
  13828. * @param byteLength the byte length of the data
  13829. */
  13830. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13831. this.bindArrayBuffer(vertexBuffer);
  13832. if (byteOffset === undefined) {
  13833. byteOffset = 0;
  13834. }
  13835. if (byteLength === undefined) {
  13836. if (data instanceof Array) {
  13837. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13838. }
  13839. else {
  13840. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13841. }
  13842. }
  13843. else {
  13844. if (data instanceof Array) {
  13845. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13846. }
  13847. else {
  13848. if (data instanceof ArrayBuffer) {
  13849. data = new Uint8Array(data, byteOffset, byteLength);
  13850. }
  13851. else {
  13852. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13853. }
  13854. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13855. }
  13856. }
  13857. this._resetVertexBufferBinding();
  13858. };
  13859. Engine.prototype._resetIndexBufferBinding = function () {
  13860. this.bindIndexBuffer(null);
  13861. this._cachedIndexBuffer = null;
  13862. };
  13863. /**
  13864. * Creates a new index buffer
  13865. * @param indices defines the content of the index buffer
  13866. * @param updatable defines if the index buffer must be updatable
  13867. * @returns a new webGL buffer
  13868. */
  13869. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13870. var vbo = this._gl.createBuffer();
  13871. if (!vbo) {
  13872. throw new Error("Unable to create index buffer");
  13873. }
  13874. this.bindIndexBuffer(vbo);
  13875. // Check for 32 bits indices
  13876. var arrayBuffer;
  13877. var need32Bits = false;
  13878. if (indices instanceof Uint16Array) {
  13879. arrayBuffer = indices;
  13880. }
  13881. else {
  13882. //check 32 bit support
  13883. if (this._caps.uintIndices) {
  13884. if (indices instanceof Uint32Array) {
  13885. arrayBuffer = indices;
  13886. need32Bits = true;
  13887. }
  13888. else {
  13889. //number[] or Int32Array, check if 32 bit is necessary
  13890. for (var index = 0; index < indices.length; index++) {
  13891. if (indices[index] > 65535) {
  13892. need32Bits = true;
  13893. break;
  13894. }
  13895. }
  13896. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13897. }
  13898. }
  13899. else {
  13900. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13901. arrayBuffer = new Uint16Array(indices);
  13902. }
  13903. }
  13904. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13905. this._resetIndexBufferBinding();
  13906. vbo.references = 1;
  13907. vbo.is32Bits = need32Bits;
  13908. return vbo;
  13909. };
  13910. /**
  13911. * Bind a webGL buffer to the webGL context
  13912. * @param buffer defines the buffer to bind
  13913. */
  13914. Engine.prototype.bindArrayBuffer = function (buffer) {
  13915. if (!this._vaoRecordInProgress) {
  13916. this._unbindVertexArrayObject();
  13917. }
  13918. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13919. };
  13920. /**
  13921. * Bind an uniform buffer to the current webGL context
  13922. * @param buffer defines the buffer to bind
  13923. */
  13924. Engine.prototype.bindUniformBuffer = function (buffer) {
  13925. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13926. };
  13927. /**
  13928. * Bind a buffer to the current webGL context at a given location
  13929. * @param buffer defines the buffer to bind
  13930. * @param location defines the index where to bind the buffer
  13931. */
  13932. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13933. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13934. };
  13935. /**
  13936. * Bind a specific block at a given index in a specific shader program
  13937. * @param shaderProgram defines the shader program
  13938. * @param blockName defines the block name
  13939. * @param index defines the index where to bind the block
  13940. */
  13941. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13942. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13943. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13944. };
  13945. ;
  13946. Engine.prototype.bindIndexBuffer = function (buffer) {
  13947. if (!this._vaoRecordInProgress) {
  13948. this._unbindVertexArrayObject();
  13949. }
  13950. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13951. };
  13952. Engine.prototype.bindBuffer = function (buffer, target) {
  13953. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13954. this._gl.bindBuffer(target, buffer);
  13955. this._currentBoundBuffer[target] = buffer;
  13956. }
  13957. };
  13958. /**
  13959. * update the bound buffer with the given data
  13960. * @param data defines the data to update
  13961. */
  13962. Engine.prototype.updateArrayBuffer = function (data) {
  13963. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13964. };
  13965. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13966. var pointer = this._currentBufferPointers[indx];
  13967. var changed = false;
  13968. if (!pointer.active) {
  13969. changed = true;
  13970. pointer.active = true;
  13971. pointer.index = indx;
  13972. pointer.size = size;
  13973. pointer.type = type;
  13974. pointer.normalized = normalized;
  13975. pointer.stride = stride;
  13976. pointer.offset = offset;
  13977. pointer.buffer = buffer;
  13978. }
  13979. else {
  13980. if (pointer.buffer !== buffer) {
  13981. pointer.buffer = buffer;
  13982. changed = true;
  13983. }
  13984. if (pointer.size !== size) {
  13985. pointer.size = size;
  13986. changed = true;
  13987. }
  13988. if (pointer.type !== type) {
  13989. pointer.type = type;
  13990. changed = true;
  13991. }
  13992. if (pointer.normalized !== normalized) {
  13993. pointer.normalized = normalized;
  13994. changed = true;
  13995. }
  13996. if (pointer.stride !== stride) {
  13997. pointer.stride = stride;
  13998. changed = true;
  13999. }
  14000. if (pointer.offset !== offset) {
  14001. pointer.offset = offset;
  14002. changed = true;
  14003. }
  14004. }
  14005. if (changed || this._vaoRecordInProgress) {
  14006. this.bindArrayBuffer(buffer);
  14007. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14008. }
  14009. };
  14010. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14011. if (indexBuffer == null) {
  14012. return;
  14013. }
  14014. if (this._cachedIndexBuffer !== indexBuffer) {
  14015. this._cachedIndexBuffer = indexBuffer;
  14016. this.bindIndexBuffer(indexBuffer);
  14017. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14018. }
  14019. };
  14020. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14021. var attributes = effect.getAttributesNames();
  14022. if (!this._vaoRecordInProgress) {
  14023. this._unbindVertexArrayObject();
  14024. }
  14025. this.unbindAllAttributes();
  14026. for (var index = 0; index < attributes.length; index++) {
  14027. var order = effect.getAttributeLocation(index);
  14028. if (order >= 0) {
  14029. var vertexBuffer = vertexBuffers[attributes[index]];
  14030. if (!vertexBuffer) {
  14031. continue;
  14032. }
  14033. this._gl.enableVertexAttribArray(order);
  14034. if (!this._vaoRecordInProgress) {
  14035. this._vertexAttribArraysEnabled[order] = true;
  14036. }
  14037. var buffer = vertexBuffer.getBuffer();
  14038. if (buffer) {
  14039. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14040. if (vertexBuffer.getIsInstanced()) {
  14041. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14042. if (!this._vaoRecordInProgress) {
  14043. this._currentInstanceLocations.push(order);
  14044. this._currentInstanceBuffers.push(buffer);
  14045. }
  14046. }
  14047. }
  14048. }
  14049. }
  14050. };
  14051. /**
  14052. * Records a vertex array object
  14053. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14054. * @param vertexBuffers defines the list of vertex buffers to store
  14055. * @param indexBuffer defines the index buffer to store
  14056. * @param effect defines the effect to store
  14057. * @returns the new vertex array object
  14058. */
  14059. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14060. var vao = this._gl.createVertexArray();
  14061. this._vaoRecordInProgress = true;
  14062. this._gl.bindVertexArray(vao);
  14063. this._mustWipeVertexAttributes = true;
  14064. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14065. this.bindIndexBuffer(indexBuffer);
  14066. this._vaoRecordInProgress = false;
  14067. this._gl.bindVertexArray(null);
  14068. return vao;
  14069. };
  14070. /**
  14071. * Bind a specific vertex array object
  14072. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14073. * @param vertexArrayObject defines the vertex array object to bind
  14074. * @param indexBuffer defines the index buffer to bind
  14075. */
  14076. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14077. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14078. this._cachedVertexArrayObject = vertexArrayObject;
  14079. this._gl.bindVertexArray(vertexArrayObject);
  14080. this._cachedVertexBuffers = null;
  14081. this._cachedIndexBuffer = null;
  14082. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14083. this._mustWipeVertexAttributes = true;
  14084. }
  14085. };
  14086. /**
  14087. * Bind webGl buffers directly to the webGL context
  14088. * @param vertexBuffer defines the vertex buffer to bind
  14089. * @param indexBuffer defines the index buffer to bind
  14090. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14091. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14092. * @param effect defines the effect associated with the vertex buffer
  14093. */
  14094. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14095. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14096. this._cachedVertexBuffers = vertexBuffer;
  14097. this._cachedEffectForVertexBuffers = effect;
  14098. var attributesCount = effect.getAttributesCount();
  14099. this._unbindVertexArrayObject();
  14100. this.unbindAllAttributes();
  14101. var offset = 0;
  14102. for (var index = 0; index < attributesCount; index++) {
  14103. if (index < vertexDeclaration.length) {
  14104. var order = effect.getAttributeLocation(index);
  14105. if (order >= 0) {
  14106. this._gl.enableVertexAttribArray(order);
  14107. this._vertexAttribArraysEnabled[order] = true;
  14108. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14109. }
  14110. offset += vertexDeclaration[index] * 4;
  14111. }
  14112. }
  14113. }
  14114. this._bindIndexBufferWithCache(indexBuffer);
  14115. };
  14116. Engine.prototype._unbindVertexArrayObject = function () {
  14117. if (!this._cachedVertexArrayObject) {
  14118. return;
  14119. }
  14120. this._cachedVertexArrayObject = null;
  14121. this._gl.bindVertexArray(null);
  14122. };
  14123. /**
  14124. * Bind a list of vertex buffers to the webGL context
  14125. * @param vertexBuffers defines the list of vertex buffers to bind
  14126. * @param indexBuffer defines the index buffer to bind
  14127. * @param effect defines the effect associated with the vertex buffers
  14128. */
  14129. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14130. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14131. this._cachedVertexBuffers = vertexBuffers;
  14132. this._cachedEffectForVertexBuffers = effect;
  14133. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14134. }
  14135. this._bindIndexBufferWithCache(indexBuffer);
  14136. };
  14137. /**
  14138. * Unbind all instance attributes
  14139. */
  14140. Engine.prototype.unbindInstanceAttributes = function () {
  14141. var boundBuffer;
  14142. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14143. var instancesBuffer = this._currentInstanceBuffers[i];
  14144. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14145. boundBuffer = instancesBuffer;
  14146. this.bindArrayBuffer(instancesBuffer);
  14147. }
  14148. var offsetLocation = this._currentInstanceLocations[i];
  14149. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14150. }
  14151. this._currentInstanceBuffers.length = 0;
  14152. this._currentInstanceLocations.length = 0;
  14153. };
  14154. /**
  14155. * Release and free the memory of a vertex array object
  14156. * @param vao defines the vertex array object to delete
  14157. */
  14158. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14159. this._gl.deleteVertexArray(vao);
  14160. };
  14161. /** @hidden */
  14162. Engine.prototype._releaseBuffer = function (buffer) {
  14163. buffer.references--;
  14164. if (buffer.references === 0) {
  14165. this._gl.deleteBuffer(buffer);
  14166. return true;
  14167. }
  14168. return false;
  14169. };
  14170. /**
  14171. * Creates a webGL buffer to use with instanciation
  14172. * @param capacity defines the size of the buffer
  14173. * @returns the webGL buffer
  14174. */
  14175. Engine.prototype.createInstancesBuffer = function (capacity) {
  14176. var buffer = this._gl.createBuffer();
  14177. if (!buffer) {
  14178. throw new Error("Unable to create instance buffer");
  14179. }
  14180. buffer.capacity = capacity;
  14181. this.bindArrayBuffer(buffer);
  14182. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14183. return buffer;
  14184. };
  14185. /**
  14186. * Delete a webGL buffer used with instanciation
  14187. * @param buffer defines the webGL buffer to delete
  14188. */
  14189. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14190. this._gl.deleteBuffer(buffer);
  14191. };
  14192. /**
  14193. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14194. * @param instancesBuffer defines the webGL buffer to update and bind
  14195. * @param data defines the data to store in the buffer
  14196. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14197. */
  14198. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14199. this.bindArrayBuffer(instancesBuffer);
  14200. if (data) {
  14201. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14202. }
  14203. if (offsetLocations[0].index !== undefined) {
  14204. var stride = 0;
  14205. for (var i = 0; i < offsetLocations.length; i++) {
  14206. var ai = offsetLocations[i];
  14207. stride += ai.attributeSize * 4;
  14208. }
  14209. for (var i = 0; i < offsetLocations.length; i++) {
  14210. var ai = offsetLocations[i];
  14211. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14212. this._gl.enableVertexAttribArray(ai.index);
  14213. this._vertexAttribArraysEnabled[ai.index] = true;
  14214. }
  14215. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14216. this._gl.vertexAttribDivisor(ai.index, 1);
  14217. this._currentInstanceLocations.push(ai.index);
  14218. this._currentInstanceBuffers.push(instancesBuffer);
  14219. }
  14220. }
  14221. else {
  14222. for (var index = 0; index < 4; index++) {
  14223. var offsetLocation = offsetLocations[index];
  14224. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14225. this._gl.enableVertexAttribArray(offsetLocation);
  14226. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14227. }
  14228. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14229. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14230. this._currentInstanceLocations.push(offsetLocation);
  14231. this._currentInstanceBuffers.push(instancesBuffer);
  14232. }
  14233. }
  14234. };
  14235. /**
  14236. * Apply all cached states (depth, culling, stencil and alpha)
  14237. */
  14238. Engine.prototype.applyStates = function () {
  14239. this._depthCullingState.apply(this._gl);
  14240. this._stencilState.apply(this._gl);
  14241. this._alphaState.apply(this._gl);
  14242. };
  14243. /**
  14244. * Send a draw order
  14245. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14246. * @param indexStart defines the starting index
  14247. * @param indexCount defines the number of index to draw
  14248. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14249. */
  14250. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14251. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14252. };
  14253. /**
  14254. * Draw a list of points
  14255. * @param verticesStart defines the index of first vertex to draw
  14256. * @param verticesCount defines the count of vertices to draw
  14257. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14258. */
  14259. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14260. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14261. };
  14262. /**
  14263. * Draw a list of unindexed primitives
  14264. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14265. * @param verticesStart defines the index of first vertex to draw
  14266. * @param verticesCount defines the count of vertices to draw
  14267. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14268. */
  14269. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14270. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14271. };
  14272. /**
  14273. * Draw a list of indexed primitives
  14274. * @param fillMode defines the primitive to use
  14275. * @param indexStart defines the starting index
  14276. * @param indexCount defines the number of index to draw
  14277. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14278. */
  14279. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14280. // Apply states
  14281. this.applyStates();
  14282. this._drawCalls.addCount(1, false);
  14283. // Render
  14284. var drawMode = this._drawMode(fillMode);
  14285. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14286. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14287. if (instancesCount) {
  14288. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14289. }
  14290. else {
  14291. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14292. }
  14293. };
  14294. /**
  14295. * Draw a list of unindexed primitives
  14296. * @param fillMode defines the primitive to use
  14297. * @param verticesStart defines the index of first vertex to draw
  14298. * @param verticesCount defines the count of vertices to draw
  14299. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14300. */
  14301. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14302. // Apply states
  14303. this.applyStates();
  14304. this._drawCalls.addCount(1, false);
  14305. var drawMode = this._drawMode(fillMode);
  14306. if (instancesCount) {
  14307. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14308. }
  14309. else {
  14310. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14311. }
  14312. };
  14313. Engine.prototype._drawMode = function (fillMode) {
  14314. switch (fillMode) {
  14315. // Triangle views
  14316. case BABYLON.Material.TriangleFillMode:
  14317. return this._gl.TRIANGLES;
  14318. case BABYLON.Material.PointFillMode:
  14319. return this._gl.POINTS;
  14320. case BABYLON.Material.WireFrameFillMode:
  14321. return this._gl.LINES;
  14322. // Draw modes
  14323. case BABYLON.Material.PointListDrawMode:
  14324. return this._gl.POINTS;
  14325. case BABYLON.Material.LineListDrawMode:
  14326. return this._gl.LINES;
  14327. case BABYLON.Material.LineLoopDrawMode:
  14328. return this._gl.LINE_LOOP;
  14329. case BABYLON.Material.LineStripDrawMode:
  14330. return this._gl.LINE_STRIP;
  14331. case BABYLON.Material.TriangleStripDrawMode:
  14332. return this._gl.TRIANGLE_STRIP;
  14333. case BABYLON.Material.TriangleFanDrawMode:
  14334. return this._gl.TRIANGLE_FAN;
  14335. default:
  14336. return this._gl.TRIANGLES;
  14337. }
  14338. };
  14339. // Shaders
  14340. /** @hidden */
  14341. Engine.prototype._releaseEffect = function (effect) {
  14342. if (this._compiledEffects[effect._key]) {
  14343. delete this._compiledEffects[effect._key];
  14344. this._deleteProgram(effect.getProgram());
  14345. }
  14346. };
  14347. /** @hidden */
  14348. Engine.prototype._deleteProgram = function (program) {
  14349. if (program) {
  14350. program.__SPECTOR_rebuildProgram = null;
  14351. if (program.transformFeedback) {
  14352. this.deleteTransformFeedback(program.transformFeedback);
  14353. program.transformFeedback = null;
  14354. }
  14355. this._gl.deleteProgram(program);
  14356. }
  14357. };
  14358. /**
  14359. * Create a new effect (used to store vertex/fragment shaders)
  14360. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14361. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14362. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14363. * @param samplers defines an array of string used to represent textures
  14364. * @param defines defines the string containing the defines to use to compile the shaders
  14365. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14366. * @param onCompiled defines a function to call when the effect creation is successful
  14367. * @param onError defines a function to call when the effect creation has failed
  14368. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14369. * @returns the new Effect
  14370. */
  14371. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14372. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14373. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14374. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14375. if (this._compiledEffects[name]) {
  14376. var compiledEffect = this._compiledEffects[name];
  14377. if (onCompiled && compiledEffect.isReady()) {
  14378. onCompiled(compiledEffect);
  14379. }
  14380. return compiledEffect;
  14381. }
  14382. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14383. effect._key = name;
  14384. this._compiledEffects[name] = effect;
  14385. return effect;
  14386. };
  14387. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14388. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14389. };
  14390. ;
  14391. Engine.prototype._compileRawShader = function (source, type) {
  14392. var gl = this._gl;
  14393. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14394. gl.shaderSource(shader, source);
  14395. gl.compileShader(shader);
  14396. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14397. var log = gl.getShaderInfoLog(shader);
  14398. if (log) {
  14399. throw new Error(log);
  14400. }
  14401. }
  14402. if (!shader) {
  14403. throw new Error("Something went wrong while compile the shader.");
  14404. }
  14405. return shader;
  14406. };
  14407. ;
  14408. /**
  14409. * Directly creates a webGL program
  14410. * @param vertexCode defines the vertex shader code to use
  14411. * @param fragmentCode defines the fragment shader code to use
  14412. * @param context defines the webGL context to use (if not set, the current one will be used)
  14413. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14414. * @returns the new webGL program
  14415. */
  14416. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14417. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14418. context = context || this._gl;
  14419. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14420. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14421. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14422. };
  14423. /**
  14424. * Creates a webGL program
  14425. * @param vertexCode defines the vertex shader code to use
  14426. * @param fragmentCode defines the fragment shader code to use
  14427. * @param defines defines the string containing the defines to use to compile the shaders
  14428. * @param context defines the webGL context to use (if not set, the current one will be used)
  14429. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14430. * @returns the new webGL program
  14431. */
  14432. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14433. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14434. context = context || this._gl;
  14435. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14436. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14437. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14438. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14439. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14440. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14441. return program;
  14442. };
  14443. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14444. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14445. var shaderProgram = context.createProgram();
  14446. if (!shaderProgram) {
  14447. throw new Error("Unable to create program");
  14448. }
  14449. context.attachShader(shaderProgram, vertexShader);
  14450. context.attachShader(shaderProgram, fragmentShader);
  14451. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14452. var transformFeedback = this.createTransformFeedback();
  14453. this.bindTransformFeedback(transformFeedback);
  14454. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14455. shaderProgram.transformFeedback = transformFeedback;
  14456. }
  14457. context.linkProgram(shaderProgram);
  14458. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14459. this.bindTransformFeedback(null);
  14460. }
  14461. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14462. if (!linked) {
  14463. var error = context.getProgramInfoLog(shaderProgram);
  14464. if (error) {
  14465. throw new Error(error);
  14466. }
  14467. }
  14468. if (this.validateShaderPrograms) {
  14469. context.validateProgram(shaderProgram);
  14470. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14471. if (!validated) {
  14472. var error = context.getProgramInfoLog(shaderProgram);
  14473. if (error) {
  14474. throw new Error(error);
  14475. }
  14476. }
  14477. }
  14478. context.deleteShader(vertexShader);
  14479. context.deleteShader(fragmentShader);
  14480. return shaderProgram;
  14481. };
  14482. /**
  14483. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14484. * @param shaderProgram defines the webGL program to use
  14485. * @param uniformsNames defines the list of uniform names
  14486. * @returns an array of webGL uniform locations
  14487. */
  14488. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14489. var results = new Array();
  14490. for (var index = 0; index < uniformsNames.length; index++) {
  14491. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14492. }
  14493. return results;
  14494. };
  14495. /**
  14496. * Gets the lsit of active attributes for a given webGL program
  14497. * @param shaderProgram defines the webGL program to use
  14498. * @param attributesNames defines the list of attribute names to get
  14499. * @returns an array of indices indicating the offset of each attribute
  14500. */
  14501. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14502. var results = [];
  14503. for (var index = 0; index < attributesNames.length; index++) {
  14504. try {
  14505. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14506. }
  14507. catch (e) {
  14508. results.push(-1);
  14509. }
  14510. }
  14511. return results;
  14512. };
  14513. /**
  14514. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14515. * @param effect defines the effect to activate
  14516. */
  14517. Engine.prototype.enableEffect = function (effect) {
  14518. if (!effect || effect === this._currentEffect) {
  14519. return;
  14520. }
  14521. // Use program
  14522. this.bindSamplers(effect);
  14523. this._currentEffect = effect;
  14524. if (effect.onBind) {
  14525. effect.onBind(effect);
  14526. }
  14527. if (effect._onBindObservable) {
  14528. effect._onBindObservable.notifyObservers(effect);
  14529. }
  14530. };
  14531. /**
  14532. * Set the value of an uniform to an array of int32
  14533. * @param uniform defines the webGL uniform location where to store the value
  14534. * @param array defines the array of int32 to store
  14535. */
  14536. Engine.prototype.setIntArray = function (uniform, array) {
  14537. if (!uniform)
  14538. return;
  14539. this._gl.uniform1iv(uniform, array);
  14540. };
  14541. /**
  14542. * Set the value of an uniform to an array of int32 (stored as vec2)
  14543. * @param uniform defines the webGL uniform location where to store the value
  14544. * @param array defines the array of int32 to store
  14545. */
  14546. Engine.prototype.setIntArray2 = function (uniform, array) {
  14547. if (!uniform || array.length % 2 !== 0)
  14548. return;
  14549. this._gl.uniform2iv(uniform, array);
  14550. };
  14551. /**
  14552. * Set the value of an uniform to an array of int32 (stored as vec3)
  14553. * @param uniform defines the webGL uniform location where to store the value
  14554. * @param array defines the array of int32 to store
  14555. */
  14556. Engine.prototype.setIntArray3 = function (uniform, array) {
  14557. if (!uniform || array.length % 3 !== 0)
  14558. return;
  14559. this._gl.uniform3iv(uniform, array);
  14560. };
  14561. /**
  14562. * Set the value of an uniform to an array of int32 (stored as vec4)
  14563. * @param uniform defines the webGL uniform location where to store the value
  14564. * @param array defines the array of int32 to store
  14565. */
  14566. Engine.prototype.setIntArray4 = function (uniform, array) {
  14567. if (!uniform || array.length % 4 !== 0)
  14568. return;
  14569. this._gl.uniform4iv(uniform, array);
  14570. };
  14571. /**
  14572. * Set the value of an uniform to an array of float32
  14573. * @param uniform defines the webGL uniform location where to store the value
  14574. * @param array defines the array of float32 to store
  14575. */
  14576. Engine.prototype.setFloatArray = function (uniform, array) {
  14577. if (!uniform)
  14578. return;
  14579. this._gl.uniform1fv(uniform, array);
  14580. };
  14581. /**
  14582. * Set the value of an uniform to an array of float32 (stored as vec2)
  14583. * @param uniform defines the webGL uniform location where to store the value
  14584. * @param array defines the array of float32 to store
  14585. */
  14586. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14587. if (!uniform || array.length % 2 !== 0)
  14588. return;
  14589. this._gl.uniform2fv(uniform, array);
  14590. };
  14591. /**
  14592. * Set the value of an uniform to an array of float32 (stored as vec3)
  14593. * @param uniform defines the webGL uniform location where to store the value
  14594. * @param array defines the array of float32 to store
  14595. */
  14596. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14597. if (!uniform || array.length % 3 !== 0)
  14598. return;
  14599. this._gl.uniform3fv(uniform, array);
  14600. };
  14601. /**
  14602. * Set the value of an uniform to an array of float32 (stored as vec4)
  14603. * @param uniform defines the webGL uniform location where to store the value
  14604. * @param array defines the array of float32 to store
  14605. */
  14606. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14607. if (!uniform || array.length % 4 !== 0)
  14608. return;
  14609. this._gl.uniform4fv(uniform, array);
  14610. };
  14611. /**
  14612. * Set the value of an uniform to an array of number
  14613. * @param uniform defines the webGL uniform location where to store the value
  14614. * @param array defines the array of number to store
  14615. */
  14616. Engine.prototype.setArray = function (uniform, array) {
  14617. if (!uniform)
  14618. return;
  14619. this._gl.uniform1fv(uniform, array);
  14620. };
  14621. /**
  14622. * Set the value of an uniform to an array of number (stored as vec2)
  14623. * @param uniform defines the webGL uniform location where to store the value
  14624. * @param array defines the array of number to store
  14625. */
  14626. Engine.prototype.setArray2 = function (uniform, array) {
  14627. if (!uniform || array.length % 2 !== 0)
  14628. return;
  14629. this._gl.uniform2fv(uniform, array);
  14630. };
  14631. /**
  14632. * Set the value of an uniform to an array of number (stored as vec3)
  14633. * @param uniform defines the webGL uniform location where to store the value
  14634. * @param array defines the array of number to store
  14635. */
  14636. Engine.prototype.setArray3 = function (uniform, array) {
  14637. if (!uniform || array.length % 3 !== 0)
  14638. return;
  14639. this._gl.uniform3fv(uniform, array);
  14640. };
  14641. /**
  14642. * Set the value of an uniform to an array of number (stored as vec4)
  14643. * @param uniform defines the webGL uniform location where to store the value
  14644. * @param array defines the array of number to store
  14645. */
  14646. Engine.prototype.setArray4 = function (uniform, array) {
  14647. if (!uniform || array.length % 4 !== 0)
  14648. return;
  14649. this._gl.uniform4fv(uniform, array);
  14650. };
  14651. /**
  14652. * Set the value of an uniform to an array of float32 (stored as matrices)
  14653. * @param uniform defines the webGL uniform location where to store the value
  14654. * @param matrices defines the array of float32 to store
  14655. */
  14656. Engine.prototype.setMatrices = function (uniform, matrices) {
  14657. if (!uniform)
  14658. return;
  14659. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14660. };
  14661. /**
  14662. * Set the value of an uniform to a matrix
  14663. * @param uniform defines the webGL uniform location where to store the value
  14664. * @param matrix defines the matrix to store
  14665. */
  14666. Engine.prototype.setMatrix = function (uniform, matrix) {
  14667. if (!uniform)
  14668. return;
  14669. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14670. };
  14671. /**
  14672. * Set the value of an uniform to a matrix (3x3)
  14673. * @param uniform defines the webGL uniform location where to store the value
  14674. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14675. */
  14676. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14677. if (!uniform)
  14678. return;
  14679. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14680. };
  14681. /**
  14682. * Set the value of an uniform to a matrix (2x2)
  14683. * @param uniform defines the webGL uniform location where to store the value
  14684. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14685. */
  14686. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14687. if (!uniform)
  14688. return;
  14689. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14690. };
  14691. /**
  14692. * Set the value of an uniform to a number (int)
  14693. * @param uniform defines the webGL uniform location where to store the value
  14694. * @param value defines the int number to store
  14695. */
  14696. Engine.prototype.setInt = function (uniform, value) {
  14697. if (!uniform)
  14698. return;
  14699. this._gl.uniform1i(uniform, value);
  14700. };
  14701. /**
  14702. * Set the value of an uniform to a number (float)
  14703. * @param uniform defines the webGL uniform location where to store the value
  14704. * @param value defines the float number to store
  14705. */
  14706. Engine.prototype.setFloat = function (uniform, value) {
  14707. if (!uniform)
  14708. return;
  14709. this._gl.uniform1f(uniform, value);
  14710. };
  14711. /**
  14712. * Set the value of an uniform to a vec2
  14713. * @param uniform defines the webGL uniform location where to store the value
  14714. * @param x defines the 1st component of the value
  14715. * @param y defines the 2nd component of the value
  14716. */
  14717. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14718. if (!uniform)
  14719. return;
  14720. this._gl.uniform2f(uniform, x, y);
  14721. };
  14722. /**
  14723. * Set the value of an uniform to a vec3
  14724. * @param uniform defines the webGL uniform location where to store the value
  14725. * @param x defines the 1st component of the value
  14726. * @param y defines the 2nd component of the value
  14727. * @param z defines the 3rd component of the value
  14728. */
  14729. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14730. if (!uniform)
  14731. return;
  14732. this._gl.uniform3f(uniform, x, y, z);
  14733. };
  14734. /**
  14735. * Set the value of an uniform to a boolean
  14736. * @param uniform defines the webGL uniform location where to store the value
  14737. * @param bool defines the boolean to store
  14738. */
  14739. Engine.prototype.setBool = function (uniform, bool) {
  14740. if (!uniform)
  14741. return;
  14742. this._gl.uniform1i(uniform, bool);
  14743. };
  14744. /**
  14745. * Set the value of an uniform to a vec4
  14746. * @param uniform defines the webGL uniform location where to store the value
  14747. * @param x defines the 1st component of the value
  14748. * @param y defines the 2nd component of the value
  14749. * @param z defines the 3rd component of the value
  14750. * @param w defines the 4th component of the value
  14751. */
  14752. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14753. if (!uniform)
  14754. return;
  14755. this._gl.uniform4f(uniform, x, y, z, w);
  14756. };
  14757. /**
  14758. * Set the value of an uniform to a Color3
  14759. * @param uniform defines the webGL uniform location where to store the value
  14760. * @param color3 defines the color to store
  14761. */
  14762. Engine.prototype.setColor3 = function (uniform, color3) {
  14763. if (!uniform)
  14764. return;
  14765. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14766. };
  14767. /**
  14768. * Set the value of an uniform to a Color3 and an alpha value
  14769. * @param uniform defines the webGL uniform location where to store the value
  14770. * @param color3 defines the color to store
  14771. * @param alpha defines the alpha component to store
  14772. */
  14773. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14774. if (!uniform)
  14775. return;
  14776. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14777. };
  14778. /**
  14779. * Sets a Color4 on a uniform variable
  14780. * @param uniform defines the uniform location
  14781. * @param color4 defines the value to be set
  14782. */
  14783. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14784. if (!uniform)
  14785. return;
  14786. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14787. };
  14788. // States
  14789. /**
  14790. * Set various states to the webGL context
  14791. * @param culling defines backface culling state
  14792. * @param zOffset defines the value to apply to zOffset (0 by default)
  14793. * @param force defines if states must be applied even if cache is up to date
  14794. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14795. */
  14796. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14797. if (zOffset === void 0) { zOffset = 0; }
  14798. if (reverseSide === void 0) { reverseSide = false; }
  14799. // Culling
  14800. if (this._depthCullingState.cull !== culling || force) {
  14801. this._depthCullingState.cull = culling;
  14802. }
  14803. // Cull face
  14804. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14805. if (this._depthCullingState.cullFace !== cullFace || force) {
  14806. this._depthCullingState.cullFace = cullFace;
  14807. }
  14808. // Z offset
  14809. this.setZOffset(zOffset);
  14810. // Front face
  14811. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14812. if (this._depthCullingState.frontFace !== frontFace || force) {
  14813. this._depthCullingState.frontFace = frontFace;
  14814. }
  14815. };
  14816. /**
  14817. * Set the z offset to apply to current rendering
  14818. * @param value defines the offset to apply
  14819. */
  14820. Engine.prototype.setZOffset = function (value) {
  14821. this._depthCullingState.zOffset = value;
  14822. };
  14823. /**
  14824. * Gets the current value of the zOffset
  14825. * @returns the current zOffset state
  14826. */
  14827. Engine.prototype.getZOffset = function () {
  14828. return this._depthCullingState.zOffset;
  14829. };
  14830. /**
  14831. * Enable or disable depth buffering
  14832. * @param enable defines the state to set
  14833. */
  14834. Engine.prototype.setDepthBuffer = function (enable) {
  14835. this._depthCullingState.depthTest = enable;
  14836. };
  14837. /**
  14838. * Gets a boolean indicating if depth writing is enabled
  14839. * @returns the current depth writing state
  14840. */
  14841. Engine.prototype.getDepthWrite = function () {
  14842. return this._depthCullingState.depthMask;
  14843. };
  14844. /**
  14845. * Enable or disable depth writing
  14846. * @param enable defines the state to set
  14847. */
  14848. Engine.prototype.setDepthWrite = function (enable) {
  14849. this._depthCullingState.depthMask = enable;
  14850. };
  14851. /**
  14852. * Enable or disable color writing
  14853. * @param enable defines the state to set
  14854. */
  14855. Engine.prototype.setColorWrite = function (enable) {
  14856. this._gl.colorMask(enable, enable, enable, enable);
  14857. this._colorWrite = enable;
  14858. };
  14859. /**
  14860. * Gets a boolean indicating if color writing is enabled
  14861. * @returns the current color writing state
  14862. */
  14863. Engine.prototype.getColorWrite = function () {
  14864. return this._colorWrite;
  14865. };
  14866. /**
  14867. * Sets alpha constants used by some alpha blending modes
  14868. * @param r defines the red component
  14869. * @param g defines the green component
  14870. * @param b defines the blue component
  14871. * @param a defines the alpha component
  14872. */
  14873. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14874. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14875. };
  14876. /**
  14877. * Sets the current alpha mode
  14878. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14879. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14880. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14881. */
  14882. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14883. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14884. if (this._alphaMode === mode) {
  14885. return;
  14886. }
  14887. switch (mode) {
  14888. case Engine.ALPHA_DISABLE:
  14889. this._alphaState.alphaBlend = false;
  14890. break;
  14891. case Engine.ALPHA_PREMULTIPLIED:
  14892. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14893. this._alphaState.alphaBlend = true;
  14894. break;
  14895. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14896. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14897. this._alphaState.alphaBlend = true;
  14898. break;
  14899. case Engine.ALPHA_COMBINE:
  14900. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14901. this._alphaState.alphaBlend = true;
  14902. break;
  14903. case Engine.ALPHA_ONEONE:
  14904. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14905. this._alphaState.alphaBlend = true;
  14906. break;
  14907. case Engine.ALPHA_ADD:
  14908. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14909. this._alphaState.alphaBlend = true;
  14910. break;
  14911. case Engine.ALPHA_SUBTRACT:
  14912. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14913. this._alphaState.alphaBlend = true;
  14914. break;
  14915. case Engine.ALPHA_MULTIPLY:
  14916. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14917. this._alphaState.alphaBlend = true;
  14918. break;
  14919. case Engine.ALPHA_MAXIMIZED:
  14920. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14921. this._alphaState.alphaBlend = true;
  14922. break;
  14923. case Engine.ALPHA_INTERPOLATE:
  14924. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14925. this._alphaState.alphaBlend = true;
  14926. break;
  14927. case Engine.ALPHA_SCREENMODE:
  14928. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14929. this._alphaState.alphaBlend = true;
  14930. break;
  14931. }
  14932. if (!noDepthWriteChange) {
  14933. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14934. }
  14935. this._alphaMode = mode;
  14936. };
  14937. /**
  14938. * Gets the current alpha mode
  14939. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14940. * @returns the current alpha mode
  14941. */
  14942. Engine.prototype.getAlphaMode = function () {
  14943. return this._alphaMode;
  14944. };
  14945. // Textures
  14946. /**
  14947. * Clears the list of texture accessible through engine.
  14948. * This can help preventing texture load conflict due to name collision.
  14949. */
  14950. Engine.prototype.clearInternalTexturesCache = function () {
  14951. this._internalTexturesCache = [];
  14952. };
  14953. /**
  14954. * Force the entire cache to be cleared
  14955. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14956. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14957. */
  14958. Engine.prototype.wipeCaches = function (bruteForce) {
  14959. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14960. return;
  14961. }
  14962. this._currentEffect = null;
  14963. this._viewportCached.x = 0;
  14964. this._viewportCached.y = 0;
  14965. this._viewportCached.z = 0;
  14966. this._viewportCached.w = 0;
  14967. if (bruteForce) {
  14968. this.resetTextureCache();
  14969. this._currentProgram = null;
  14970. this._stencilState.reset();
  14971. this._depthCullingState.reset();
  14972. this.setDepthFunctionToLessOrEqual();
  14973. this._alphaState.reset();
  14974. this._unpackFlipYCached = null;
  14975. }
  14976. this._resetVertexBufferBinding();
  14977. this._cachedIndexBuffer = null;
  14978. this._cachedEffectForVertexBuffers = null;
  14979. this._unbindVertexArrayObject();
  14980. this.bindIndexBuffer(null);
  14981. };
  14982. /**
  14983. * Set the compressed texture format to use, based on the formats you have, and the formats
  14984. * supported by the hardware / browser.
  14985. *
  14986. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14987. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14988. * to API arguments needed to compressed textures. This puts the burden on the container
  14989. * generator to house the arcane code for determining these for current & future formats.
  14990. *
  14991. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14992. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14993. *
  14994. * Note: The result of this call is not taken into account when a texture is base64.
  14995. *
  14996. * @param formatsAvailable defines the list of those format families you have created
  14997. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14998. *
  14999. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15000. * @returns The extension selected.
  15001. */
  15002. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15003. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15004. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15005. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15006. return this._textureFormatInUse = this._texturesSupported[i];
  15007. }
  15008. }
  15009. }
  15010. // actively set format to nothing, to allow this to be called more than once
  15011. // and possibly fail the 2nd time
  15012. this._textureFormatInUse = null;
  15013. return null;
  15014. };
  15015. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15016. var gl = this._gl;
  15017. var magFilter = gl.NEAREST;
  15018. var minFilter = gl.NEAREST;
  15019. switch (samplingMode) {
  15020. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15021. magFilter = gl.LINEAR;
  15022. if (generateMipMaps) {
  15023. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15024. }
  15025. else {
  15026. minFilter = gl.LINEAR;
  15027. }
  15028. break;
  15029. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15030. magFilter = gl.LINEAR;
  15031. if (generateMipMaps) {
  15032. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15033. }
  15034. else {
  15035. minFilter = gl.LINEAR;
  15036. }
  15037. break;
  15038. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15039. magFilter = gl.NEAREST;
  15040. if (generateMipMaps) {
  15041. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15042. }
  15043. else {
  15044. minFilter = gl.NEAREST;
  15045. }
  15046. break;
  15047. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15048. magFilter = gl.NEAREST;
  15049. if (generateMipMaps) {
  15050. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15051. }
  15052. else {
  15053. minFilter = gl.NEAREST;
  15054. }
  15055. break;
  15056. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15057. magFilter = gl.NEAREST;
  15058. if (generateMipMaps) {
  15059. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15060. }
  15061. else {
  15062. minFilter = gl.LINEAR;
  15063. }
  15064. break;
  15065. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15066. magFilter = gl.NEAREST;
  15067. if (generateMipMaps) {
  15068. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15069. }
  15070. else {
  15071. minFilter = gl.LINEAR;
  15072. }
  15073. break;
  15074. case Engine.TEXTURE_NEAREST_LINEAR:
  15075. magFilter = gl.NEAREST;
  15076. minFilter = gl.LINEAR;
  15077. break;
  15078. case Engine.TEXTURE_NEAREST_NEAREST:
  15079. magFilter = gl.NEAREST;
  15080. minFilter = gl.NEAREST;
  15081. break;
  15082. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15083. magFilter = gl.LINEAR;
  15084. if (generateMipMaps) {
  15085. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15086. }
  15087. else {
  15088. minFilter = gl.NEAREST;
  15089. }
  15090. break;
  15091. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15092. magFilter = gl.LINEAR;
  15093. if (generateMipMaps) {
  15094. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15095. }
  15096. else {
  15097. minFilter = gl.NEAREST;
  15098. }
  15099. break;
  15100. case Engine.TEXTURE_LINEAR_LINEAR:
  15101. magFilter = gl.LINEAR;
  15102. minFilter = gl.LINEAR;
  15103. break;
  15104. case Engine.TEXTURE_LINEAR_NEAREST:
  15105. magFilter = gl.LINEAR;
  15106. minFilter = gl.NEAREST;
  15107. break;
  15108. }
  15109. return {
  15110. min: minFilter,
  15111. mag: magFilter
  15112. };
  15113. };
  15114. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15115. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15116. var img;
  15117. var onload = function () {
  15118. loadedImages[index] = img;
  15119. loadedImages._internalCount++;
  15120. if (scene) {
  15121. scene._removePendingData(img);
  15122. }
  15123. if (loadedImages._internalCount === 6) {
  15124. onfinish(loadedImages);
  15125. }
  15126. };
  15127. var onerror = function (message, exception) {
  15128. if (scene) {
  15129. scene._removePendingData(img);
  15130. }
  15131. if (onErrorCallBack) {
  15132. onErrorCallBack(message, exception);
  15133. }
  15134. };
  15135. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15136. if (scene) {
  15137. scene._addPendingData(img);
  15138. }
  15139. };
  15140. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15141. if (onError === void 0) { onError = null; }
  15142. var loadedImages = [];
  15143. loadedImages._internalCount = 0;
  15144. for (var index = 0; index < 6; index++) {
  15145. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15146. }
  15147. };
  15148. ;
  15149. /** @hidden */
  15150. Engine.prototype._createTexture = function () {
  15151. var texture = this._gl.createTexture();
  15152. if (!texture) {
  15153. throw new Error("Unable to create texture");
  15154. }
  15155. return texture;
  15156. };
  15157. /**
  15158. * Usually called from BABYLON.Texture.ts.
  15159. * Passed information to create a WebGLTexture
  15160. * @param urlArg defines a value which contains one of the following:
  15161. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15162. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15163. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15164. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15165. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15166. * @param scene needed for loading to the correct scene
  15167. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15168. * @param onLoad optional callback to be called upon successful completion
  15169. * @param onError optional callback to be called upon failure
  15170. * @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
  15171. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15172. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15173. * @param forcedExtension defines the extension to use to pick the right loader
  15174. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15175. */
  15176. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15177. var _this = this;
  15178. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15179. if (onLoad === void 0) { onLoad = null; }
  15180. if (onError === void 0) { onError = null; }
  15181. if (buffer === void 0) { buffer = null; }
  15182. if (fallback === void 0) { fallback = null; }
  15183. if (format === void 0) { format = null; }
  15184. if (forcedExtension === void 0) { forcedExtension = null; }
  15185. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15186. var fromData = url.substr(0, 5) === "data:";
  15187. var fromBlob = url.substr(0, 5) === "blob:";
  15188. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15189. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15190. // establish the file extension, if possible
  15191. var lastDot = url.lastIndexOf('.');
  15192. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15193. var loader = null;
  15194. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15195. var availableLoader = _a[_i];
  15196. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15197. loader = availableLoader;
  15198. break;
  15199. }
  15200. }
  15201. if (loader) {
  15202. url = loader.transformUrl(url, this._textureFormatInUse);
  15203. }
  15204. if (scene) {
  15205. scene._addPendingData(texture);
  15206. }
  15207. texture.url = url;
  15208. texture.generateMipMaps = !noMipmap;
  15209. texture.samplingMode = samplingMode;
  15210. texture.invertY = invertY;
  15211. if (!this._doNotHandleContextLost) {
  15212. // Keep a link to the buffer only if we plan to handle context lost
  15213. texture._buffer = buffer;
  15214. }
  15215. var onLoadObserver = null;
  15216. if (onLoad && !fallback) {
  15217. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15218. }
  15219. if (!fallback)
  15220. this._internalTexturesCache.push(texture);
  15221. var onInternalError = function (message, exception) {
  15222. if (scene) {
  15223. scene._removePendingData(texture);
  15224. }
  15225. var customFallback = false;
  15226. if (loader) {
  15227. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15228. if (fallbackUrl) {
  15229. // Add Back
  15230. customFallback = true;
  15231. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15232. }
  15233. }
  15234. if (!customFallback) {
  15235. if (onLoadObserver) {
  15236. texture.onLoadedObservable.remove(onLoadObserver);
  15237. }
  15238. if (BABYLON.Tools.UseFallbackTexture) {
  15239. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15240. }
  15241. }
  15242. if (onError) {
  15243. onError(message || "Unknown error", exception);
  15244. }
  15245. };
  15246. // processing for non-image formats
  15247. if (loader) {
  15248. var callback = function (data) {
  15249. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15250. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15251. done();
  15252. return false;
  15253. }, samplingMode);
  15254. });
  15255. };
  15256. if (!buffer) {
  15257. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15258. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15259. });
  15260. }
  15261. else {
  15262. callback(buffer);
  15263. }
  15264. }
  15265. else {
  15266. var onload = function (img) {
  15267. if (fromBlob && !_this._doNotHandleContextLost) {
  15268. // We need to store the image if we need to rebuild the texture
  15269. // in case of a webgl context lost
  15270. texture._buffer = img;
  15271. }
  15272. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15273. var gl = _this._gl;
  15274. var isPot = (img.width === potWidth && img.height === potHeight);
  15275. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15276. if (isPot) {
  15277. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15278. return false;
  15279. }
  15280. var maxTextureSize = _this._caps.maxTextureSize;
  15281. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15282. _this._prepareWorkingCanvas();
  15283. if (!_this._workingCanvas || !_this._workingContext) {
  15284. return false;
  15285. }
  15286. _this._workingCanvas.width = potWidth;
  15287. _this._workingCanvas.height = potHeight;
  15288. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15289. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15290. texture.width = potWidth;
  15291. texture.height = potHeight;
  15292. return false;
  15293. }
  15294. else {
  15295. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15296. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15297. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15298. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15302. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15303. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15304. _this._releaseTexture(source_1);
  15305. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15306. continuationCallback();
  15307. });
  15308. }
  15309. return true;
  15310. }, samplingMode);
  15311. };
  15312. if (!fromData || isBase64) {
  15313. if (buffer instanceof HTMLImageElement) {
  15314. onload(buffer);
  15315. }
  15316. else {
  15317. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15318. }
  15319. }
  15320. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15321. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15322. }
  15323. else {
  15324. onload(buffer);
  15325. }
  15326. }
  15327. return texture;
  15328. };
  15329. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15330. var _this = this;
  15331. var rtt = this.createRenderTargetTexture({
  15332. width: destination.width,
  15333. height: destination.height,
  15334. }, {
  15335. generateMipMaps: false,
  15336. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15337. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15338. generateDepthBuffer: false,
  15339. generateStencilBuffer: false
  15340. });
  15341. if (!this._rescalePostProcess) {
  15342. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15343. }
  15344. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15345. _this._rescalePostProcess.onApply = function (effect) {
  15346. effect._bindTexture("textureSampler", source);
  15347. };
  15348. var hostingScene = scene;
  15349. if (!hostingScene) {
  15350. hostingScene = _this.scenes[_this.scenes.length - 1];
  15351. }
  15352. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15353. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15354. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15355. _this.unBindFramebuffer(rtt);
  15356. _this._releaseTexture(rtt);
  15357. if (onComplete) {
  15358. onComplete();
  15359. }
  15360. });
  15361. };
  15362. /**
  15363. * Update a raw texture
  15364. * @param texture defines the texture to update
  15365. * @param data defines the data to store in the texture
  15366. * @param format defines the format of the data
  15367. * @param invertY defines if data must be stored with Y axis inverted
  15368. * @param compression defines the compression used (null by default)
  15369. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15370. */
  15371. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15372. if (compression === void 0) { compression = null; }
  15373. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15374. if (!texture) {
  15375. return;
  15376. }
  15377. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15378. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15379. // babylon's internalFormat but gl's texImage2D format
  15380. var internalFormat = this._getInternalFormat(format);
  15381. var textureType = this._getWebGLTextureType(type);
  15382. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15383. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15384. if (!this._doNotHandleContextLost) {
  15385. texture._bufferView = data;
  15386. texture.format = format;
  15387. texture.type = type;
  15388. texture.invertY = invertY;
  15389. texture._compression = compression;
  15390. }
  15391. if (texture.width % 4 !== 0) {
  15392. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15393. }
  15394. if (compression && data) {
  15395. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15396. }
  15397. else {
  15398. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15399. }
  15400. if (texture.generateMipMaps) {
  15401. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15402. }
  15403. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15404. // this.resetTextureCache();
  15405. texture.isReady = true;
  15406. };
  15407. /**
  15408. * Creates a raw texture
  15409. * @param data defines the data to store in the texture
  15410. * @param width defines the width of the texture
  15411. * @param height defines the height of the texture
  15412. * @param format defines the format of the data
  15413. * @param generateMipMaps defines if the engine should generate the mip levels
  15414. * @param invertY defines if data must be stored with Y axis inverted
  15415. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15416. * @param compression defines the compression used (null by default)
  15417. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15418. * @returns the raw texture inside an InternalTexture
  15419. */
  15420. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15421. if (compression === void 0) { compression = null; }
  15422. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15423. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15424. texture.baseWidth = width;
  15425. texture.baseHeight = height;
  15426. texture.width = width;
  15427. texture.height = height;
  15428. texture.format = format;
  15429. texture.generateMipMaps = generateMipMaps;
  15430. texture.samplingMode = samplingMode;
  15431. texture.invertY = invertY;
  15432. texture._compression = compression;
  15433. texture.type = type;
  15434. if (!this._doNotHandleContextLost) {
  15435. texture._bufferView = data;
  15436. }
  15437. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15438. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15439. // Filters
  15440. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15441. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15442. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15443. if (generateMipMaps) {
  15444. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15445. }
  15446. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15447. this._internalTexturesCache.push(texture);
  15448. return texture;
  15449. };
  15450. /** @hidden */
  15451. Engine.prototype._unpackFlipY = function (value) {
  15452. if (this._unpackFlipYCached !== value) {
  15453. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15454. if (this.enableUnpackFlipYCached) {
  15455. this._unpackFlipYCached = value;
  15456. }
  15457. }
  15458. };
  15459. /** @hidden */
  15460. Engine.prototype._getUnpackAlignement = function () {
  15461. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15462. };
  15463. /**
  15464. * Creates a dynamic texture
  15465. * @param width defines the width of the texture
  15466. * @param height defines the height of the texture
  15467. * @param generateMipMaps defines if the engine should generate the mip levels
  15468. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15469. * @returns the dynamic texture inside an InternalTexture
  15470. */
  15471. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15472. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15473. texture.baseWidth = width;
  15474. texture.baseHeight = height;
  15475. if (generateMipMaps) {
  15476. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15477. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15478. }
  15479. // this.resetTextureCache();
  15480. texture.width = width;
  15481. texture.height = height;
  15482. texture.isReady = false;
  15483. texture.generateMipMaps = generateMipMaps;
  15484. texture.samplingMode = samplingMode;
  15485. this.updateTextureSamplingMode(samplingMode, texture);
  15486. this._internalTexturesCache.push(texture);
  15487. return texture;
  15488. };
  15489. /**
  15490. * Update the sampling mode of a given texture
  15491. * @param samplingMode defines the required sampling mode
  15492. * @param texture defines the texture to update
  15493. */
  15494. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15495. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15496. if (texture.isCube) {
  15497. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15498. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15499. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15500. }
  15501. else if (texture.is3D) {
  15502. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15503. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15504. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15505. }
  15506. else {
  15507. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15508. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15509. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15510. }
  15511. texture.samplingMode = samplingMode;
  15512. };
  15513. /**
  15514. * Update the content of a dynamic texture
  15515. * @param texture defines the texture to update
  15516. * @param canvas defines the canvas containing the source
  15517. * @param invertY defines if data must be stored with Y axis inverted
  15518. * @param premulAlpha defines if alpha is stored as premultiplied
  15519. * @param format defines the format of the data
  15520. */
  15521. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15522. if (premulAlpha === void 0) { premulAlpha = false; }
  15523. if (!texture) {
  15524. return;
  15525. }
  15526. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15527. this._unpackFlipY(invertY);
  15528. if (premulAlpha) {
  15529. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15530. }
  15531. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15532. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15533. if (texture.generateMipMaps) {
  15534. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15535. }
  15536. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15537. if (premulAlpha) {
  15538. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15539. }
  15540. texture.isReady = true;
  15541. };
  15542. /**
  15543. * Update a video texture
  15544. * @param texture defines the texture to update
  15545. * @param video defines the video element to use
  15546. * @param invertY defines if data must be stored with Y axis inverted
  15547. */
  15548. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15549. if (!texture || texture._isDisabled) {
  15550. return;
  15551. }
  15552. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15553. this._unpackFlipY(!invertY); // Video are upside down by default
  15554. try {
  15555. // Testing video texture support
  15556. if (this._videoTextureSupported === undefined) {
  15557. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15558. if (this._gl.getError() !== 0) {
  15559. this._videoTextureSupported = false;
  15560. }
  15561. else {
  15562. this._videoTextureSupported = true;
  15563. }
  15564. }
  15565. // Copy video through the current working canvas if video texture is not supported
  15566. if (!this._videoTextureSupported) {
  15567. if (!texture._workingCanvas) {
  15568. texture._workingCanvas = document.createElement("canvas");
  15569. var context = texture._workingCanvas.getContext("2d");
  15570. if (!context) {
  15571. throw new Error("Unable to get 2d context");
  15572. }
  15573. texture._workingContext = context;
  15574. texture._workingCanvas.width = texture.width;
  15575. texture._workingCanvas.height = texture.height;
  15576. }
  15577. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15578. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15579. }
  15580. else {
  15581. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15582. }
  15583. if (texture.generateMipMaps) {
  15584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15585. }
  15586. if (!wasPreviouslyBound) {
  15587. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15588. }
  15589. // this.resetTextureCache();
  15590. texture.isReady = true;
  15591. }
  15592. catch (ex) {
  15593. // Something unexpected
  15594. // Let's disable the texture
  15595. texture._isDisabled = true;
  15596. }
  15597. };
  15598. /**
  15599. * Updates a depth texture Comparison Mode and Function.
  15600. * If the comparison Function is equal to 0, the mode will be set to none.
  15601. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15602. * @param texture The texture to set the comparison function for
  15603. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15604. */
  15605. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15606. if (this.webGLVersion === 1) {
  15607. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15608. return;
  15609. }
  15610. var gl = this._gl;
  15611. if (texture.isCube) {
  15612. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15613. if (comparisonFunction === 0) {
  15614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15616. }
  15617. else {
  15618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15619. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15620. }
  15621. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15622. }
  15623. else {
  15624. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15625. if (comparisonFunction === 0) {
  15626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15628. }
  15629. else {
  15630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15632. }
  15633. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15634. }
  15635. texture._comparisonFunction = comparisonFunction;
  15636. };
  15637. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15638. var width = size.width || size;
  15639. var height = size.height || size;
  15640. internalTexture.baseWidth = width;
  15641. internalTexture.baseHeight = height;
  15642. internalTexture.width = width;
  15643. internalTexture.height = height;
  15644. internalTexture.isReady = true;
  15645. internalTexture.samples = 1;
  15646. internalTexture.generateMipMaps = false;
  15647. internalTexture._generateDepthBuffer = true;
  15648. internalTexture._generateStencilBuffer = generateStencil;
  15649. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15650. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15651. internalTexture._comparisonFunction = comparisonFunction;
  15652. var gl = this._gl;
  15653. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15654. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15655. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15656. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15657. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15658. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15659. if (comparisonFunction === 0) {
  15660. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15661. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15662. }
  15663. else {
  15664. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15665. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15666. }
  15667. };
  15668. /**
  15669. * Creates a depth stencil texture.
  15670. * This is only available in WebGL 2 or with the depth texture extension available.
  15671. * @param size The size of face edge in the texture.
  15672. * @param options The options defining the texture.
  15673. * @returns The texture
  15674. */
  15675. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15676. if (options.isCube) {
  15677. var width = size.width || size;
  15678. return this._createDepthStencilCubeTexture(width, options);
  15679. }
  15680. else {
  15681. return this._createDepthStencilTexture(size, options);
  15682. }
  15683. };
  15684. /**
  15685. * Creates a depth stencil texture.
  15686. * This is only available in WebGL 2 or with the depth texture extension available.
  15687. * @param size The size of face edge in the texture.
  15688. * @param options The options defining the texture.
  15689. * @returns The texture
  15690. */
  15691. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15692. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15693. if (!this._caps.depthTextureExtension) {
  15694. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15695. return internalTexture;
  15696. }
  15697. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15698. var gl = this._gl;
  15699. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15700. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15701. if (this.webGLVersion > 1) {
  15702. if (internalOptions.generateStencil) {
  15703. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15704. }
  15705. else {
  15706. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15707. }
  15708. }
  15709. else {
  15710. if (internalOptions.generateStencil) {
  15711. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15712. }
  15713. else {
  15714. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15715. }
  15716. }
  15717. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15718. return internalTexture;
  15719. };
  15720. /**
  15721. * Creates a depth stencil cube texture.
  15722. * This is only available in WebGL 2.
  15723. * @param size The size of face edge in the cube texture.
  15724. * @param options The options defining the cube texture.
  15725. * @returns The cube texture
  15726. */
  15727. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15728. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15729. internalTexture.isCube = true;
  15730. if (this.webGLVersion === 1) {
  15731. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15732. return internalTexture;
  15733. }
  15734. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15735. var gl = this._gl;
  15736. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15737. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15738. // Create the depth/stencil buffer
  15739. for (var face = 0; face < 6; face++) {
  15740. if (internalOptions.generateStencil) {
  15741. 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);
  15742. }
  15743. else {
  15744. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15745. }
  15746. }
  15747. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15748. return internalTexture;
  15749. };
  15750. /**
  15751. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15752. * @param renderTarget The render target to set the frame buffer for
  15753. */
  15754. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15755. // Create the framebuffer
  15756. var internalTexture = renderTarget.getInternalTexture();
  15757. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15758. return;
  15759. }
  15760. var gl = this._gl;
  15761. var depthStencilTexture = renderTarget.depthStencilTexture;
  15762. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15763. if (depthStencilTexture.isCube) {
  15764. if (depthStencilTexture._generateStencilBuffer) {
  15765. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15766. }
  15767. else {
  15768. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15769. }
  15770. }
  15771. else {
  15772. if (depthStencilTexture._generateStencilBuffer) {
  15773. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15774. }
  15775. else {
  15776. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15777. }
  15778. }
  15779. this.bindUnboundFramebuffer(null);
  15780. };
  15781. /**
  15782. * Creates a new render target texture
  15783. * @param size defines the size of the texture
  15784. * @param options defines the options used to create the texture
  15785. * @returns a new render target texture stored in an InternalTexture
  15786. */
  15787. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15788. var fullOptions = new RenderTargetCreationOptions();
  15789. if (options !== undefined && typeof options === "object") {
  15790. fullOptions.generateMipMaps = options.generateMipMaps;
  15791. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15792. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15793. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15794. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15795. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15796. }
  15797. else {
  15798. fullOptions.generateMipMaps = options;
  15799. fullOptions.generateDepthBuffer = true;
  15800. fullOptions.generateStencilBuffer = false;
  15801. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15802. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15803. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15804. }
  15805. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15806. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15807. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15808. }
  15809. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15810. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15811. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15812. }
  15813. var gl = this._gl;
  15814. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15815. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15816. var width = size.width || size;
  15817. var height = size.height || size;
  15818. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15819. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15820. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15821. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15822. }
  15823. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15824. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15825. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15826. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15827. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15828. // Create the framebuffer
  15829. var currentFrameBuffer = this._currentFramebuffer;
  15830. var framebuffer = gl.createFramebuffer();
  15831. this.bindUnboundFramebuffer(framebuffer);
  15832. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15833. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15834. if (fullOptions.generateMipMaps) {
  15835. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15836. }
  15837. // Unbind
  15838. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15839. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15840. this.bindUnboundFramebuffer(currentFrameBuffer);
  15841. texture._framebuffer = framebuffer;
  15842. texture.baseWidth = width;
  15843. texture.baseHeight = height;
  15844. texture.width = width;
  15845. texture.height = height;
  15846. texture.isReady = true;
  15847. texture.samples = 1;
  15848. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15849. texture.samplingMode = fullOptions.samplingMode;
  15850. texture.type = fullOptions.type;
  15851. texture.format = fullOptions.format;
  15852. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15853. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15854. // this.resetTextureCache();
  15855. this._internalTexturesCache.push(texture);
  15856. return texture;
  15857. };
  15858. /**
  15859. * Create a multi render target texture
  15860. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15861. * @param size defines the size of the texture
  15862. * @param options defines the creation options
  15863. * @returns the cube texture as an InternalTexture
  15864. */
  15865. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15866. var generateMipMaps = false;
  15867. var generateDepthBuffer = true;
  15868. var generateStencilBuffer = false;
  15869. var generateDepthTexture = false;
  15870. var textureCount = 1;
  15871. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15872. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15873. var types = new Array();
  15874. var samplingModes = new Array();
  15875. if (options !== undefined) {
  15876. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15877. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15878. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15879. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15880. textureCount = options.textureCount || 1;
  15881. if (options.types) {
  15882. types = options.types;
  15883. }
  15884. if (options.samplingModes) {
  15885. samplingModes = options.samplingModes;
  15886. }
  15887. }
  15888. var gl = this._gl;
  15889. // Create the framebuffer
  15890. var framebuffer = gl.createFramebuffer();
  15891. this.bindUnboundFramebuffer(framebuffer);
  15892. var width = size.width || size;
  15893. var height = size.height || size;
  15894. var textures = [];
  15895. var attachments = [];
  15896. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15897. for (var i = 0; i < textureCount; i++) {
  15898. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15899. var type = types[i] || defaultType;
  15900. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15901. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15902. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15903. }
  15904. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15905. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15906. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15907. }
  15908. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15909. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15910. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15911. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15912. }
  15913. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15914. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15915. textures.push(texture);
  15916. attachments.push(attachment);
  15917. gl.activeTexture(gl["TEXTURE" + i]);
  15918. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15920. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15921. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15922. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15923. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15924. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15925. if (generateMipMaps) {
  15926. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15927. }
  15928. // Unbind
  15929. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15930. texture._framebuffer = framebuffer;
  15931. texture._depthStencilBuffer = depthStencilBuffer;
  15932. texture.baseWidth = width;
  15933. texture.baseHeight = height;
  15934. texture.width = width;
  15935. texture.height = height;
  15936. texture.isReady = true;
  15937. texture.samples = 1;
  15938. texture.generateMipMaps = generateMipMaps;
  15939. texture.samplingMode = samplingMode;
  15940. texture.type = type;
  15941. texture._generateDepthBuffer = generateDepthBuffer;
  15942. texture._generateStencilBuffer = generateStencilBuffer;
  15943. texture._attachments = attachments;
  15944. this._internalTexturesCache.push(texture);
  15945. }
  15946. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15947. // Depth texture
  15948. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15949. gl.activeTexture(gl.TEXTURE0);
  15950. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15951. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15952. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15954. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15955. 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);
  15956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15957. depthTexture._framebuffer = framebuffer;
  15958. depthTexture.baseWidth = width;
  15959. depthTexture.baseHeight = height;
  15960. depthTexture.width = width;
  15961. depthTexture.height = height;
  15962. depthTexture.isReady = true;
  15963. depthTexture.samples = 1;
  15964. depthTexture.generateMipMaps = generateMipMaps;
  15965. depthTexture.samplingMode = gl.NEAREST;
  15966. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15967. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15968. textures.push(depthTexture);
  15969. this._internalTexturesCache.push(depthTexture);
  15970. }
  15971. gl.drawBuffers(attachments);
  15972. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15973. this.bindUnboundFramebuffer(null);
  15974. this.resetTextureCache();
  15975. return textures;
  15976. };
  15977. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15978. if (samples === void 0) { samples = 1; }
  15979. var depthStencilBuffer = null;
  15980. var gl = this._gl;
  15981. // Create the depth/stencil buffer
  15982. if (generateStencilBuffer) {
  15983. depthStencilBuffer = gl.createRenderbuffer();
  15984. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15985. if (samples > 1) {
  15986. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15987. }
  15988. else {
  15989. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15990. }
  15991. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15992. }
  15993. else if (generateDepthBuffer) {
  15994. depthStencilBuffer = gl.createRenderbuffer();
  15995. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15996. if (samples > 1) {
  15997. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15998. }
  15999. else {
  16000. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16001. }
  16002. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16003. }
  16004. return depthStencilBuffer;
  16005. };
  16006. /**
  16007. * Updates the sample count of a render target texture
  16008. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16009. * @param texture defines the texture to update
  16010. * @param samples defines the sample count to set
  16011. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16012. */
  16013. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16014. if (this.webGLVersion < 2 || !texture) {
  16015. return 1;
  16016. }
  16017. if (texture.samples === samples) {
  16018. return samples;
  16019. }
  16020. var gl = this._gl;
  16021. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16022. // Dispose previous render buffers
  16023. if (texture._depthStencilBuffer) {
  16024. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16025. texture._depthStencilBuffer = null;
  16026. }
  16027. if (texture._MSAAFramebuffer) {
  16028. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16029. texture._MSAAFramebuffer = null;
  16030. }
  16031. if (texture._MSAARenderBuffer) {
  16032. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16033. texture._MSAARenderBuffer = null;
  16034. }
  16035. if (samples > 1) {
  16036. var framebuffer = gl.createFramebuffer();
  16037. if (!framebuffer) {
  16038. throw new Error("Unable to create multi sampled framebuffer");
  16039. }
  16040. texture._MSAAFramebuffer = framebuffer;
  16041. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16042. var colorRenderbuffer = gl.createRenderbuffer();
  16043. if (!colorRenderbuffer) {
  16044. throw new Error("Unable to create multi sampled framebuffer");
  16045. }
  16046. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16047. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16048. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16049. texture._MSAARenderBuffer = colorRenderbuffer;
  16050. }
  16051. else {
  16052. this.bindUnboundFramebuffer(texture._framebuffer);
  16053. }
  16054. texture.samples = samples;
  16055. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16056. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16057. this.bindUnboundFramebuffer(null);
  16058. return samples;
  16059. };
  16060. /**
  16061. * Update the sample count for a given multiple render target texture
  16062. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16063. * @param textures defines the textures to update
  16064. * @param samples defines the sample count to set
  16065. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16066. */
  16067. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16068. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16069. return 1;
  16070. }
  16071. if (textures[0].samples === samples) {
  16072. return samples;
  16073. }
  16074. var gl = this._gl;
  16075. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16076. // Dispose previous render buffers
  16077. if (textures[0]._depthStencilBuffer) {
  16078. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16079. textures[0]._depthStencilBuffer = null;
  16080. }
  16081. if (textures[0]._MSAAFramebuffer) {
  16082. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16083. textures[0]._MSAAFramebuffer = null;
  16084. }
  16085. for (var i = 0; i < textures.length; i++) {
  16086. if (textures[i]._MSAARenderBuffer) {
  16087. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16088. textures[i]._MSAARenderBuffer = null;
  16089. }
  16090. }
  16091. if (samples > 1) {
  16092. var framebuffer = gl.createFramebuffer();
  16093. if (!framebuffer) {
  16094. throw new Error("Unable to create multi sampled framebuffer");
  16095. }
  16096. this.bindUnboundFramebuffer(framebuffer);
  16097. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16098. var attachments = [];
  16099. for (var i = 0; i < textures.length; i++) {
  16100. var texture = textures[i];
  16101. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16102. var colorRenderbuffer = gl.createRenderbuffer();
  16103. if (!colorRenderbuffer) {
  16104. throw new Error("Unable to create multi sampled framebuffer");
  16105. }
  16106. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16107. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16108. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16109. texture._MSAAFramebuffer = framebuffer;
  16110. texture._MSAARenderBuffer = colorRenderbuffer;
  16111. texture.samples = samples;
  16112. texture._depthStencilBuffer = depthStencilBuffer;
  16113. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16114. attachments.push(attachment);
  16115. }
  16116. gl.drawBuffers(attachments);
  16117. }
  16118. else {
  16119. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16120. }
  16121. this.bindUnboundFramebuffer(null);
  16122. return samples;
  16123. };
  16124. /** @hidden */
  16125. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16126. if (faceIndex === void 0) { faceIndex = 0; }
  16127. if (lod === void 0) { lod = 0; }
  16128. var gl = this._gl;
  16129. var target = gl.TEXTURE_2D;
  16130. if (texture.isCube) {
  16131. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16132. }
  16133. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16134. };
  16135. /** @hidden */
  16136. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16137. if (faceIndex === void 0) { faceIndex = 0; }
  16138. if (lod === void 0) { lod = 0; }
  16139. var gl = this._gl;
  16140. var textureType = this._getWebGLTextureType(texture.type);
  16141. var format = this._getInternalFormat(texture.format);
  16142. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16143. this._unpackFlipY(texture.invertY);
  16144. var target = gl.TEXTURE_2D;
  16145. if (texture.isCube) {
  16146. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16147. }
  16148. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16149. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16150. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16151. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16152. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16153. };
  16154. /** @hidden */
  16155. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16156. if (faceIndex === void 0) { faceIndex = 0; }
  16157. if (lod === void 0) { lod = 0; }
  16158. var gl = this._gl;
  16159. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16160. this._bindTextureDirectly(bindTarget, texture, true);
  16161. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16162. this._bindTextureDirectly(bindTarget, null, true);
  16163. };
  16164. /** @hidden */
  16165. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16166. if (faceIndex === void 0) { faceIndex = 0; }
  16167. if (lod === void 0) { lod = 0; }
  16168. var gl = this._gl;
  16169. var textureType = this._getWebGLTextureType(texture.type);
  16170. var format = this._getInternalFormat(texture.format);
  16171. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16172. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16173. this._bindTextureDirectly(bindTarget, texture, true);
  16174. this._unpackFlipY(texture.invertY);
  16175. var target = gl.TEXTURE_2D;
  16176. if (texture.isCube) {
  16177. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16178. }
  16179. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16180. this._bindTextureDirectly(bindTarget, null, true);
  16181. };
  16182. /**
  16183. * Creates a new render target cube texture
  16184. * @param size defines the size of the texture
  16185. * @param options defines the options used to create the texture
  16186. * @returns a new render target cube texture stored in an InternalTexture
  16187. */
  16188. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16189. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16190. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16191. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16192. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16193. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16194. }
  16195. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16196. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16197. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16198. }
  16199. var gl = this._gl;
  16200. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16201. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16202. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16203. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16204. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16205. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16206. }
  16207. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16208. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16209. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16210. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16211. for (var face = 0; face < 6; face++) {
  16212. 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);
  16213. }
  16214. // Create the framebuffer
  16215. var framebuffer = gl.createFramebuffer();
  16216. this.bindUnboundFramebuffer(framebuffer);
  16217. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16218. // MipMaps
  16219. if (fullOptions.generateMipMaps) {
  16220. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16221. }
  16222. // Unbind
  16223. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16224. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16225. this.bindUnboundFramebuffer(null);
  16226. texture._framebuffer = framebuffer;
  16227. texture.width = size;
  16228. texture.height = size;
  16229. texture.isReady = true;
  16230. texture.isCube = true;
  16231. texture.samples = 1;
  16232. texture.generateMipMaps = fullOptions.generateMipMaps;
  16233. texture.samplingMode = fullOptions.samplingMode;
  16234. texture.type = fullOptions.type;
  16235. texture.format = fullOptions.format;
  16236. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16237. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16238. this._internalTexturesCache.push(texture);
  16239. return texture;
  16240. };
  16241. /**
  16242. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16243. * @param rootUrl defines the url where the file to load is located
  16244. * @param scene defines the current scene
  16245. * @param lodScale defines scale to apply to the mip map selection
  16246. * @param lodOffset defines offset to apply to the mip map selection
  16247. * @param onLoad defines an optional callback raised when the texture is loaded
  16248. * @param onError defines an optional callback raised if there is an issue to load the texture
  16249. * @param format defines the format of the data
  16250. * @param forcedExtension defines the extension to use to pick the right loader
  16251. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16252. * @returns the cube texture as an InternalTexture
  16253. */
  16254. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16255. var _this = this;
  16256. if (onLoad === void 0) { onLoad = null; }
  16257. if (onError === void 0) { onError = null; }
  16258. if (forcedExtension === void 0) { forcedExtension = null; }
  16259. if (createPolynomials === void 0) { createPolynomials = true; }
  16260. var callback = function (loadData) {
  16261. if (!loadData) {
  16262. if (onLoad) {
  16263. onLoad(null);
  16264. }
  16265. return;
  16266. }
  16267. var texture = loadData.texture;
  16268. if (!createPolynomials) {
  16269. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16270. }
  16271. else if (loadData.info.sphericalPolynomial) {
  16272. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16273. }
  16274. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16275. if (_this._caps.textureLOD) {
  16276. // Do not add extra process if texture lod is supported.
  16277. if (onLoad) {
  16278. onLoad(texture);
  16279. }
  16280. return;
  16281. }
  16282. var mipSlices = 3;
  16283. var gl = _this._gl;
  16284. var width = loadData.width;
  16285. if (!width) {
  16286. return;
  16287. }
  16288. var textures = [];
  16289. for (var i = 0; i < mipSlices; i++) {
  16290. //compute LOD from even spacing in smoothness (matching shader calculation)
  16291. var smoothness = i / (mipSlices - 1);
  16292. var roughness = 1 - smoothness;
  16293. var minLODIndex = lodOffset; // roughness = 0
  16294. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16295. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16296. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16297. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16298. glTextureFromLod.type = texture.type;
  16299. glTextureFromLod.format = texture.format;
  16300. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16301. glTextureFromLod.height = glTextureFromLod.width;
  16302. glTextureFromLod.isCube = true;
  16303. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16305. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16306. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16307. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16308. if (loadData.isDDS) {
  16309. var info = loadData.info;
  16310. var data = loadData.data;
  16311. _this._unpackFlipY(info.isCompressed);
  16312. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16313. }
  16314. else {
  16315. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16316. }
  16317. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16318. // Wrap in a base texture for easy binding.
  16319. var lodTexture = new BABYLON.BaseTexture(scene);
  16320. lodTexture.isCube = true;
  16321. lodTexture._texture = glTextureFromLod;
  16322. glTextureFromLod.isReady = true;
  16323. textures.push(lodTexture);
  16324. }
  16325. texture._lodTextureHigh = textures[2];
  16326. texture._lodTextureMid = textures[1];
  16327. texture._lodTextureLow = textures[0];
  16328. if (onLoad) {
  16329. onLoad(texture);
  16330. }
  16331. };
  16332. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16333. };
  16334. /**
  16335. * Creates a cube texture
  16336. * @param rootUrl defines the url where the files to load is located
  16337. * @param scene defines the current scene
  16338. * @param files defines the list of files to load (1 per face)
  16339. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16340. * @param onLoad defines an optional callback raised when the texture is loaded
  16341. * @param onError defines an optional callback raised if there is an issue to load the texture
  16342. * @param format defines the format of the data
  16343. * @param forcedExtension defines the extension to use to pick the right loader
  16344. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16345. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16346. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16347. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16348. * @returns the cube texture as an InternalTexture
  16349. */
  16350. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16351. var _this = this;
  16352. if (onLoad === void 0) { onLoad = null; }
  16353. if (onError === void 0) { onError = null; }
  16354. if (forcedExtension === void 0) { forcedExtension = null; }
  16355. if (createPolynomials === void 0) { createPolynomials = false; }
  16356. if (lodScale === void 0) { lodScale = 0; }
  16357. if (lodOffset === void 0) { lodOffset = 0; }
  16358. if (fallback === void 0) { fallback = null; }
  16359. var gl = this._gl;
  16360. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16361. texture.isCube = true;
  16362. texture.url = rootUrl;
  16363. texture.generateMipMaps = !noMipmap;
  16364. texture._lodGenerationScale = lodScale;
  16365. texture._lodGenerationOffset = lodOffset;
  16366. if (!this._doNotHandleContextLost) {
  16367. texture._extension = forcedExtension;
  16368. texture._files = files;
  16369. }
  16370. var lastDot = rootUrl.lastIndexOf('.');
  16371. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16372. var loader = null;
  16373. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16374. var availableLoader = _a[_i];
  16375. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16376. loader = availableLoader;
  16377. break;
  16378. }
  16379. }
  16380. var onInternalError = function (request, exception) {
  16381. if (loader) {
  16382. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16383. if (fallbackUrl) {
  16384. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16385. }
  16386. }
  16387. if (onError && request) {
  16388. onError(request.status + " " + request.statusText, exception);
  16389. }
  16390. };
  16391. if (loader) {
  16392. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16393. var onloaddata = function (data) {
  16394. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16395. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16396. };
  16397. if (files && files.length === 6) {
  16398. if (loader.supportCascades) {
  16399. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16400. }
  16401. else if (onError) {
  16402. onError("Textures type does not support cascades.");
  16403. }
  16404. }
  16405. else {
  16406. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16407. }
  16408. }
  16409. else {
  16410. if (!files) {
  16411. throw new Error("Cannot load cubemap because files were not defined");
  16412. }
  16413. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16414. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16415. var height = width;
  16416. _this._prepareWorkingCanvas();
  16417. if (!_this._workingCanvas || !_this._workingContext) {
  16418. return;
  16419. }
  16420. _this._workingCanvas.width = width;
  16421. _this._workingCanvas.height = height;
  16422. var faces = [
  16423. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16424. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16425. ];
  16426. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16427. _this._unpackFlipY(false);
  16428. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16429. for (var index = 0; index < faces.length; index++) {
  16430. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16431. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16432. }
  16433. if (!noMipmap) {
  16434. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16435. }
  16436. _this._setCubeMapTextureParams(!noMipmap);
  16437. texture.width = width;
  16438. texture.height = height;
  16439. texture.isReady = true;
  16440. if (format) {
  16441. texture.format = format;
  16442. }
  16443. texture.onLoadedObservable.notifyObservers(texture);
  16444. texture.onLoadedObservable.clear();
  16445. if (onLoad) {
  16446. onLoad();
  16447. }
  16448. }, files, onError);
  16449. }
  16450. this._internalTexturesCache.push(texture);
  16451. return texture;
  16452. };
  16453. /**
  16454. * @hidden
  16455. */
  16456. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16457. var gl = this._gl;
  16458. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16462. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16463. // this.resetTextureCache();
  16464. };
  16465. /**
  16466. * Update a raw cube texture
  16467. * @param texture defines the texture to udpdate
  16468. * @param data defines the data to store
  16469. * @param format defines the data format
  16470. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16471. * @param invertY defines if data must be stored with Y axis inverted
  16472. * @param compression defines the compression used (null by default)
  16473. * @param level defines which level of the texture to update
  16474. */
  16475. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16476. if (compression === void 0) { compression = null; }
  16477. if (level === void 0) { level = 0; }
  16478. texture._bufferViewArray = data;
  16479. texture.format = format;
  16480. texture.type = type;
  16481. texture.invertY = invertY;
  16482. texture._compression = compression;
  16483. var gl = this._gl;
  16484. var textureType = this._getWebGLTextureType(type);
  16485. var internalFormat = this._getInternalFormat(format);
  16486. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16487. var needConversion = false;
  16488. if (internalFormat === gl.RGB) {
  16489. internalFormat = gl.RGBA;
  16490. needConversion = true;
  16491. }
  16492. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16493. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16494. if (texture.width % 4 !== 0) {
  16495. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16496. }
  16497. // Data are known to be in +X +Y +Z -X -Y -Z
  16498. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16499. var faceData = data[faceIndex];
  16500. if (compression) {
  16501. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16502. }
  16503. else {
  16504. if (needConversion) {
  16505. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16506. }
  16507. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16508. }
  16509. }
  16510. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16511. if (isPot && texture.generateMipMaps && level === 0) {
  16512. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16513. }
  16514. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16515. // this.resetTextureCache();
  16516. texture.isReady = true;
  16517. };
  16518. /**
  16519. * Creates a new raw cube texture
  16520. * @param data defines the array of data to use to create each face
  16521. * @param size defines the size of the textures
  16522. * @param format defines the format of the data
  16523. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16524. * @param generateMipMaps defines if the engine should generate the mip levels
  16525. * @param invertY defines if data must be stored with Y axis inverted
  16526. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16527. * @param compression defines the compression used (null by default)
  16528. * @returns the cube texture as an InternalTexture
  16529. */
  16530. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16531. if (compression === void 0) { compression = null; }
  16532. var gl = this._gl;
  16533. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16534. texture.isCube = true;
  16535. texture.format = format;
  16536. texture.type = type;
  16537. if (!this._doNotHandleContextLost) {
  16538. texture._bufferViewArray = data;
  16539. }
  16540. var textureType = this._getWebGLTextureType(type);
  16541. var internalFormat = this._getInternalFormat(format);
  16542. if (internalFormat === gl.RGB) {
  16543. internalFormat = gl.RGBA;
  16544. }
  16545. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16546. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16547. generateMipMaps = false;
  16548. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16549. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16550. }
  16551. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16552. generateMipMaps = false;
  16553. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16554. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16555. }
  16556. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16557. generateMipMaps = false;
  16558. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16559. }
  16560. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16561. generateMipMaps = false;
  16562. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16563. }
  16564. var width = size;
  16565. var height = width;
  16566. texture.width = width;
  16567. texture.height = height;
  16568. // Double check on POT to generate Mips.
  16569. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16570. if (!isPot) {
  16571. generateMipMaps = false;
  16572. }
  16573. // Upload data if needed. The texture won't be ready until then.
  16574. if (data) {
  16575. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16576. }
  16577. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16578. // Filters
  16579. if (data && generateMipMaps) {
  16580. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16581. }
  16582. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16584. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16587. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16588. texture.generateMipMaps = generateMipMaps;
  16589. return texture;
  16590. };
  16591. /**
  16592. * Creates a new raw cube texture from a specified url
  16593. * @param url defines the url where the data is located
  16594. * @param scene defines the current scene
  16595. * @param size defines the size of the textures
  16596. * @param format defines the format of the data
  16597. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16598. * @param noMipmap defines if the engine should avoid generating the mip levels
  16599. * @param callback defines a callback used to extract texture data from loaded data
  16600. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16601. * @param onLoad defines a callback called when texture is loaded
  16602. * @param onError defines a callback called if there is an error
  16603. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16604. * @param invertY defines if data must be stored with Y axis inverted
  16605. * @returns the cube texture as an InternalTexture
  16606. */
  16607. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16608. var _this = this;
  16609. if (onLoad === void 0) { onLoad = null; }
  16610. if (onError === void 0) { onError = null; }
  16611. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16612. if (invertY === void 0) { invertY = false; }
  16613. var gl = this._gl;
  16614. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16615. scene._addPendingData(texture);
  16616. texture.url = url;
  16617. this._internalTexturesCache.push(texture);
  16618. var onerror = function (request, exception) {
  16619. scene._removePendingData(texture);
  16620. if (onError && request) {
  16621. onError(request.status + " " + request.statusText, exception);
  16622. }
  16623. };
  16624. var internalCallback = function (data) {
  16625. var width = texture.width;
  16626. var faceDataArrays = callback(data);
  16627. if (!faceDataArrays) {
  16628. return;
  16629. }
  16630. if (mipmapGenerator) {
  16631. var textureType = _this._getWebGLTextureType(type);
  16632. var internalFormat = _this._getInternalFormat(format);
  16633. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16634. var needConversion = false;
  16635. if (internalFormat === gl.RGB) {
  16636. internalFormat = gl.RGBA;
  16637. needConversion = true;
  16638. }
  16639. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16640. _this._unpackFlipY(false);
  16641. var mipData = mipmapGenerator(faceDataArrays);
  16642. for (var level = 0; level < mipData.length; level++) {
  16643. var mipSize = width >> level;
  16644. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16645. var mipFaceData = mipData[level][faceIndex];
  16646. if (needConversion) {
  16647. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16648. }
  16649. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16650. }
  16651. }
  16652. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16653. }
  16654. else {
  16655. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16656. }
  16657. texture.isReady = true;
  16658. // this.resetTextureCache();
  16659. scene._removePendingData(texture);
  16660. if (onLoad) {
  16661. onLoad();
  16662. }
  16663. };
  16664. this._loadFile(url, function (data) {
  16665. internalCallback(data);
  16666. }, undefined, scene.database, true, onerror);
  16667. return texture;
  16668. };
  16669. ;
  16670. /**
  16671. * Update a raw 3D texture
  16672. * @param texture defines the texture to update
  16673. * @param data defines the data to store
  16674. * @param format defines the data format
  16675. * @param invertY defines if data must be stored with Y axis inverted
  16676. * @param compression defines the used compression (can be null)
  16677. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16678. */
  16679. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16680. if (compression === void 0) { compression = null; }
  16681. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16682. var internalType = this._getWebGLTextureType(textureType);
  16683. var internalFormat = this._getInternalFormat(format);
  16684. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16685. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16686. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16687. if (!this._doNotHandleContextLost) {
  16688. texture._bufferView = data;
  16689. texture.format = format;
  16690. texture.invertY = invertY;
  16691. texture._compression = compression;
  16692. }
  16693. if (texture.width % 4 !== 0) {
  16694. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16695. }
  16696. if (compression && data) {
  16697. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16698. }
  16699. else {
  16700. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16701. }
  16702. if (texture.generateMipMaps) {
  16703. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16704. }
  16705. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16706. // this.resetTextureCache();
  16707. texture.isReady = true;
  16708. };
  16709. /**
  16710. * Creates a new raw 3D texture
  16711. * @param data defines the data used to create the texture
  16712. * @param width defines the width of the texture
  16713. * @param height defines the height of the texture
  16714. * @param depth defines the depth of the texture
  16715. * @param format defines the format of the texture
  16716. * @param generateMipMaps defines if the engine must generate mip levels
  16717. * @param invertY defines if data must be stored with Y axis inverted
  16718. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16719. * @param compression defines the compressed used (can be null)
  16720. * @param textureType defines the compressed used (can be null)
  16721. * @returns a new raw 3D texture (stored in an InternalTexture)
  16722. */
  16723. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16724. if (compression === void 0) { compression = null; }
  16725. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16726. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16727. texture.baseWidth = width;
  16728. texture.baseHeight = height;
  16729. texture.baseDepth = depth;
  16730. texture.width = width;
  16731. texture.height = height;
  16732. texture.depth = depth;
  16733. texture.format = format;
  16734. texture.type = textureType;
  16735. texture.generateMipMaps = generateMipMaps;
  16736. texture.samplingMode = samplingMode;
  16737. texture.is3D = true;
  16738. if (!this._doNotHandleContextLost) {
  16739. texture._bufferView = data;
  16740. }
  16741. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16742. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16743. // Filters
  16744. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16745. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16746. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16747. if (generateMipMaps) {
  16748. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16749. }
  16750. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16751. this._internalTexturesCache.push(texture);
  16752. return texture;
  16753. };
  16754. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16755. var gl = this._gl;
  16756. if (!gl) {
  16757. return;
  16758. }
  16759. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16760. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16762. if (!noMipmap && !isCompressed) {
  16763. gl.generateMipmap(gl.TEXTURE_2D);
  16764. }
  16765. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16766. // this.resetTextureCache();
  16767. if (scene) {
  16768. scene._removePendingData(texture);
  16769. }
  16770. texture.onLoadedObservable.notifyObservers(texture);
  16771. texture.onLoadedObservable.clear();
  16772. };
  16773. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16774. var _this = this;
  16775. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16776. var maxTextureSize = this.getCaps().maxTextureSize;
  16777. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16778. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16779. var gl = this._gl;
  16780. if (!gl) {
  16781. return;
  16782. }
  16783. if (!texture._webGLTexture) {
  16784. // this.resetTextureCache();
  16785. if (scene) {
  16786. scene._removePendingData(texture);
  16787. }
  16788. return;
  16789. }
  16790. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16791. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16792. texture.baseWidth = width;
  16793. texture.baseHeight = height;
  16794. texture.width = potWidth;
  16795. texture.height = potHeight;
  16796. texture.isReady = true;
  16797. if (processFunction(potWidth, potHeight, function () {
  16798. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16799. })) {
  16800. // Returning as texture needs extra async steps
  16801. return;
  16802. }
  16803. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16804. };
  16805. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16806. // Create new RGBA data container.
  16807. var rgbaData;
  16808. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16809. rgbaData = new Float32Array(width * height * 4);
  16810. }
  16811. else {
  16812. rgbaData = new Uint32Array(width * height * 4);
  16813. }
  16814. // Convert each pixel.
  16815. for (var x = 0; x < width; x++) {
  16816. for (var y = 0; y < height; y++) {
  16817. var index = (y * width + x) * 3;
  16818. var newIndex = (y * width + x) * 4;
  16819. // Map Old Value to new value.
  16820. rgbaData[newIndex + 0] = rgbData[index + 0];
  16821. rgbaData[newIndex + 1] = rgbData[index + 1];
  16822. rgbaData[newIndex + 2] = rgbData[index + 2];
  16823. // Add fully opaque alpha channel.
  16824. rgbaData[newIndex + 3] = 1;
  16825. }
  16826. }
  16827. return rgbaData;
  16828. };
  16829. /** @hidden */
  16830. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16831. var gl = this._gl;
  16832. if (texture._framebuffer) {
  16833. gl.deleteFramebuffer(texture._framebuffer);
  16834. texture._framebuffer = null;
  16835. }
  16836. if (texture._depthStencilBuffer) {
  16837. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16838. texture._depthStencilBuffer = null;
  16839. }
  16840. if (texture._MSAAFramebuffer) {
  16841. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16842. texture._MSAAFramebuffer = null;
  16843. }
  16844. if (texture._MSAARenderBuffer) {
  16845. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16846. texture._MSAARenderBuffer = null;
  16847. }
  16848. };
  16849. /** @hidden */
  16850. Engine.prototype._releaseTexture = function (texture) {
  16851. var gl = this._gl;
  16852. this._releaseFramebufferObjects(texture);
  16853. gl.deleteTexture(texture._webGLTexture);
  16854. // Unbind channels
  16855. this.unbindAllTextures();
  16856. var index = this._internalTexturesCache.indexOf(texture);
  16857. if (index !== -1) {
  16858. this._internalTexturesCache.splice(index, 1);
  16859. }
  16860. // Integrated fixed lod samplers.
  16861. if (texture._lodTextureHigh) {
  16862. texture._lodTextureHigh.dispose();
  16863. }
  16864. if (texture._lodTextureMid) {
  16865. texture._lodTextureMid.dispose();
  16866. }
  16867. if (texture._lodTextureLow) {
  16868. texture._lodTextureLow.dispose();
  16869. }
  16870. // Set output texture of post process to null if the texture has been released/disposed
  16871. this.scenes.forEach(function (scene) {
  16872. scene.postProcesses.forEach(function (postProcess) {
  16873. if (postProcess._outputTexture == texture) {
  16874. postProcess._outputTexture = null;
  16875. }
  16876. });
  16877. scene.cameras.forEach(function (camera) {
  16878. camera._postProcesses.forEach(function (postProcess) {
  16879. if (postProcess) {
  16880. if (postProcess._outputTexture == texture) {
  16881. postProcess._outputTexture = null;
  16882. }
  16883. }
  16884. });
  16885. });
  16886. });
  16887. };
  16888. Engine.prototype.setProgram = function (program) {
  16889. if (this._currentProgram !== program) {
  16890. this._gl.useProgram(program);
  16891. this._currentProgram = program;
  16892. }
  16893. };
  16894. /**
  16895. * Binds an effect to the webGL context
  16896. * @param effect defines the effect to bind
  16897. */
  16898. Engine.prototype.bindSamplers = function (effect) {
  16899. this.setProgram(effect.getProgram());
  16900. var samplers = effect.getSamplers();
  16901. for (var index = 0; index < samplers.length; index++) {
  16902. var uniform = effect.getUniform(samplers[index]);
  16903. if (uniform) {
  16904. this._boundUniforms[index] = uniform;
  16905. }
  16906. }
  16907. this._currentEffect = null;
  16908. };
  16909. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16910. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16911. return;
  16912. }
  16913. // Remove
  16914. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16915. // Bind last to it
  16916. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16917. // Bind to dummy
  16918. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16919. };
  16920. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16921. if (!internalTexture) {
  16922. return -1;
  16923. }
  16924. internalTexture._initialSlot = channel;
  16925. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16926. if (channel !== internalTexture._designatedSlot) {
  16927. this._textureCollisions.addCount(1, false);
  16928. }
  16929. }
  16930. else {
  16931. if (channel !== internalTexture._designatedSlot) {
  16932. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16933. return internalTexture._designatedSlot;
  16934. }
  16935. else {
  16936. // No slot for this texture, let's pick a new one (if we find a free slot)
  16937. if (this._nextFreeTextureSlots.length) {
  16938. return this._nextFreeTextureSlots[0];
  16939. }
  16940. // We need to recycle the oldest bound texture, sorry.
  16941. this._textureCollisions.addCount(1, false);
  16942. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16943. }
  16944. }
  16945. }
  16946. return channel;
  16947. };
  16948. Engine.prototype._linkTrackers = function (previous, next) {
  16949. previous.next = next;
  16950. next.previous = previous;
  16951. };
  16952. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16953. var currentSlot = internalTexture._designatedSlot;
  16954. if (currentSlot === -1) {
  16955. return -1;
  16956. }
  16957. internalTexture._designatedSlot = -1;
  16958. if (this.disableTextureBindingOptimization) {
  16959. return -1;
  16960. }
  16961. // Remove from bound list
  16962. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16963. // Free the slot
  16964. this._boundTexturesCache[currentSlot] = null;
  16965. this._nextFreeTextureSlots.push(currentSlot);
  16966. return currentSlot;
  16967. };
  16968. Engine.prototype._activateCurrentTexture = function () {
  16969. if (this._currentTextureChannel !== this._activeChannel) {
  16970. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16971. this._currentTextureChannel = this._activeChannel;
  16972. }
  16973. };
  16974. /** @hidden */
  16975. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16976. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16977. if (force === void 0) { force = false; }
  16978. var wasPreviouslyBound = false;
  16979. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16980. this._activeChannel = texture._designatedSlot;
  16981. }
  16982. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16983. var isTextureForRendering = texture && texture._initialSlot > -1;
  16984. if (currentTextureBound !== texture || force) {
  16985. if (currentTextureBound) {
  16986. this._removeDesignatedSlot(currentTextureBound);
  16987. }
  16988. this._activateCurrentTexture();
  16989. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16990. this._boundTexturesCache[this._activeChannel] = texture;
  16991. if (texture) {
  16992. if (!this.disableTextureBindingOptimization) {
  16993. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16994. if (slotIndex > -1) {
  16995. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16996. }
  16997. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16998. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16999. }
  17000. texture._designatedSlot = this._activeChannel;
  17001. }
  17002. }
  17003. else if (forTextureDataUpdate) {
  17004. wasPreviouslyBound = true;
  17005. this._activateCurrentTexture();
  17006. }
  17007. if (isTextureForRendering && !forTextureDataUpdate) {
  17008. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17009. }
  17010. return wasPreviouslyBound;
  17011. };
  17012. /** @hidden */
  17013. Engine.prototype._bindTexture = function (channel, texture) {
  17014. if (channel < 0) {
  17015. return;
  17016. }
  17017. if (texture) {
  17018. channel = this._getCorrectTextureChannel(channel, texture);
  17019. }
  17020. this._activeChannel = channel;
  17021. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17022. };
  17023. /**
  17024. * Sets a texture to the webGL context from a postprocess
  17025. * @param channel defines the channel to use
  17026. * @param postProcess defines the source postprocess
  17027. */
  17028. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17029. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17030. };
  17031. /**
  17032. * Binds the output of the passed in post process to the texture channel specified
  17033. * @param channel The channel the texture should be bound to
  17034. * @param postProcess The post process which's output should be bound
  17035. */
  17036. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17037. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17038. };
  17039. /**
  17040. * Unbind all textures from the webGL context
  17041. */
  17042. Engine.prototype.unbindAllTextures = function () {
  17043. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17044. this._activeChannel = channel;
  17045. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17046. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17047. if (this.webGLVersion > 1) {
  17048. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17049. }
  17050. }
  17051. };
  17052. /**
  17053. * Sets a texture to the according uniform.
  17054. * @param channel The texture channel
  17055. * @param uniform The uniform to set
  17056. * @param texture The texture to apply
  17057. */
  17058. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17059. if (channel < 0) {
  17060. return;
  17061. }
  17062. if (uniform) {
  17063. this._boundUniforms[channel] = uniform;
  17064. }
  17065. this._setTexture(channel, texture);
  17066. };
  17067. /**
  17068. * Sets a depth stencil texture from a render target to the according uniform.
  17069. * @param channel The texture channel
  17070. * @param uniform The uniform to set
  17071. * @param texture The render target texture containing the depth stencil texture to apply
  17072. */
  17073. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17074. if (channel < 0) {
  17075. return;
  17076. }
  17077. if (uniform) {
  17078. this._boundUniforms[channel] = uniform;
  17079. }
  17080. if (!texture || !texture.depthStencilTexture) {
  17081. this._setTexture(channel, null);
  17082. }
  17083. else {
  17084. this._setTexture(channel, texture, false, true);
  17085. }
  17086. };
  17087. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17088. var uniform = this._boundUniforms[sourceSlot];
  17089. if (uniform._currentState === destination) {
  17090. return;
  17091. }
  17092. this._gl.uniform1i(uniform, destination);
  17093. uniform._currentState = destination;
  17094. };
  17095. Engine.prototype._getTextureWrapMode = function (mode) {
  17096. switch (mode) {
  17097. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17098. return this._gl.REPEAT;
  17099. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17100. return this._gl.CLAMP_TO_EDGE;
  17101. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17102. return this._gl.MIRRORED_REPEAT;
  17103. }
  17104. return this._gl.REPEAT;
  17105. };
  17106. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17107. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17108. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17109. // Not ready?
  17110. if (!texture) {
  17111. if (this._boundTexturesCache[channel] != null) {
  17112. this._activeChannel = channel;
  17113. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17114. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17115. if (this.webGLVersion > 1) {
  17116. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17117. }
  17118. }
  17119. return false;
  17120. }
  17121. // Video
  17122. if (texture.video) {
  17123. this._activeChannel = channel;
  17124. texture.update();
  17125. }
  17126. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17127. texture.delayLoad();
  17128. return false;
  17129. }
  17130. var internalTexture;
  17131. if (depthStencilTexture) {
  17132. internalTexture = texture.depthStencilTexture;
  17133. }
  17134. else if (texture.isReady()) {
  17135. internalTexture = texture.getInternalTexture();
  17136. }
  17137. else if (texture.isCube) {
  17138. internalTexture = this.emptyCubeTexture;
  17139. }
  17140. else if (texture.is3D) {
  17141. internalTexture = this.emptyTexture3D;
  17142. }
  17143. else {
  17144. internalTexture = this.emptyTexture;
  17145. }
  17146. if (!isPartOfTextureArray) {
  17147. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17148. }
  17149. var needToBind = true;
  17150. if (this._boundTexturesCache[channel] === internalTexture) {
  17151. this._moveBoundTextureOnTop(internalTexture);
  17152. if (!isPartOfTextureArray) {
  17153. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17154. }
  17155. needToBind = false;
  17156. }
  17157. this._activeChannel = channel;
  17158. if (internalTexture && internalTexture.is3D) {
  17159. if (needToBind) {
  17160. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17161. }
  17162. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17163. internalTexture._cachedWrapU = texture.wrapU;
  17164. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17165. }
  17166. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17167. internalTexture._cachedWrapV = texture.wrapV;
  17168. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17169. }
  17170. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17171. internalTexture._cachedWrapR = texture.wrapR;
  17172. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17173. }
  17174. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17175. }
  17176. else if (internalTexture && internalTexture.isCube) {
  17177. if (needToBind) {
  17178. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17179. }
  17180. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17181. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17182. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17183. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17184. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17185. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17186. }
  17187. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17188. }
  17189. else {
  17190. if (needToBind) {
  17191. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17192. }
  17193. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17194. internalTexture._cachedWrapU = texture.wrapU;
  17195. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17196. }
  17197. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17198. internalTexture._cachedWrapV = texture.wrapV;
  17199. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17200. }
  17201. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17202. }
  17203. return true;
  17204. };
  17205. /**
  17206. * Sets an array of texture to the webGL context
  17207. * @param channel defines the channel where the texture array must be set
  17208. * @param uniform defines the associated uniform location
  17209. * @param textures defines the array of textures to bind
  17210. */
  17211. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17212. if (channel < 0 || !uniform) {
  17213. return;
  17214. }
  17215. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17216. this._textureUnits = new Int32Array(textures.length);
  17217. }
  17218. for (var i = 0; i < textures.length; i++) {
  17219. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17220. }
  17221. this._gl.uniform1iv(uniform, this._textureUnits);
  17222. for (var index = 0; index < textures.length; index++) {
  17223. this._setTexture(this._textureUnits[index], textures[index], true);
  17224. }
  17225. };
  17226. /** @hidden */
  17227. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17228. var internalTexture = texture.getInternalTexture();
  17229. if (!internalTexture) {
  17230. return;
  17231. }
  17232. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17233. var value = texture.anisotropicFilteringLevel;
  17234. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17235. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17236. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17237. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17238. }
  17239. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17240. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17241. internalTexture._cachedAnisotropicFilteringLevel = value;
  17242. }
  17243. };
  17244. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17245. this._bindTextureDirectly(target, texture, true, true);
  17246. this._gl.texParameterf(target, parameter, value);
  17247. };
  17248. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17249. if (texture) {
  17250. this._bindTextureDirectly(target, texture, true, true);
  17251. }
  17252. this._gl.texParameteri(target, parameter, value);
  17253. };
  17254. /**
  17255. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17256. * @param x defines the x coordinate of the rectangle where pixels must be read
  17257. * @param y defines the y coordinate of the rectangle where pixels must be read
  17258. * @param width defines the width of the rectangle where pixels must be read
  17259. * @param height defines the height of the rectangle where pixels must be read
  17260. * @returns a Uint8Array containing RGBA colors
  17261. */
  17262. Engine.prototype.readPixels = function (x, y, width, height) {
  17263. var data = new Uint8Array(height * width * 4);
  17264. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17265. return data;
  17266. };
  17267. /**
  17268. * Add an externaly attached data from its key.
  17269. * This method call will fail and return false, if such key already exists.
  17270. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17271. * @param key the unique key that identifies the data
  17272. * @param data the data object to associate to the key for this Engine instance
  17273. * @return true if no such key were already present and the data was added successfully, false otherwise
  17274. */
  17275. Engine.prototype.addExternalData = function (key, data) {
  17276. if (!this._externalData) {
  17277. this._externalData = new BABYLON.StringDictionary();
  17278. }
  17279. return this._externalData.add(key, data);
  17280. };
  17281. /**
  17282. * Get an externaly attached data from its key
  17283. * @param key the unique key that identifies the data
  17284. * @return the associated data, if present (can be null), or undefined if not present
  17285. */
  17286. Engine.prototype.getExternalData = function (key) {
  17287. if (!this._externalData) {
  17288. this._externalData = new BABYLON.StringDictionary();
  17289. }
  17290. return this._externalData.get(key);
  17291. };
  17292. /**
  17293. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17294. * @param key the unique key that identifies the data
  17295. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17296. * @return the associated data, can be null if the factory returned null.
  17297. */
  17298. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17299. if (!this._externalData) {
  17300. this._externalData = new BABYLON.StringDictionary();
  17301. }
  17302. return this._externalData.getOrAddWithFactory(key, factory);
  17303. };
  17304. /**
  17305. * Remove an externaly attached data from the Engine instance
  17306. * @param key the unique key that identifies the data
  17307. * @return true if the data was successfully removed, false if it doesn't exist
  17308. */
  17309. Engine.prototype.removeExternalData = function (key) {
  17310. if (!this._externalData) {
  17311. this._externalData = new BABYLON.StringDictionary();
  17312. }
  17313. return this._externalData.remove(key);
  17314. };
  17315. /**
  17316. * Unbind all vertex attributes from the webGL context
  17317. */
  17318. Engine.prototype.unbindAllAttributes = function () {
  17319. if (this._mustWipeVertexAttributes) {
  17320. this._mustWipeVertexAttributes = false;
  17321. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17322. this._gl.disableVertexAttribArray(i);
  17323. this._vertexAttribArraysEnabled[i] = false;
  17324. this._currentBufferPointers[i].active = false;
  17325. }
  17326. return;
  17327. }
  17328. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17329. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17330. continue;
  17331. }
  17332. this._gl.disableVertexAttribArray(i);
  17333. this._vertexAttribArraysEnabled[i] = false;
  17334. this._currentBufferPointers[i].active = false;
  17335. }
  17336. };
  17337. /**
  17338. * 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
  17339. */
  17340. Engine.prototype.releaseEffects = function () {
  17341. for (var name in this._compiledEffects) {
  17342. this._deleteProgram(this._compiledEffects[name]._program);
  17343. }
  17344. this._compiledEffects = {};
  17345. };
  17346. /**
  17347. * Dispose and release all associated resources
  17348. */
  17349. Engine.prototype.dispose = function () {
  17350. this.hideLoadingUI();
  17351. this.stopRenderLoop();
  17352. // Release postProcesses
  17353. while (this.postProcesses.length) {
  17354. this.postProcesses[0].dispose();
  17355. }
  17356. // Empty texture
  17357. if (this._emptyTexture) {
  17358. this._releaseTexture(this._emptyTexture);
  17359. this._emptyTexture = null;
  17360. }
  17361. if (this._emptyCubeTexture) {
  17362. this._releaseTexture(this._emptyCubeTexture);
  17363. this._emptyCubeTexture = null;
  17364. }
  17365. // Rescale PP
  17366. if (this._rescalePostProcess) {
  17367. this._rescalePostProcess.dispose();
  17368. }
  17369. // Release scenes
  17370. while (this.scenes.length) {
  17371. this.scenes[0].dispose();
  17372. }
  17373. // Release audio engine
  17374. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17375. Engine.audioEngine.dispose();
  17376. }
  17377. // Release effects
  17378. this.releaseEffects();
  17379. // Unbind
  17380. this.unbindAllAttributes();
  17381. this._boundUniforms = [];
  17382. if (this._dummyFramebuffer) {
  17383. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17384. }
  17385. //WebVR
  17386. this.disableVR();
  17387. // Events
  17388. if (BABYLON.Tools.IsWindowObjectExist()) {
  17389. window.removeEventListener("blur", this._onBlur);
  17390. window.removeEventListener("focus", this._onFocus);
  17391. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17392. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17393. if (this._renderingCanvas) {
  17394. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17395. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17396. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17397. if (!this._doNotHandleContextLost) {
  17398. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17399. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17400. }
  17401. }
  17402. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17403. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17404. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17405. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17406. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17407. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17408. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17409. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17410. if (this._onVrDisplayConnect) {
  17411. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17412. if (this._onVrDisplayDisconnect) {
  17413. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17414. }
  17415. if (this._onVrDisplayPresentChange) {
  17416. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17417. }
  17418. this._onVrDisplayConnect = null;
  17419. this._onVrDisplayDisconnect = null;
  17420. }
  17421. }
  17422. // Remove from Instances
  17423. var index = Engine.Instances.indexOf(this);
  17424. if (index >= 0) {
  17425. Engine.Instances.splice(index, 1);
  17426. }
  17427. this._workingCanvas = null;
  17428. this._workingContext = null;
  17429. this._currentBufferPointers = [];
  17430. this._renderingCanvas = null;
  17431. this._currentProgram = null;
  17432. this._bindedRenderFunction = null;
  17433. this.onResizeObservable.clear();
  17434. this.onCanvasBlurObservable.clear();
  17435. this.onCanvasFocusObservable.clear();
  17436. this.onCanvasPointerOutObservable.clear();
  17437. this.onBeginFrameObservable.clear();
  17438. this.onEndFrameObservable.clear();
  17439. BABYLON.Effect.ResetCache();
  17440. // Abort active requests
  17441. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17442. var request = _a[_i];
  17443. request.abort();
  17444. }
  17445. };
  17446. // Loading screen
  17447. /**
  17448. * Display the loading screen
  17449. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17450. */
  17451. Engine.prototype.displayLoadingUI = function () {
  17452. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17453. return;
  17454. }
  17455. var loadingScreen = this.loadingScreen;
  17456. if (loadingScreen) {
  17457. loadingScreen.displayLoadingUI();
  17458. }
  17459. };
  17460. /**
  17461. * Hide the loading screen
  17462. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17463. */
  17464. Engine.prototype.hideLoadingUI = function () {
  17465. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17466. return;
  17467. }
  17468. var loadingScreen = this.loadingScreen;
  17469. if (loadingScreen) {
  17470. loadingScreen.hideLoadingUI();
  17471. }
  17472. };
  17473. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17474. /**
  17475. * Gets the current loading screen object
  17476. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17477. */
  17478. get: function () {
  17479. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17480. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17481. return this._loadingScreen;
  17482. },
  17483. /**
  17484. * Sets the current loading screen object
  17485. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17486. */
  17487. set: function (loadingScreen) {
  17488. this._loadingScreen = loadingScreen;
  17489. },
  17490. enumerable: true,
  17491. configurable: true
  17492. });
  17493. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17494. /**
  17495. * Sets the current loading screen text
  17496. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17497. */
  17498. set: function (text) {
  17499. this.loadingScreen.loadingUIText = text;
  17500. },
  17501. enumerable: true,
  17502. configurable: true
  17503. });
  17504. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17505. /**
  17506. * Sets the current loading screen background color
  17507. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17508. */
  17509. set: function (color) {
  17510. this.loadingScreen.loadingUIBackgroundColor = color;
  17511. },
  17512. enumerable: true,
  17513. configurable: true
  17514. });
  17515. /**
  17516. * Attach a new callback raised when context lost event is fired
  17517. * @param callback defines the callback to call
  17518. */
  17519. Engine.prototype.attachContextLostEvent = function (callback) {
  17520. if (this._renderingCanvas) {
  17521. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17522. }
  17523. };
  17524. /**
  17525. * Attach a new callback raised when context restored event is fired
  17526. * @param callback defines the callback to call
  17527. */
  17528. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17529. if (this._renderingCanvas) {
  17530. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17531. }
  17532. };
  17533. /**
  17534. * Gets the source code of the vertex shader associated with a specific webGL program
  17535. * @param program defines the program to use
  17536. * @returns a string containing the source code of the vertex shader associated with the program
  17537. */
  17538. Engine.prototype.getVertexShaderSource = function (program) {
  17539. var shaders = this._gl.getAttachedShaders(program);
  17540. if (!shaders) {
  17541. return null;
  17542. }
  17543. return this._gl.getShaderSource(shaders[0]);
  17544. };
  17545. /**
  17546. * Gets the source code of the fragment shader associated with a specific webGL program
  17547. * @param program defines the program to use
  17548. * @returns a string containing the source code of the fragment shader associated with the program
  17549. */
  17550. Engine.prototype.getFragmentShaderSource = function (program) {
  17551. var shaders = this._gl.getAttachedShaders(program);
  17552. if (!shaders) {
  17553. return null;
  17554. }
  17555. return this._gl.getShaderSource(shaders[1]);
  17556. };
  17557. /**
  17558. * Get the current error code of the webGL context
  17559. * @returns the error code
  17560. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17561. */
  17562. Engine.prototype.getError = function () {
  17563. return this._gl.getError();
  17564. };
  17565. // FPS
  17566. /**
  17567. * Gets the current framerate
  17568. * @returns a number representing the framerate
  17569. */
  17570. Engine.prototype.getFps = function () {
  17571. return this._fps;
  17572. };
  17573. /**
  17574. * Gets the time spent between current and previous frame
  17575. * @returns a number representing the delta time in ms
  17576. */
  17577. Engine.prototype.getDeltaTime = function () {
  17578. return this._deltaTime;
  17579. };
  17580. Engine.prototype._measureFps = function () {
  17581. this._performanceMonitor.sampleFrame();
  17582. this._fps = this._performanceMonitor.averageFPS;
  17583. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17584. };
  17585. /** @hidden */
  17586. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17587. if (faceIndex === void 0) { faceIndex = -1; }
  17588. if (level === void 0) { level = 0; }
  17589. if (buffer === void 0) { buffer = null; }
  17590. var gl = this._gl;
  17591. if (!this._dummyFramebuffer) {
  17592. var dummy = gl.createFramebuffer();
  17593. if (!dummy) {
  17594. throw new Error("Unable to create dummy framebuffer");
  17595. }
  17596. this._dummyFramebuffer = dummy;
  17597. }
  17598. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17599. if (faceIndex > -1) {
  17600. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17601. }
  17602. else {
  17603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17604. }
  17605. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17606. switch (readType) {
  17607. case gl.UNSIGNED_BYTE:
  17608. if (!buffer) {
  17609. buffer = new Uint8Array(4 * width * height);
  17610. }
  17611. readType = gl.UNSIGNED_BYTE;
  17612. break;
  17613. default:
  17614. if (!buffer) {
  17615. buffer = new Float32Array(4 * width * height);
  17616. }
  17617. readType = gl.FLOAT;
  17618. break;
  17619. }
  17620. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17621. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17622. return buffer;
  17623. };
  17624. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17625. if (this._webGLVersion > 1) {
  17626. return this._caps.colorBufferFloat;
  17627. }
  17628. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17629. };
  17630. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17631. if (this._webGLVersion > 1) {
  17632. return this._caps.colorBufferFloat;
  17633. }
  17634. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17635. };
  17636. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17637. Engine.prototype._canRenderToFramebuffer = function (type) {
  17638. var gl = this._gl;
  17639. //clear existing errors
  17640. while (gl.getError() !== gl.NO_ERROR) { }
  17641. var successful = true;
  17642. var texture = gl.createTexture();
  17643. gl.bindTexture(gl.TEXTURE_2D, texture);
  17644. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17647. var fb = gl.createFramebuffer();
  17648. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17649. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17650. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17651. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17652. successful = successful && (gl.getError() === gl.NO_ERROR);
  17653. //try render by clearing frame buffer's color buffer
  17654. if (successful) {
  17655. gl.clear(gl.COLOR_BUFFER_BIT);
  17656. successful = successful && (gl.getError() === gl.NO_ERROR);
  17657. }
  17658. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17659. if (successful) {
  17660. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17661. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17662. var readFormat = gl.RGBA;
  17663. var readType = gl.UNSIGNED_BYTE;
  17664. var buffer = new Uint8Array(4);
  17665. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17666. successful = successful && (gl.getError() === gl.NO_ERROR);
  17667. }
  17668. //clean up
  17669. gl.deleteTexture(texture);
  17670. gl.deleteFramebuffer(fb);
  17671. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17672. //clear accumulated errors
  17673. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17674. return successful;
  17675. };
  17676. /** @hidden */
  17677. Engine.prototype._getWebGLTextureType = function (type) {
  17678. if (this._webGLVersion === 1) {
  17679. switch (type) {
  17680. case Engine.TEXTURETYPE_FLOAT:
  17681. return this._gl.FLOAT;
  17682. case Engine.TEXTURETYPE_HALF_FLOAT:
  17683. return this._gl.HALF_FLOAT_OES;
  17684. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17685. return this._gl.UNSIGNED_BYTE;
  17686. }
  17687. return this._gl.UNSIGNED_BYTE;
  17688. }
  17689. switch (type) {
  17690. case Engine.TEXTURETYPE_BYTE:
  17691. return this._gl.BYTE;
  17692. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17693. return this._gl.UNSIGNED_BYTE;
  17694. case Engine.TEXTURETYPE_SHORT:
  17695. return this._gl.SHORT;
  17696. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17697. return this._gl.UNSIGNED_SHORT;
  17698. case Engine.TEXTURETYPE_INT:
  17699. return this._gl.INT;
  17700. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17701. return this._gl.UNSIGNED_INT;
  17702. case Engine.TEXTURETYPE_FLOAT:
  17703. return this._gl.FLOAT;
  17704. case Engine.TEXTURETYPE_HALF_FLOAT:
  17705. return this._gl.HALF_FLOAT;
  17706. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17707. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17708. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17709. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17710. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17711. return this._gl.UNSIGNED_SHORT_5_6_5;
  17712. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17713. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17714. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17715. return this._gl.UNSIGNED_INT_24_8;
  17716. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17717. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17718. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17719. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17720. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17721. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17722. }
  17723. return this._gl.UNSIGNED_BYTE;
  17724. };
  17725. ;
  17726. Engine.prototype._getInternalFormat = function (format) {
  17727. var internalFormat = this._gl.RGBA;
  17728. switch (format) {
  17729. case Engine.TEXTUREFORMAT_ALPHA:
  17730. internalFormat = this._gl.ALPHA;
  17731. break;
  17732. case Engine.TEXTUREFORMAT_LUMINANCE:
  17733. internalFormat = this._gl.LUMINANCE;
  17734. break;
  17735. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17736. internalFormat = this._gl.LUMINANCE_ALPHA;
  17737. break;
  17738. case Engine.TEXTUREFORMAT_RED:
  17739. internalFormat = this._gl.RED;
  17740. break;
  17741. case Engine.TEXTUREFORMAT_RG:
  17742. internalFormat = this._gl.RG;
  17743. break;
  17744. case Engine.TEXTUREFORMAT_RGB:
  17745. internalFormat = this._gl.RGB;
  17746. break;
  17747. case Engine.TEXTUREFORMAT_RGBA:
  17748. internalFormat = this._gl.RGBA;
  17749. break;
  17750. }
  17751. if (this._webGLVersion > 1) {
  17752. switch (format) {
  17753. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17754. internalFormat = this._gl.RED_INTEGER;
  17755. break;
  17756. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17757. internalFormat = this._gl.RG_INTEGER;
  17758. break;
  17759. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17760. internalFormat = this._gl.RGB_INTEGER;
  17761. break;
  17762. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17763. internalFormat = this._gl.RGBA_INTEGER;
  17764. break;
  17765. }
  17766. }
  17767. return internalFormat;
  17768. };
  17769. /** @hidden */
  17770. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17771. if (this._webGLVersion === 1) {
  17772. if (format !== undefined) {
  17773. switch (format) {
  17774. case Engine.TEXTUREFORMAT_ALPHA:
  17775. return this._gl.ALPHA;
  17776. case Engine.TEXTUREFORMAT_LUMINANCE:
  17777. return this._gl.LUMINANCE;
  17778. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17779. return this._gl.LUMINANCE_ALPHA;
  17780. }
  17781. }
  17782. return this._gl.RGBA;
  17783. }
  17784. switch (type) {
  17785. case Engine.TEXTURETYPE_BYTE:
  17786. switch (format) {
  17787. case Engine.TEXTUREFORMAT_RED:
  17788. return this._gl.R8_SNORM;
  17789. case Engine.TEXTUREFORMAT_RG:
  17790. return this._gl.RG8_SNORM;
  17791. case Engine.TEXTUREFORMAT_RGB:
  17792. return this._gl.RGB8_SNORM;
  17793. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17794. return this._gl.R8I;
  17795. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17796. return this._gl.RG8I;
  17797. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17798. return this._gl.RGB8I;
  17799. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17800. return this._gl.RGBA8I;
  17801. default:
  17802. return this._gl.RGBA8_SNORM;
  17803. }
  17804. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17805. switch (format) {
  17806. case Engine.TEXTUREFORMAT_RED:
  17807. return this._gl.R8;
  17808. case Engine.TEXTUREFORMAT_RG:
  17809. return this._gl.RG8;
  17810. case Engine.TEXTUREFORMAT_RGB:
  17811. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17812. case Engine.TEXTUREFORMAT_RGBA:
  17813. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17814. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17815. return this._gl.R8UI;
  17816. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17817. return this._gl.RG8UI;
  17818. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17819. return this._gl.RGB8UI;
  17820. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17821. return this._gl.RGBA8UI;
  17822. default:
  17823. return this._gl.RGBA8;
  17824. }
  17825. case Engine.TEXTURETYPE_SHORT:
  17826. switch (format) {
  17827. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17828. return this._gl.R16I;
  17829. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17830. return this._gl.RG16I;
  17831. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17832. return this._gl.RGB16I;
  17833. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17834. return this._gl.RGBA16I;
  17835. default:
  17836. return this._gl.RGBA16I;
  17837. }
  17838. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17839. switch (format) {
  17840. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17841. return this._gl.R16UI;
  17842. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17843. return this._gl.RG16UI;
  17844. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17845. return this._gl.RGB16UI;
  17846. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17847. return this._gl.RGBA16UI;
  17848. default:
  17849. return this._gl.RGBA16UI;
  17850. }
  17851. case Engine.TEXTURETYPE_INT:
  17852. switch (format) {
  17853. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17854. return this._gl.R32I;
  17855. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17856. return this._gl.RG32I;
  17857. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17858. return this._gl.RGB32I;
  17859. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17860. return this._gl.RGBA32I;
  17861. default:
  17862. return this._gl.RGBA32I;
  17863. }
  17864. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17865. switch (format) {
  17866. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17867. return this._gl.R32UI;
  17868. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17869. return this._gl.RG32UI;
  17870. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17871. return this._gl.RGB32UI;
  17872. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17873. return this._gl.RGBA32UI;
  17874. default:
  17875. return this._gl.RGBA32UI;
  17876. }
  17877. case Engine.TEXTURETYPE_FLOAT:
  17878. switch (format) {
  17879. case Engine.TEXTUREFORMAT_RED:
  17880. return this._gl.R32F; // By default. Other possibility is R16F.
  17881. case Engine.TEXTUREFORMAT_RG:
  17882. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17883. case Engine.TEXTUREFORMAT_RGB:
  17884. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17885. case Engine.TEXTUREFORMAT_RGBA:
  17886. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17887. default:
  17888. return this._gl.RGBA32F;
  17889. }
  17890. case Engine.TEXTURETYPE_HALF_FLOAT:
  17891. switch (format) {
  17892. case Engine.TEXTUREFORMAT_RED:
  17893. return this._gl.R16F;
  17894. case Engine.TEXTUREFORMAT_RG:
  17895. return this._gl.RG16F;
  17896. case Engine.TEXTUREFORMAT_RGB:
  17897. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17898. case Engine.TEXTUREFORMAT_RGBA:
  17899. return this._gl.RGBA16F;
  17900. default:
  17901. return this._gl.RGBA16F;
  17902. }
  17903. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17904. return this._gl.RGB565;
  17905. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17906. return this._gl.R11F_G11F_B10F;
  17907. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17908. return this._gl.RGB9_E5;
  17909. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17910. return this._gl.RGBA4;
  17911. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17912. return this._gl.RGB5_A1;
  17913. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17914. switch (format) {
  17915. case Engine.TEXTUREFORMAT_RGBA:
  17916. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17917. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17918. return this._gl.RGB10_A2UI;
  17919. default:
  17920. return this._gl.RGB10_A2;
  17921. }
  17922. }
  17923. return this._gl.RGBA8;
  17924. };
  17925. ;
  17926. /** @hidden */
  17927. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17928. if (type === Engine.TEXTURETYPE_FLOAT) {
  17929. return this._gl.RGBA32F;
  17930. }
  17931. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17932. return this._gl.RGBA16F;
  17933. }
  17934. return this._gl.RGBA8;
  17935. };
  17936. ;
  17937. /** @hidden */
  17938. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17939. var _this = this;
  17940. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17941. this._activeRequests.push(request);
  17942. request.onCompleteObservable.add(function (request) {
  17943. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17944. });
  17945. return request;
  17946. };
  17947. /** @hidden */
  17948. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17949. var _this = this;
  17950. return new Promise(function (resolve, reject) {
  17951. _this._loadFile(url, function (data) {
  17952. resolve(data);
  17953. }, undefined, database, useArrayBuffer, function (request, exception) {
  17954. reject(exception);
  17955. });
  17956. });
  17957. };
  17958. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17959. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17960. var onload = function (data) {
  17961. loadedFiles[index] = data;
  17962. loadedFiles._internalCount++;
  17963. if (loadedFiles._internalCount === 6) {
  17964. onfinish(loadedFiles);
  17965. }
  17966. };
  17967. var onerror = function (request, exception) {
  17968. if (onErrorCallBack && request) {
  17969. onErrorCallBack(request.status + " " + request.statusText, exception);
  17970. }
  17971. };
  17972. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17973. };
  17974. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17975. if (onError === void 0) { onError = null; }
  17976. var loadedFiles = [];
  17977. loadedFiles._internalCount = 0;
  17978. for (var index = 0; index < 6; index++) {
  17979. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17980. }
  17981. };
  17982. // Statics
  17983. /**
  17984. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17985. * @returns true if the engine can be created
  17986. * @ignorenaming
  17987. */
  17988. Engine.isSupported = function () {
  17989. try {
  17990. var tempcanvas = document.createElement("canvas");
  17991. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17992. return gl != null && !!window.WebGLRenderingContext;
  17993. }
  17994. catch (e) {
  17995. return false;
  17996. }
  17997. };
  17998. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17999. Engine.ExceptionList = [
  18000. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18001. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18002. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18003. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18004. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18005. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18006. ];
  18007. /** Gets the list of created engines */
  18008. Engine.Instances = new Array();
  18009. /**
  18010. * Hidden
  18011. */
  18012. Engine._TextureLoaders = [];
  18013. // Const statics
  18014. /** Defines that alpha blending is disabled */
  18015. Engine.ALPHA_DISABLE = 0;
  18016. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18017. Engine.ALPHA_ADD = 1;
  18018. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18019. Engine.ALPHA_COMBINE = 2;
  18020. /** Defines that alpha blending to DEST - SRC * DEST */
  18021. Engine.ALPHA_SUBTRACT = 3;
  18022. /** Defines that alpha blending to SRC * DEST */
  18023. Engine.ALPHA_MULTIPLY = 4;
  18024. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18025. Engine.ALPHA_MAXIMIZED = 5;
  18026. /** Defines that alpha blending to SRC + DEST */
  18027. Engine.ALPHA_ONEONE = 6;
  18028. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18029. Engine.ALPHA_PREMULTIPLIED = 7;
  18030. /**
  18031. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18032. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18033. */
  18034. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18035. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18036. Engine.ALPHA_INTERPOLATE = 9;
  18037. /**
  18038. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18039. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18040. */
  18041. Engine.ALPHA_SCREENMODE = 10;
  18042. /** Defines that the ressource is not delayed*/
  18043. Engine.DELAYLOADSTATE_NONE = 0;
  18044. /** Defines that the ressource was successfully delay loaded */
  18045. Engine.DELAYLOADSTATE_LOADED = 1;
  18046. /** Defines that the ressource is currently delay loading */
  18047. Engine.DELAYLOADSTATE_LOADING = 2;
  18048. /** Defines that the ressource is delayed and has not started loading */
  18049. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18050. // Depht or Stencil test Constants.
  18051. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18052. Engine.NEVER = 0x0200;
  18053. /** 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 */
  18054. Engine.ALWAYS = 0x0207;
  18055. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18056. Engine.LESS = 0x0201;
  18057. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18058. Engine.EQUAL = 0x0202;
  18059. /** 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 */
  18060. Engine.LEQUAL = 0x0203;
  18061. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18062. Engine.GREATER = 0x0204;
  18063. /** 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 */
  18064. Engine.GEQUAL = 0x0206;
  18065. /** 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 */
  18066. Engine.NOTEQUAL = 0x0205;
  18067. // Stencil Actions Constants.
  18068. /** Passed to stencilOperation to specify that stencil value must be kept */
  18069. Engine.KEEP = 0x1E00;
  18070. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18071. Engine.REPLACE = 0x1E01;
  18072. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18073. Engine.INCR = 0x1E02;
  18074. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18075. Engine.DECR = 0x1E03;
  18076. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18077. Engine.INVERT = 0x150A;
  18078. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18079. Engine.INCR_WRAP = 0x8507;
  18080. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18081. Engine.DECR_WRAP = 0x8508;
  18082. /** Texture is not repeating outside of 0..1 UVs */
  18083. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18084. /** Texture is repeating outside of 0..1 UVs */
  18085. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18086. /** Texture is repeating and mirrored */
  18087. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18088. /** ALPHA */
  18089. Engine.TEXTUREFORMAT_ALPHA = 0;
  18090. /** LUMINANCE */
  18091. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18092. /** LUMINANCE_ALPHA */
  18093. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18094. /** RGB */
  18095. Engine.TEXTUREFORMAT_RGB = 4;
  18096. /** RGBA */
  18097. Engine.TEXTUREFORMAT_RGBA = 5;
  18098. /** RED */
  18099. Engine.TEXTUREFORMAT_RED = 6;
  18100. /** RED (2nd reference) */
  18101. Engine.TEXTUREFORMAT_R = 6;
  18102. /** RG */
  18103. Engine.TEXTUREFORMAT_RG = 7;
  18104. /** RED_INTEGER */
  18105. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18106. /** RED_INTEGER (2nd reference) */
  18107. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18108. /** RG_INTEGER */
  18109. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18110. /** RGB_INTEGER */
  18111. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18112. /** RGBA_INTEGER */
  18113. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18114. /** UNSIGNED_BYTE */
  18115. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18116. /** UNSIGNED_BYTE (2nd reference) */
  18117. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18118. /** FLOAT */
  18119. Engine.TEXTURETYPE_FLOAT = 1;
  18120. /** HALF_FLOAT */
  18121. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18122. /** BYTE */
  18123. Engine.TEXTURETYPE_BYTE = 3;
  18124. /** SHORT */
  18125. Engine.TEXTURETYPE_SHORT = 4;
  18126. /** UNSIGNED_SHORT */
  18127. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18128. /** INT */
  18129. Engine.TEXTURETYPE_INT = 6;
  18130. /** UNSIGNED_INT */
  18131. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18132. /** UNSIGNED_SHORT_4_4_4_4 */
  18133. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18134. /** UNSIGNED_SHORT_5_5_5_1 */
  18135. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18136. /** UNSIGNED_SHORT_5_6_5 */
  18137. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18138. /** UNSIGNED_INT_2_10_10_10_REV */
  18139. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18140. /** UNSIGNED_INT_24_8 */
  18141. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18142. /** UNSIGNED_INT_10F_11F_11F_REV */
  18143. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18144. /** UNSIGNED_INT_5_9_9_9_REV */
  18145. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18146. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18147. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18148. /** nearest is mag = nearest and min = nearest and mip = linear */
  18149. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18150. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18151. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18152. /** Trilinear is mag = linear and min = linear and mip = linear */
  18153. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18154. /** nearest is mag = nearest and min = nearest and mip = linear */
  18155. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18156. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18157. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18158. /** Trilinear is mag = linear and min = linear and mip = linear */
  18159. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18160. /** mag = nearest and min = nearest and mip = nearest */
  18161. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18162. /** mag = nearest and min = linear and mip = nearest */
  18163. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18164. /** mag = nearest and min = linear and mip = linear */
  18165. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18166. /** mag = nearest and min = linear and mip = none */
  18167. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18168. /** mag = nearest and min = nearest and mip = none */
  18169. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18170. /** mag = linear and min = nearest and mip = nearest */
  18171. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18172. /** mag = linear and min = nearest and mip = linear */
  18173. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18174. /** mag = linear and min = linear and mip = none */
  18175. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18176. /** mag = linear and min = nearest and mip = none */
  18177. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18178. /** Explicit coordinates mode */
  18179. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18180. /** Spherical coordinates mode */
  18181. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18182. /** Planar coordinates mode */
  18183. Engine.TEXTURE_PLANAR_MODE = 2;
  18184. /** Cubic coordinates mode */
  18185. Engine.TEXTURE_CUBIC_MODE = 3;
  18186. /** Projection coordinates mode */
  18187. Engine.TEXTURE_PROJECTION_MODE = 4;
  18188. /** Skybox coordinates mode */
  18189. Engine.TEXTURE_SKYBOX_MODE = 5;
  18190. /** Inverse Cubic coordinates mode */
  18191. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18192. /** Equirectangular coordinates mode */
  18193. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18194. /** Equirectangular Fixed coordinates mode */
  18195. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18196. /** Equirectangular Fixed Mirrored coordinates mode */
  18197. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18198. // Texture rescaling mode
  18199. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18200. Engine.SCALEMODE_FLOOR = 1;
  18201. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18202. Engine.SCALEMODE_NEAREST = 2;
  18203. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18204. Engine.SCALEMODE_CEILING = 3;
  18205. // Updatable statics so stick with vars here
  18206. /**
  18207. * Gets or sets the epsilon value used by collision engine
  18208. */
  18209. Engine.CollisionsEpsilon = 0.001;
  18210. /**
  18211. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18212. */
  18213. Engine.CodeRepository = "src/";
  18214. /**
  18215. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18216. */
  18217. Engine.ShadersRepository = "src/Shaders/";
  18218. return Engine;
  18219. }());
  18220. BABYLON.Engine = Engine;
  18221. })(BABYLON || (BABYLON = {}));
  18222. //# sourceMappingURL=babylon.engine.js.map
  18223. var BABYLON;
  18224. (function (BABYLON) {
  18225. /**
  18226. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18227. */
  18228. var Node = /** @class */ (function () {
  18229. /**
  18230. * Creates a new Node
  18231. * @param {string} name - the name and id to be given to this node
  18232. * @param {BABYLON.Scene} the scene this node will be added to
  18233. */
  18234. function Node(name, scene) {
  18235. if (scene === void 0) { scene = null; }
  18236. /**
  18237. * Gets or sets a string used to store user defined state for the node
  18238. */
  18239. this.state = "";
  18240. /**
  18241. * Gets or sets an object used to store user defined information for the node
  18242. */
  18243. this.metadata = null;
  18244. /**
  18245. * Gets or sets a boolean used to define if the node must be serialized
  18246. */
  18247. this.doNotSerialize = false;
  18248. /** @hidden */
  18249. this._isDisposed = false;
  18250. /**
  18251. * Gets a list of Animations associated with the node
  18252. */
  18253. this.animations = new Array();
  18254. this._ranges = {};
  18255. this._isEnabled = true;
  18256. this._isParentEnabled = true;
  18257. this._isReady = true;
  18258. /** @hidden */
  18259. this._currentRenderId = -1;
  18260. this._parentRenderId = -1;
  18261. this._childRenderId = -1;
  18262. /** @hidden */
  18263. this._worldMatrix = BABYLON.Matrix.Identity();
  18264. /** @hidden */
  18265. this._worldMatrixDeterminant = 0;
  18266. /** @hidden */
  18267. this._sceneRootNodesIndex = -1;
  18268. this._animationPropertiesOverride = null;
  18269. /**
  18270. * An event triggered when the mesh is disposed
  18271. */
  18272. this.onDisposeObservable = new BABYLON.Observable();
  18273. // Behaviors
  18274. this._behaviors = new Array();
  18275. this.name = name;
  18276. this.id = name;
  18277. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18278. this.uniqueId = this._scene.getUniqueId();
  18279. this._initCache();
  18280. this.addToSceneRootNodes();
  18281. }
  18282. /**
  18283. * Add a new node constructor
  18284. * @param type defines the type name of the node to construct
  18285. * @param constructorFunc defines the constructor function
  18286. */
  18287. Node.AddNodeConstructor = function (type, constructorFunc) {
  18288. this._NodeConstructors[type] = constructorFunc;
  18289. };
  18290. /**
  18291. * Returns a node constructor based on type name
  18292. * @param type defines the type name
  18293. * @param name defines the new node name
  18294. * @param scene defines the hosting scene
  18295. * @param options defines optional options to transmit to constructors
  18296. * @returns the new constructor or null
  18297. */
  18298. Node.Construct = function (type, name, scene, options) {
  18299. var constructorFunc = this._NodeConstructors[type];
  18300. if (!constructorFunc) {
  18301. return null;
  18302. }
  18303. return constructorFunc(name, scene, options);
  18304. };
  18305. /**
  18306. * Gets a boolean indicating if the node has been disposed
  18307. * @returns true if the node was disposed
  18308. */
  18309. Node.prototype.isDisposed = function () {
  18310. return this._isDisposed;
  18311. };
  18312. Object.defineProperty(Node.prototype, "parent", {
  18313. get: function () {
  18314. return this._parentNode;
  18315. },
  18316. /**
  18317. * Gets or sets the parent of the node
  18318. */
  18319. set: function (parent) {
  18320. if (this._parentNode === parent) {
  18321. return;
  18322. }
  18323. var previousParentNode = this._parentNode;
  18324. // Remove self from list of children of parent
  18325. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18326. var index = this._parentNode._children.indexOf(this);
  18327. if (index !== -1) {
  18328. this._parentNode._children.splice(index, 1);
  18329. }
  18330. if (!parent) {
  18331. this.addToSceneRootNodes();
  18332. }
  18333. }
  18334. // Store new parent
  18335. this._parentNode = parent;
  18336. // Add as child to new parent
  18337. if (this._parentNode) {
  18338. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18339. this._parentNode._children = new Array();
  18340. }
  18341. this._parentNode._children.push(this);
  18342. if (!previousParentNode) {
  18343. this.removeFromSceneRootNodes();
  18344. }
  18345. }
  18346. // Enabled state
  18347. this._syncParentEnabledState();
  18348. },
  18349. enumerable: true,
  18350. configurable: true
  18351. });
  18352. Node.prototype.addToSceneRootNodes = function () {
  18353. if (this._sceneRootNodesIndex === -1) {
  18354. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18355. this._scene.rootNodes.push(this);
  18356. }
  18357. };
  18358. Node.prototype.removeFromSceneRootNodes = function () {
  18359. if (this._sceneRootNodesIndex !== -1) {
  18360. var rootNodes = this._scene.rootNodes;
  18361. var lastIdx = rootNodes.length - 1;
  18362. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18363. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18364. this._scene.rootNodes.pop();
  18365. this._sceneRootNodesIndex = -1;
  18366. }
  18367. };
  18368. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18369. /**
  18370. * Gets or sets the animation properties override
  18371. */
  18372. get: function () {
  18373. if (!this._animationPropertiesOverride) {
  18374. return this._scene.animationPropertiesOverride;
  18375. }
  18376. return this._animationPropertiesOverride;
  18377. },
  18378. set: function (value) {
  18379. this._animationPropertiesOverride = value;
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. /**
  18385. * Gets a string idenfifying the name of the class
  18386. * @returns "Node" string
  18387. */
  18388. Node.prototype.getClassName = function () {
  18389. return "Node";
  18390. };
  18391. Object.defineProperty(Node.prototype, "onDispose", {
  18392. /**
  18393. * Sets a callback that will be raised when the node will be disposed
  18394. */
  18395. set: function (callback) {
  18396. if (this._onDisposeObserver) {
  18397. this.onDisposeObservable.remove(this._onDisposeObserver);
  18398. }
  18399. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18400. },
  18401. enumerable: true,
  18402. configurable: true
  18403. });
  18404. /**
  18405. * Gets the scene of the node
  18406. * @returns a {BABYLON.Scene}
  18407. */
  18408. Node.prototype.getScene = function () {
  18409. return this._scene;
  18410. };
  18411. /**
  18412. * Gets the engine of the node
  18413. * @returns a {BABYLON.Engine}
  18414. */
  18415. Node.prototype.getEngine = function () {
  18416. return this._scene.getEngine();
  18417. };
  18418. /**
  18419. * Attach a behavior to the node
  18420. * @see http://doc.babylonjs.com/features/behaviour
  18421. * @param behavior defines the behavior to attach
  18422. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18423. * @returns the current Node
  18424. */
  18425. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18426. var _this = this;
  18427. if (attachImmediately === void 0) { attachImmediately = false; }
  18428. var index = this._behaviors.indexOf(behavior);
  18429. if (index !== -1) {
  18430. return this;
  18431. }
  18432. behavior.init();
  18433. if (this._scene.isLoading && !attachImmediately) {
  18434. // We defer the attach when the scene will be loaded
  18435. this._scene.onDataLoadedObservable.addOnce(function () {
  18436. behavior.attach(_this);
  18437. });
  18438. }
  18439. else {
  18440. behavior.attach(this);
  18441. }
  18442. this._behaviors.push(behavior);
  18443. return this;
  18444. };
  18445. /**
  18446. * Remove an attached behavior
  18447. * @see http://doc.babylonjs.com/features/behaviour
  18448. * @param behavior defines the behavior to attach
  18449. * @returns the current Node
  18450. */
  18451. Node.prototype.removeBehavior = function (behavior) {
  18452. var index = this._behaviors.indexOf(behavior);
  18453. if (index === -1) {
  18454. return this;
  18455. }
  18456. this._behaviors[index].detach();
  18457. this._behaviors.splice(index, 1);
  18458. return this;
  18459. };
  18460. Object.defineProperty(Node.prototype, "behaviors", {
  18461. /**
  18462. * Gets the list of attached behaviors
  18463. * @see http://doc.babylonjs.com/features/behaviour
  18464. */
  18465. get: function () {
  18466. return this._behaviors;
  18467. },
  18468. enumerable: true,
  18469. configurable: true
  18470. });
  18471. /**
  18472. * Gets an attached behavior by name
  18473. * @param name defines the name of the behavior to look for
  18474. * @see http://doc.babylonjs.com/features/behaviour
  18475. * @returns null if behavior was not found else the requested behavior
  18476. */
  18477. Node.prototype.getBehaviorByName = function (name) {
  18478. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18479. var behavior = _a[_i];
  18480. if (behavior.name === name) {
  18481. return behavior;
  18482. }
  18483. }
  18484. return null;
  18485. };
  18486. /**
  18487. * Returns the latest update of the World matrix
  18488. * @returns a Matrix
  18489. */
  18490. Node.prototype.getWorldMatrix = function () {
  18491. if (this._currentRenderId !== this._scene.getRenderId()) {
  18492. this.computeWorldMatrix();
  18493. }
  18494. return this._worldMatrix;
  18495. };
  18496. /** @hidden */
  18497. Node.prototype._getWorldMatrixDeterminant = function () {
  18498. return this._worldMatrixDeterminant;
  18499. };
  18500. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18501. /**
  18502. * Returns directly the latest state of the mesh World matrix.
  18503. * A Matrix is returned.
  18504. */
  18505. get: function () {
  18506. return this._worldMatrix;
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. // override it in derived class if you add new variables to the cache
  18512. // and call the parent class method
  18513. /** @hidden */
  18514. Node.prototype._initCache = function () {
  18515. this._cache = {};
  18516. this._cache.parent = undefined;
  18517. };
  18518. /** @hidden */
  18519. Node.prototype.updateCache = function (force) {
  18520. if (!force && this.isSynchronized())
  18521. return;
  18522. this._cache.parent = this.parent;
  18523. this._updateCache();
  18524. };
  18525. // override it in derived class if you add new variables to the cache
  18526. // and call the parent class method if !ignoreParentClass
  18527. /** @hidden */
  18528. Node.prototype._updateCache = function (ignoreParentClass) {
  18529. };
  18530. // override it in derived class if you add new variables to the cache
  18531. /** @hidden */
  18532. Node.prototype._isSynchronized = function () {
  18533. return true;
  18534. };
  18535. /** @hidden */
  18536. Node.prototype._markSyncedWithParent = function () {
  18537. if (this._parentNode) {
  18538. this._parentRenderId = this._parentNode._childRenderId;
  18539. }
  18540. };
  18541. /** @hidden */
  18542. Node.prototype.isSynchronizedWithParent = function () {
  18543. if (!this._parentNode) {
  18544. return true;
  18545. }
  18546. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18547. return false;
  18548. }
  18549. return this._parentNode.isSynchronized();
  18550. };
  18551. /** @hidden */
  18552. Node.prototype.isSynchronized = function () {
  18553. if (this._cache.parent != this._parentNode) {
  18554. this._cache.parent = this._parentNode;
  18555. return false;
  18556. }
  18557. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18558. return false;
  18559. }
  18560. return this._isSynchronized();
  18561. };
  18562. /**
  18563. * Is this node ready to be used/rendered
  18564. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18565. * @return true if the node is ready
  18566. */
  18567. Node.prototype.isReady = function (completeCheck) {
  18568. if (completeCheck === void 0) { completeCheck = false; }
  18569. return this._isReady;
  18570. };
  18571. /**
  18572. * Is this node enabled?
  18573. * 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
  18574. * @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
  18575. * @return whether this node (and its parent) is enabled
  18576. */
  18577. Node.prototype.isEnabled = function (checkAncestors) {
  18578. if (checkAncestors === void 0) { checkAncestors = true; }
  18579. if (checkAncestors === false) {
  18580. return this._isEnabled;
  18581. }
  18582. if (!this._isEnabled) {
  18583. return false;
  18584. }
  18585. return this._isParentEnabled;
  18586. };
  18587. /** @hidden */
  18588. Node.prototype._syncParentEnabledState = function () {
  18589. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18590. if (this._children) {
  18591. this._children.forEach(function (c) {
  18592. c._syncParentEnabledState(); // Force children to update accordingly
  18593. });
  18594. }
  18595. };
  18596. /**
  18597. * Set the enabled state of this node
  18598. * @param value defines the new enabled state
  18599. */
  18600. Node.prototype.setEnabled = function (value) {
  18601. this._isEnabled = value;
  18602. this._syncParentEnabledState();
  18603. };
  18604. /**
  18605. * Is this node a descendant of the given node?
  18606. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18607. * @param ancestor defines the parent node to inspect
  18608. * @returns a boolean indicating if this node is a descendant of the given node
  18609. */
  18610. Node.prototype.isDescendantOf = function (ancestor) {
  18611. if (this.parent) {
  18612. if (this.parent === ancestor) {
  18613. return true;
  18614. }
  18615. return this.parent.isDescendantOf(ancestor);
  18616. }
  18617. return false;
  18618. };
  18619. /** @hidden */
  18620. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18621. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18622. if (!this._children) {
  18623. return;
  18624. }
  18625. for (var index = 0; index < this._children.length; index++) {
  18626. var item = this._children[index];
  18627. if (!predicate || predicate(item)) {
  18628. results.push(item);
  18629. }
  18630. if (!directDescendantsOnly) {
  18631. item._getDescendants(results, false, predicate);
  18632. }
  18633. }
  18634. };
  18635. /**
  18636. * Will return all nodes that have this node as ascendant
  18637. * @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
  18638. * @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
  18639. * @return all children nodes of all types
  18640. */
  18641. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18642. var results = new Array();
  18643. this._getDescendants(results, directDescendantsOnly, predicate);
  18644. return results;
  18645. };
  18646. /**
  18647. * Get all child-meshes of this node
  18648. * @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
  18649. * @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
  18650. * @returns an array of {BABYLON.AbstractMesh}
  18651. */
  18652. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18653. var results = [];
  18654. this._getDescendants(results, directDescendantsOnly, function (node) {
  18655. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18656. });
  18657. return results;
  18658. };
  18659. /**
  18660. * Get all child-transformNodes of this node
  18661. * @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
  18662. * @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
  18663. * @returns an array of {BABYLON.TransformNode}
  18664. */
  18665. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18666. var results = [];
  18667. this._getDescendants(results, directDescendantsOnly, function (node) {
  18668. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18669. });
  18670. return results;
  18671. };
  18672. /**
  18673. * Get all direct children of this node
  18674. * @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
  18675. * @returns an array of {BABYLON.Node}
  18676. */
  18677. Node.prototype.getChildren = function (predicate) {
  18678. return this.getDescendants(true, predicate);
  18679. };
  18680. /** @hidden */
  18681. Node.prototype._setReady = function (state) {
  18682. if (state === this._isReady) {
  18683. return;
  18684. }
  18685. if (!state) {
  18686. this._isReady = false;
  18687. return;
  18688. }
  18689. if (this.onReady) {
  18690. this.onReady(this);
  18691. }
  18692. this._isReady = true;
  18693. };
  18694. /**
  18695. * Get an animation by name
  18696. * @param name defines the name of the animation to look for
  18697. * @returns null if not found else the requested animation
  18698. */
  18699. Node.prototype.getAnimationByName = function (name) {
  18700. for (var i = 0; i < this.animations.length; i++) {
  18701. var animation = this.animations[i];
  18702. if (animation.name === name) {
  18703. return animation;
  18704. }
  18705. }
  18706. return null;
  18707. };
  18708. /**
  18709. * Creates an animation range for this node
  18710. * @param name defines the name of the range
  18711. * @param from defines the starting key
  18712. * @param to defines the end key
  18713. */
  18714. Node.prototype.createAnimationRange = function (name, from, to) {
  18715. // check name not already in use
  18716. if (!this._ranges[name]) {
  18717. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18718. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18719. if (this.animations[i]) {
  18720. this.animations[i].createRange(name, from, to);
  18721. }
  18722. }
  18723. }
  18724. };
  18725. /**
  18726. * Delete a specific animation range
  18727. * @param name defines the name of the range to delete
  18728. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18729. */
  18730. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18731. if (deleteFrames === void 0) { deleteFrames = true; }
  18732. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18733. if (this.animations[i]) {
  18734. this.animations[i].deleteRange(name, deleteFrames);
  18735. }
  18736. }
  18737. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18738. };
  18739. /**
  18740. * Get an animation range by name
  18741. * @param name defines the name of the animation range to look for
  18742. * @returns null if not found else the requested animation range
  18743. */
  18744. Node.prototype.getAnimationRange = function (name) {
  18745. return this._ranges[name];
  18746. };
  18747. /**
  18748. * Will start the animation sequence
  18749. * @param name defines the range frames for animation sequence
  18750. * @param loop defines if the animation should loop (false by default)
  18751. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18752. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18753. * @returns the object created for this animation. If range does not exist, it will return null
  18754. */
  18755. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18756. var range = this.getAnimationRange(name);
  18757. if (!range) {
  18758. return null;
  18759. }
  18760. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18761. };
  18762. /**
  18763. * Serialize animation ranges into a JSON compatible object
  18764. * @returns serialization object
  18765. */
  18766. Node.prototype.serializeAnimationRanges = function () {
  18767. var serializationRanges = [];
  18768. for (var name in this._ranges) {
  18769. var localRange = this._ranges[name];
  18770. if (!localRange) {
  18771. continue;
  18772. }
  18773. var range = {};
  18774. range.name = name;
  18775. range.from = localRange.from;
  18776. range.to = localRange.to;
  18777. serializationRanges.push(range);
  18778. }
  18779. return serializationRanges;
  18780. };
  18781. /**
  18782. * Computes the world matrix of the node
  18783. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18784. * @returns the world matrix
  18785. */
  18786. Node.prototype.computeWorldMatrix = function (force) {
  18787. if (!this._worldMatrix) {
  18788. this._worldMatrix = BABYLON.Matrix.Identity();
  18789. }
  18790. return this._worldMatrix;
  18791. };
  18792. /**
  18793. * Releases resources associated with this node.
  18794. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18795. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18796. */
  18797. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18798. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18799. if (!doNotRecurse) {
  18800. var nodes = this.getDescendants(true);
  18801. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18802. var node = nodes_1[_i];
  18803. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18804. }
  18805. }
  18806. else {
  18807. var transformNodes = this.getChildTransformNodes(true);
  18808. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18809. var transformNode = transformNodes_1[_a];
  18810. transformNode.parent = null;
  18811. transformNode.computeWorldMatrix(true);
  18812. }
  18813. }
  18814. if (!this.parent) {
  18815. this.removeFromSceneRootNodes();
  18816. }
  18817. else {
  18818. this.parent = null;
  18819. }
  18820. // Callback
  18821. this.onDisposeObservable.notifyObservers(this);
  18822. this.onDisposeObservable.clear();
  18823. // Behaviors
  18824. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18825. var behavior = _c[_b];
  18826. behavior.detach();
  18827. }
  18828. this._behaviors = [];
  18829. this._isDisposed = true;
  18830. };
  18831. /**
  18832. * Parse animation range data from a serialization object and store them into a given node
  18833. * @param node defines where to store the animation ranges
  18834. * @param parsedNode defines the serialization object to read data from
  18835. * @param scene defines the hosting scene
  18836. */
  18837. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18838. if (parsedNode.ranges) {
  18839. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18840. var data = parsedNode.ranges[index];
  18841. node.createAnimationRange(data.name, data.from, data.to);
  18842. }
  18843. }
  18844. };
  18845. Node._NodeConstructors = {};
  18846. __decorate([
  18847. BABYLON.serialize()
  18848. ], Node.prototype, "name", void 0);
  18849. __decorate([
  18850. BABYLON.serialize()
  18851. ], Node.prototype, "id", void 0);
  18852. __decorate([
  18853. BABYLON.serialize()
  18854. ], Node.prototype, "uniqueId", void 0);
  18855. __decorate([
  18856. BABYLON.serialize()
  18857. ], Node.prototype, "state", void 0);
  18858. __decorate([
  18859. BABYLON.serialize()
  18860. ], Node.prototype, "metadata", void 0);
  18861. return Node;
  18862. }());
  18863. BABYLON.Node = Node;
  18864. })(BABYLON || (BABYLON = {}));
  18865. //# sourceMappingURL=babylon.node.js.map
  18866. var BABYLON;
  18867. (function (BABYLON) {
  18868. // This matrix is used as a value to reset the bounding box.
  18869. var _identityMatrix = BABYLON.Matrix.Identity();
  18870. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18871. /**
  18872. * Class used to store bounding sphere information
  18873. */
  18874. var BoundingSphere = /** @class */ (function () {
  18875. /**
  18876. * Creates a new bounding sphere
  18877. * @param min defines the minimum vector (in local space)
  18878. * @param max defines the maximum vector (in local space)
  18879. */
  18880. function BoundingSphere(min, max) {
  18881. this.center = BABYLON.Vector3.Zero();
  18882. this.centerWorld = BABYLON.Vector3.Zero();
  18883. this.reConstruct(min, max);
  18884. }
  18885. /**
  18886. * Recreates the entire bounding sphere from scratch
  18887. * @param min defines the new minimum vector (in local space)
  18888. * @param max defines the new maximum vector (in local space)
  18889. */
  18890. BoundingSphere.prototype.reConstruct = function (min, max) {
  18891. this.minimum = min.clone();
  18892. this.maximum = max.clone();
  18893. var distance = BABYLON.Vector3.Distance(min, max);
  18894. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18895. this.radius = distance * 0.5;
  18896. this.centerWorld.set(0, 0, 0);
  18897. this._update(_identityMatrix);
  18898. };
  18899. /**
  18900. * Scale the current bounding sphere by applying a scale factor
  18901. * @param factor defines the scale factor to apply
  18902. * @returns the current bounding box
  18903. */
  18904. BoundingSphere.prototype.scale = function (factor) {
  18905. var newRadius = this.radius * factor;
  18906. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18907. var min = this.center.subtract(_tempRadiusVector);
  18908. var max = this.center.add(_tempRadiusVector);
  18909. this.reConstruct(min, max);
  18910. return this;
  18911. };
  18912. // Methods
  18913. /** @hidden */
  18914. BoundingSphere.prototype._update = function (world) {
  18915. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18916. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18917. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18918. };
  18919. /**
  18920. * Tests if the bounding sphere is intersecting the frustum planes
  18921. * @param frustumPlanes defines the frustum planes to test
  18922. * @returns true if there is an intersection
  18923. */
  18924. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18925. for (var i = 0; i < 6; i++) {
  18926. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18927. return false;
  18928. }
  18929. return true;
  18930. };
  18931. /**
  18932. * Tests if a point is inside the bounding sphere
  18933. * @param point defines the point to test
  18934. * @returns true if the point is inside the bounding sphere
  18935. */
  18936. BoundingSphere.prototype.intersectsPoint = function (point) {
  18937. var x = this.centerWorld.x - point.x;
  18938. var y = this.centerWorld.y - point.y;
  18939. var z = this.centerWorld.z - point.z;
  18940. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18941. if (this.radiusWorld < distance)
  18942. return false;
  18943. return true;
  18944. };
  18945. // Statics
  18946. /**
  18947. * Checks if two sphere intersct
  18948. * @param sphere0 sphere 0
  18949. * @param sphere1 sphere 1
  18950. * @returns true if the speres intersect
  18951. */
  18952. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18953. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18954. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18955. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18956. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18957. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18958. return false;
  18959. return true;
  18960. };
  18961. return BoundingSphere;
  18962. }());
  18963. BABYLON.BoundingSphere = BoundingSphere;
  18964. })(BABYLON || (BABYLON = {}));
  18965. //# sourceMappingURL=babylon.boundingSphere.js.map
  18966. var BABYLON;
  18967. (function (BABYLON) {
  18968. /**
  18969. * Class used to store bounding box information
  18970. */
  18971. var BoundingBox = /** @class */ (function () {
  18972. /**
  18973. * Creates a new bounding box
  18974. * @param min defines the minimum vector (in local space)
  18975. * @param max defines the maximum vector (in local space)
  18976. */
  18977. function BoundingBox(min, max) {
  18978. /**
  18979. * Gets the 8 vectors representing the bounding box in world space
  18980. */
  18981. this.vectorsWorld = new Array();
  18982. this.reConstruct(min, max);
  18983. }
  18984. // Methods
  18985. /**
  18986. * Recreates the entire bounding box from scratch
  18987. * @param min defines the new minimum vector (in local space)
  18988. * @param max defines the new maximum vector (in local space)
  18989. */
  18990. BoundingBox.prototype.reConstruct = function (min, max) {
  18991. this.minimum = min.clone();
  18992. this.maximum = max.clone();
  18993. // Bounding vectors
  18994. this.vectors = [
  18995. this.minimum.clone(),
  18996. this.maximum.clone(),
  18997. this.minimum.clone(),
  18998. this.minimum.clone(),
  18999. this.minimum.clone(),
  19000. this.maximum.clone(),
  19001. this.maximum.clone(),
  19002. this.maximum.clone()
  19003. ];
  19004. this.vectors[2].x = this.maximum.x;
  19005. this.vectors[3].y = this.maximum.y;
  19006. this.vectors[4].z = this.maximum.z;
  19007. this.vectors[5].z = this.minimum.z;
  19008. this.vectors[6].x = this.minimum.x;
  19009. this.vectors[7].y = this.minimum.y;
  19010. // OBB
  19011. this.center = this.maximum.add(this.minimum).scale(0.5);
  19012. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  19013. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19014. // World
  19015. for (var index = 0; index < this.vectors.length; index++) {
  19016. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  19017. }
  19018. this.minimumWorld = BABYLON.Vector3.Zero();
  19019. this.maximumWorld = BABYLON.Vector3.Zero();
  19020. this.centerWorld = BABYLON.Vector3.Zero();
  19021. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19022. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19023. };
  19024. /**
  19025. * Scale the current bounding box by applying a scale factor
  19026. * @param factor defines the scale factor to apply
  19027. * @returns the current bounding box
  19028. */
  19029. BoundingBox.prototype.scale = function (factor) {
  19030. var diff = this.maximum.subtract(this.minimum);
  19031. var distance = diff.length() * factor;
  19032. diff.normalize();
  19033. var newRadius = diff.scale(distance / 2);
  19034. var min = this.center.subtract(newRadius);
  19035. var max = this.center.add(newRadius);
  19036. this.reConstruct(min, max);
  19037. return this;
  19038. };
  19039. /**
  19040. * Gets the world matrix of the bounding box
  19041. * @returns a matrix
  19042. */
  19043. BoundingBox.prototype.getWorldMatrix = function () {
  19044. return this._worldMatrix;
  19045. };
  19046. /**
  19047. * Sets the world matrix stored in the bounding box
  19048. * @param matrix defines the matrix to store
  19049. * @returns current bounding box
  19050. */
  19051. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19052. this._worldMatrix.copyFrom(matrix);
  19053. return this;
  19054. };
  19055. /** @hidden */
  19056. BoundingBox.prototype._update = function (world) {
  19057. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19058. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19059. for (var index = 0; index < this.vectors.length; index++) {
  19060. var v = this.vectorsWorld[index];
  19061. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19062. if (v.x < this.minimumWorld.x)
  19063. this.minimumWorld.x = v.x;
  19064. if (v.y < this.minimumWorld.y)
  19065. this.minimumWorld.y = v.y;
  19066. if (v.z < this.minimumWorld.z)
  19067. this.minimumWorld.z = v.z;
  19068. if (v.x > this.maximumWorld.x)
  19069. this.maximumWorld.x = v.x;
  19070. if (v.y > this.maximumWorld.y)
  19071. this.maximumWorld.y = v.y;
  19072. if (v.z > this.maximumWorld.z)
  19073. this.maximumWorld.z = v.z;
  19074. }
  19075. // Extend
  19076. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19077. this.extendSizeWorld.scaleInPlace(0.5);
  19078. // OBB
  19079. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19080. this.centerWorld.scaleInPlace(0.5);
  19081. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19082. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19083. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19084. this._worldMatrix = world;
  19085. };
  19086. /**
  19087. * Tests if the bounding box is intersecting the frustum planes
  19088. * @param frustumPlanes defines the frustum planes to test
  19089. * @returns true if there is an intersection
  19090. */
  19091. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19092. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19093. };
  19094. /**
  19095. * Tests if the bounding box is entirely inside the frustum planes
  19096. * @param frustumPlanes defines the frustum planes to test
  19097. * @returns true if there is an inclusion
  19098. */
  19099. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19100. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19101. };
  19102. /**
  19103. * Tests if a point is inside the bounding box
  19104. * @param point defines the point to test
  19105. * @returns true if the point is inside the bounding box
  19106. */
  19107. BoundingBox.prototype.intersectsPoint = function (point) {
  19108. var delta = -BABYLON.Epsilon;
  19109. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19110. return false;
  19111. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19112. return false;
  19113. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19114. return false;
  19115. return true;
  19116. };
  19117. /**
  19118. * Tests if the bounding box intersects with a bounding sphere
  19119. * @param sphere defines the sphere to test
  19120. * @returns true if there is an intersection
  19121. */
  19122. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19123. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19124. };
  19125. /**
  19126. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19127. * @param min defines the min vector to use
  19128. * @param max defines the max vector to use
  19129. * @returns true if there is an intersection
  19130. */
  19131. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19132. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19133. return false;
  19134. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19135. return false;
  19136. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19137. return false;
  19138. return true;
  19139. };
  19140. // Statics
  19141. /**
  19142. * Tests if two bounding boxes are intersections
  19143. * @param box0 defines the first box to test
  19144. * @param box1 defines the second box to test
  19145. * @returns true if there is an intersection
  19146. */
  19147. BoundingBox.Intersects = function (box0, box1) {
  19148. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19149. return false;
  19150. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19151. return false;
  19152. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19153. return false;
  19154. return true;
  19155. };
  19156. /**
  19157. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19158. * @param minPoint defines the minimum vector of the bounding box
  19159. * @param maxPoint defines the maximum vector of the bounding box
  19160. * @param sphereCenter defines the sphere center
  19161. * @param sphereRadius defines the sphere radius
  19162. * @returns true if there is an intersection
  19163. */
  19164. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19165. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19166. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19167. return (num <= (sphereRadius * sphereRadius));
  19168. };
  19169. /**
  19170. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19171. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19172. * @param frustumPlanes defines the frustum planes to test
  19173. * @return true if there is an inclusion
  19174. */
  19175. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19176. for (var p = 0; p < 6; p++) {
  19177. for (var i = 0; i < 8; i++) {
  19178. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19179. return false;
  19180. }
  19181. }
  19182. }
  19183. return true;
  19184. };
  19185. /**
  19186. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19187. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19188. * @param frustumPlanes defines the frustum planes to test
  19189. * @return true if there is an intersection
  19190. */
  19191. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19192. for (var p = 0; p < 6; p++) {
  19193. var inCount = 8;
  19194. for (var i = 0; i < 8; i++) {
  19195. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19196. --inCount;
  19197. }
  19198. else {
  19199. break;
  19200. }
  19201. }
  19202. if (inCount === 0)
  19203. return false;
  19204. }
  19205. return true;
  19206. };
  19207. return BoundingBox;
  19208. }());
  19209. BABYLON.BoundingBox = BoundingBox;
  19210. })(BABYLON || (BABYLON = {}));
  19211. //# sourceMappingURL=babylon.boundingBox.js.map
  19212. var BABYLON;
  19213. (function (BABYLON) {
  19214. var computeBoxExtents = function (axis, box) {
  19215. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19216. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19217. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19218. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19219. var r = r0 + r1 + r2;
  19220. return {
  19221. min: p - r,
  19222. max: p + r
  19223. };
  19224. };
  19225. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19226. var axisOverlap = function (axis, box0, box1) {
  19227. var result0 = computeBoxExtents(axis, box0);
  19228. var result1 = computeBoxExtents(axis, box1);
  19229. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19230. };
  19231. /**
  19232. * Info for a bounding data of a mesh
  19233. */
  19234. var BoundingInfo = /** @class */ (function () {
  19235. /**
  19236. * Constructs bounding info
  19237. * @param minimum min vector of the bounding box/sphere
  19238. * @param maximum max vector of the bounding box/sphere
  19239. */
  19240. function BoundingInfo(
  19241. /**
  19242. * min vector of the bounding box/sphere
  19243. */
  19244. minimum,
  19245. /**
  19246. * max vector of the bounding box/sphere
  19247. */
  19248. maximum) {
  19249. this.minimum = minimum;
  19250. this.maximum = maximum;
  19251. this._isLocked = false;
  19252. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19253. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19254. }
  19255. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19256. /**
  19257. * If the info is locked and won't be updated to avoid perf overhead
  19258. */
  19259. get: function () {
  19260. return this._isLocked;
  19261. },
  19262. set: function (value) {
  19263. this._isLocked = value;
  19264. },
  19265. enumerable: true,
  19266. configurable: true
  19267. });
  19268. // Methods
  19269. /**
  19270. * Updates the boudning sphere and box
  19271. * @param world world matrix to be used to update
  19272. */
  19273. BoundingInfo.prototype.update = function (world) {
  19274. if (this._isLocked) {
  19275. return;
  19276. }
  19277. this.boundingBox._update(world);
  19278. this.boundingSphere._update(world);
  19279. };
  19280. /**
  19281. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19282. * @param center New center of the bounding info
  19283. * @param extend New extend of the bounding info
  19284. * @returns the current bounding info
  19285. */
  19286. BoundingInfo.prototype.centerOn = function (center, extend) {
  19287. this.minimum = center.subtract(extend);
  19288. this.maximum = center.add(extend);
  19289. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  19290. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  19291. return this;
  19292. };
  19293. /**
  19294. * Scale the current bounding info by applying a scale factor
  19295. * @param factor defines the scale factor to apply
  19296. * @returns the current bounding info
  19297. */
  19298. BoundingInfo.prototype.scale = function (factor) {
  19299. this.boundingBox.scale(factor);
  19300. this.boundingSphere.scale(factor);
  19301. return this;
  19302. };
  19303. /**
  19304. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19305. * @param frustumPlanes defines the frustum to test
  19306. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19307. * @returns true if the bounding info is in the frustum planes
  19308. */
  19309. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19310. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19311. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19312. return false;
  19313. }
  19314. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19315. return true;
  19316. }
  19317. return this.boundingBox.isInFrustum(frustumPlanes);
  19318. };
  19319. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19320. /**
  19321. * Gets the world distance between the min and max points of the bounding box
  19322. */
  19323. get: function () {
  19324. var boundingBox = this.boundingBox;
  19325. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19326. return size.length();
  19327. },
  19328. enumerable: true,
  19329. configurable: true
  19330. });
  19331. /**
  19332. * Checks if a cullable object (mesh...) is in the camera frustum
  19333. * Unlike isInFrustum this cheks the full bounding box
  19334. * @param frustumPlanes Camera near/planes
  19335. * @returns true if the object is in frustum otherwise false
  19336. */
  19337. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19338. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19339. };
  19340. /** @hidden */
  19341. BoundingInfo.prototype._checkCollision = function (collider) {
  19342. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19343. };
  19344. /**
  19345. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19346. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19347. * @param point the point to check intersection with
  19348. * @returns if the point intersects
  19349. */
  19350. BoundingInfo.prototype.intersectsPoint = function (point) {
  19351. if (!this.boundingSphere.centerWorld) {
  19352. return false;
  19353. }
  19354. if (!this.boundingSphere.intersectsPoint(point)) {
  19355. return false;
  19356. }
  19357. if (!this.boundingBox.intersectsPoint(point)) {
  19358. return false;
  19359. }
  19360. return true;
  19361. };
  19362. /**
  19363. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19364. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19365. * @param boundingInfo the bounding info to check intersection with
  19366. * @param precise if the intersection should be done using OBB
  19367. * @returns if the bounding info intersects
  19368. */
  19369. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19370. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19371. return false;
  19372. }
  19373. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19374. return false;
  19375. }
  19376. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19377. return false;
  19378. }
  19379. if (!precise) {
  19380. return true;
  19381. }
  19382. var box0 = this.boundingBox;
  19383. var box1 = boundingInfo.boundingBox;
  19384. if (!axisOverlap(box0.directions[0], box0, box1))
  19385. return false;
  19386. if (!axisOverlap(box0.directions[1], box0, box1))
  19387. return false;
  19388. if (!axisOverlap(box0.directions[2], box0, box1))
  19389. return false;
  19390. if (!axisOverlap(box1.directions[0], box0, box1))
  19391. return false;
  19392. if (!axisOverlap(box1.directions[1], box0, box1))
  19393. return false;
  19394. if (!axisOverlap(box1.directions[2], box0, box1))
  19395. return false;
  19396. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19397. return false;
  19398. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19399. return false;
  19400. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19401. return false;
  19402. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19403. return false;
  19404. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19405. return false;
  19406. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19407. return false;
  19408. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19409. return false;
  19410. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19411. return false;
  19412. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19413. return false;
  19414. return true;
  19415. };
  19416. return BoundingInfo;
  19417. }());
  19418. BABYLON.BoundingInfo = BoundingInfo;
  19419. })(BABYLON || (BABYLON = {}));
  19420. //# sourceMappingURL=babylon.boundingInfo.js.map
  19421. var BABYLON;
  19422. (function (BABYLON) {
  19423. var TransformNode = /** @class */ (function (_super) {
  19424. __extends(TransformNode, _super);
  19425. function TransformNode(name, scene, isPure) {
  19426. if (scene === void 0) { scene = null; }
  19427. if (isPure === void 0) { isPure = true; }
  19428. var _this = _super.call(this, name, scene) || this;
  19429. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19430. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19431. _this._up = new BABYLON.Vector3(0, 1, 0);
  19432. _this._right = new BABYLON.Vector3(1, 0, 0);
  19433. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19434. // Properties
  19435. _this._position = BABYLON.Vector3.Zero();
  19436. _this._rotation = BABYLON.Vector3.Zero();
  19437. _this._scaling = BABYLON.Vector3.One();
  19438. _this._isDirty = false;
  19439. /**
  19440. * Set the billboard mode. Default is 0.
  19441. *
  19442. * | Value | Type | Description |
  19443. * | --- | --- | --- |
  19444. * | 0 | BILLBOARDMODE_NONE | |
  19445. * | 1 | BILLBOARDMODE_X | |
  19446. * | 2 | BILLBOARDMODE_Y | |
  19447. * | 4 | BILLBOARDMODE_Z | |
  19448. * | 7 | BILLBOARDMODE_ALL | |
  19449. *
  19450. */
  19451. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19452. _this.scalingDeterminant = 1;
  19453. _this.infiniteDistance = false;
  19454. /**
  19455. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19456. * By default the system will update normals to compensate
  19457. */
  19458. _this.ignoreNonUniformScaling = false;
  19459. _this._localWorld = BABYLON.Matrix.Zero();
  19460. _this._absolutePosition = BABYLON.Vector3.Zero();
  19461. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19462. _this._postMultiplyPivotMatrix = false;
  19463. _this._isWorldMatrixFrozen = false;
  19464. /**
  19465. * An event triggered after the world matrix is updated
  19466. */
  19467. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19468. _this._nonUniformScaling = false;
  19469. if (isPure) {
  19470. _this.getScene().addTransformNode(_this);
  19471. }
  19472. return _this;
  19473. }
  19474. /**
  19475. * Gets a string identifying the name of the class
  19476. * @returns "TransformNode" string
  19477. */
  19478. TransformNode.prototype.getClassName = function () {
  19479. return "TransformNode";
  19480. };
  19481. Object.defineProperty(TransformNode.prototype, "position", {
  19482. /**
  19483. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19484. */
  19485. get: function () {
  19486. return this._position;
  19487. },
  19488. set: function (newPosition) {
  19489. this._position = newPosition;
  19490. this._isDirty = true;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(TransformNode.prototype, "rotation", {
  19496. /**
  19497. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19498. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19499. */
  19500. get: function () {
  19501. return this._rotation;
  19502. },
  19503. set: function (newRotation) {
  19504. this._rotation = newRotation;
  19505. this._isDirty = true;
  19506. },
  19507. enumerable: true,
  19508. configurable: true
  19509. });
  19510. Object.defineProperty(TransformNode.prototype, "scaling", {
  19511. /**
  19512. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19513. */
  19514. get: function () {
  19515. return this._scaling;
  19516. },
  19517. set: function (newScaling) {
  19518. this._scaling = newScaling;
  19519. this._isDirty = true;
  19520. },
  19521. enumerable: true,
  19522. configurable: true
  19523. });
  19524. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19525. /**
  19526. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19527. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19528. */
  19529. get: function () {
  19530. return this._rotationQuaternion;
  19531. },
  19532. set: function (quaternion) {
  19533. this._rotationQuaternion = quaternion;
  19534. //reset the rotation vector.
  19535. if (quaternion && this.rotation.length()) {
  19536. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19537. }
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. Object.defineProperty(TransformNode.prototype, "forward", {
  19543. /**
  19544. * The forward direction of that transform in world space.
  19545. */
  19546. get: function () {
  19547. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Object.defineProperty(TransformNode.prototype, "up", {
  19553. /**
  19554. * The up direction of that transform in world space.
  19555. */
  19556. get: function () {
  19557. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. Object.defineProperty(TransformNode.prototype, "right", {
  19563. /**
  19564. * The right direction of that transform in world space.
  19565. */
  19566. get: function () {
  19567. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. /**
  19573. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19574. * Returns the TransformNode.
  19575. */
  19576. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19577. this._poseMatrix.copyFrom(matrix);
  19578. return this;
  19579. };
  19580. /**
  19581. * Returns the mesh Pose matrix.
  19582. * Returned object : Matrix
  19583. */
  19584. TransformNode.prototype.getPoseMatrix = function () {
  19585. return this._poseMatrix;
  19586. };
  19587. /** @hidden */
  19588. TransformNode.prototype._isSynchronized = function () {
  19589. if (this._isDirty) {
  19590. return false;
  19591. }
  19592. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19593. return false;
  19594. if (this._cache.pivotMatrixUpdated) {
  19595. return false;
  19596. }
  19597. if (this.infiniteDistance) {
  19598. return false;
  19599. }
  19600. if (!this._cache.position.equals(this._position))
  19601. return false;
  19602. if (this._rotationQuaternion) {
  19603. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19604. return false;
  19605. }
  19606. if (!this._cache.rotation.equals(this._rotation))
  19607. return false;
  19608. if (!this._cache.scaling.equals(this._scaling))
  19609. return false;
  19610. return true;
  19611. };
  19612. /** @hidden */
  19613. TransformNode.prototype._initCache = function () {
  19614. _super.prototype._initCache.call(this);
  19615. this._cache.localMatrixUpdated = false;
  19616. this._cache.position = BABYLON.Vector3.Zero();
  19617. this._cache.scaling = BABYLON.Vector3.Zero();
  19618. this._cache.rotation = BABYLON.Vector3.Zero();
  19619. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19620. this._cache.billboardMode = -1;
  19621. };
  19622. TransformNode.prototype.markAsDirty = function (property) {
  19623. if (property === "rotation") {
  19624. this.rotationQuaternion = null;
  19625. }
  19626. this._currentRenderId = Number.MAX_VALUE;
  19627. this._isDirty = true;
  19628. return this;
  19629. };
  19630. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19631. /**
  19632. * Returns the current mesh absolute position.
  19633. * Returns a Vector3.
  19634. */
  19635. get: function () {
  19636. return this._absolutePosition;
  19637. },
  19638. enumerable: true,
  19639. configurable: true
  19640. });
  19641. /**
  19642. * Sets a new matrix to apply before all other transformation
  19643. * @param matrix defines the transform matrix
  19644. * @returns the current TransformNode
  19645. */
  19646. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19647. return this.setPivotMatrix(matrix, false);
  19648. };
  19649. /**
  19650. * Sets a new pivot matrix to the current node
  19651. * @param matrix defines the new pivot matrix to use
  19652. * @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
  19653. * @returns the current TransformNode
  19654. */
  19655. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19656. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19657. this._pivotMatrix = matrix.clone();
  19658. this._cache.pivotMatrixUpdated = true;
  19659. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19660. if (this._postMultiplyPivotMatrix) {
  19661. if (!this._pivotMatrixInverse) {
  19662. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19663. }
  19664. else {
  19665. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19666. }
  19667. }
  19668. return this;
  19669. };
  19670. /**
  19671. * Returns the mesh pivot matrix.
  19672. * Default : Identity.
  19673. * A Matrix is returned.
  19674. */
  19675. TransformNode.prototype.getPivotMatrix = function () {
  19676. return this._pivotMatrix;
  19677. };
  19678. /**
  19679. * Prevents the World matrix to be computed any longer.
  19680. * Returns the TransformNode.
  19681. */
  19682. TransformNode.prototype.freezeWorldMatrix = function () {
  19683. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19684. this.computeWorldMatrix(true);
  19685. this._isWorldMatrixFrozen = true;
  19686. return this;
  19687. };
  19688. /**
  19689. * Allows back the World matrix computation.
  19690. * Returns the TransformNode.
  19691. */
  19692. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19693. this._isWorldMatrixFrozen = false;
  19694. this.computeWorldMatrix(true);
  19695. return this;
  19696. };
  19697. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19698. /**
  19699. * True if the World matrix has been frozen.
  19700. * Returns a boolean.
  19701. */
  19702. get: function () {
  19703. return this._isWorldMatrixFrozen;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. /**
  19709. * Retuns the mesh absolute position in the World.
  19710. * Returns a Vector3.
  19711. */
  19712. TransformNode.prototype.getAbsolutePosition = function () {
  19713. this.computeWorldMatrix();
  19714. return this._absolutePosition;
  19715. };
  19716. /**
  19717. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19718. * Returns the TransformNode.
  19719. */
  19720. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19721. if (!absolutePosition) {
  19722. return this;
  19723. }
  19724. var absolutePositionX;
  19725. var absolutePositionY;
  19726. var absolutePositionZ;
  19727. if (absolutePosition.x === undefined) {
  19728. if (arguments.length < 3) {
  19729. return this;
  19730. }
  19731. absolutePositionX = arguments[0];
  19732. absolutePositionY = arguments[1];
  19733. absolutePositionZ = arguments[2];
  19734. }
  19735. else {
  19736. absolutePositionX = absolutePosition.x;
  19737. absolutePositionY = absolutePosition.y;
  19738. absolutePositionZ = absolutePosition.z;
  19739. }
  19740. if (this.parent) {
  19741. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19742. invertParentWorldMatrix.invert();
  19743. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19744. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19745. }
  19746. else {
  19747. this.position.x = absolutePositionX;
  19748. this.position.y = absolutePositionY;
  19749. this.position.z = absolutePositionZ;
  19750. }
  19751. return this;
  19752. };
  19753. /**
  19754. * Sets the mesh position in its local space.
  19755. * Returns the TransformNode.
  19756. */
  19757. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19758. this.computeWorldMatrix();
  19759. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19760. return this;
  19761. };
  19762. /**
  19763. * Returns the mesh position in the local space from the current World matrix values.
  19764. * Returns a new Vector3.
  19765. */
  19766. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19767. this.computeWorldMatrix();
  19768. var invLocalWorldMatrix = this._localWorld.clone();
  19769. invLocalWorldMatrix.invert();
  19770. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19771. };
  19772. /**
  19773. * Translates the mesh along the passed Vector3 in its local space.
  19774. * Returns the TransformNode.
  19775. */
  19776. TransformNode.prototype.locallyTranslate = function (vector3) {
  19777. this.computeWorldMatrix(true);
  19778. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19779. return this;
  19780. };
  19781. /**
  19782. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19783. * @param targetPoint the position (must be in same space as current mesh) to look at
  19784. * @param yawCor optional yaw (y-axis) correction in radians
  19785. * @param pitchCor optional pitch (x-axis) correction in radians
  19786. * @param rollCor optional roll (z-axis) correction in radians
  19787. * @param space the choosen space of the target
  19788. * @returns the TransformNode.
  19789. */
  19790. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19791. if (yawCor === void 0) { yawCor = 0; }
  19792. if (pitchCor === void 0) { pitchCor = 0; }
  19793. if (rollCor === void 0) { rollCor = 0; }
  19794. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19795. var dv = TransformNode._lookAtVectorCache;
  19796. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19797. targetPoint.subtractToRef(pos, dv);
  19798. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19799. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19800. var pitch = Math.atan2(dv.y, len);
  19801. if (this.rotationQuaternion) {
  19802. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19803. }
  19804. else {
  19805. this.rotation.x = pitch + pitchCor;
  19806. this.rotation.y = yaw + yawCor;
  19807. this.rotation.z = rollCor;
  19808. }
  19809. return this;
  19810. };
  19811. /**
  19812. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19813. * This Vector3 is expressed in the World space.
  19814. */
  19815. TransformNode.prototype.getDirection = function (localAxis) {
  19816. var result = BABYLON.Vector3.Zero();
  19817. this.getDirectionToRef(localAxis, result);
  19818. return result;
  19819. };
  19820. /**
  19821. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19822. * localAxis is expressed in the mesh local space.
  19823. * result is computed in the Wordl space from the mesh World matrix.
  19824. * Returns the TransformNode.
  19825. */
  19826. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19827. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19828. return this;
  19829. };
  19830. /**
  19831. * Sets a new pivot point to the current node
  19832. * @param point defines the new pivot point to use
  19833. * @param space defines if the point is in world or local space (local by default)
  19834. * @returns the current TransformNode
  19835. */
  19836. TransformNode.prototype.setPivotPoint = function (point, space) {
  19837. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19838. if (this.getScene().getRenderId() == 0) {
  19839. this.computeWorldMatrix(true);
  19840. }
  19841. var wm = this.getWorldMatrix();
  19842. if (space == BABYLON.Space.WORLD) {
  19843. var tmat = BABYLON.Tmp.Matrix[0];
  19844. wm.invertToRef(tmat);
  19845. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19846. }
  19847. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19848. };
  19849. /**
  19850. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19851. */
  19852. TransformNode.prototype.getPivotPoint = function () {
  19853. var point = BABYLON.Vector3.Zero();
  19854. this.getPivotPointToRef(point);
  19855. return point;
  19856. };
  19857. /**
  19858. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19859. * Returns the TransformNode.
  19860. */
  19861. TransformNode.prototype.getPivotPointToRef = function (result) {
  19862. result.x = -this._pivotMatrix.m[12];
  19863. result.y = -this._pivotMatrix.m[13];
  19864. result.z = -this._pivotMatrix.m[14];
  19865. return this;
  19866. };
  19867. /**
  19868. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19869. */
  19870. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19871. var point = BABYLON.Vector3.Zero();
  19872. this.getAbsolutePivotPointToRef(point);
  19873. return point;
  19874. };
  19875. /**
  19876. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19877. * Returns the TransformNode.
  19878. */
  19879. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19880. result.x = this._pivotMatrix.m[12];
  19881. result.y = this._pivotMatrix.m[13];
  19882. result.z = this._pivotMatrix.m[14];
  19883. this.getPivotPointToRef(result);
  19884. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19885. return this;
  19886. };
  19887. /**
  19888. * Defines the passed node as the parent of the current node.
  19889. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19890. * Returns the TransformNode.
  19891. */
  19892. TransformNode.prototype.setParent = function (node) {
  19893. if (!node && !this.parent) {
  19894. return this;
  19895. }
  19896. if (!node) {
  19897. var rotation = BABYLON.Tmp.Quaternion[0];
  19898. var position = BABYLON.Tmp.Vector3[0];
  19899. var scale = BABYLON.Tmp.Vector3[1];
  19900. if (this.parent && this.parent.computeWorldMatrix) {
  19901. this.parent.computeWorldMatrix(true);
  19902. }
  19903. this.computeWorldMatrix(true);
  19904. this.getWorldMatrix().decompose(scale, rotation, position);
  19905. if (this.rotationQuaternion) {
  19906. this.rotationQuaternion.copyFrom(rotation);
  19907. }
  19908. else {
  19909. rotation.toEulerAnglesToRef(this.rotation);
  19910. }
  19911. this.scaling.x = scale.x;
  19912. this.scaling.y = scale.y;
  19913. this.scaling.z = scale.z;
  19914. this.position.x = position.x;
  19915. this.position.y = position.y;
  19916. this.position.z = position.z;
  19917. }
  19918. else {
  19919. var rotation = BABYLON.Tmp.Quaternion[0];
  19920. var position = BABYLON.Tmp.Vector3[0];
  19921. var scale = BABYLON.Tmp.Vector3[1];
  19922. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19923. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19924. this.computeWorldMatrix(true);
  19925. node.computeWorldMatrix(true);
  19926. node.getWorldMatrix().invertToRef(invParentMatrix);
  19927. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19928. diffMatrix.decompose(scale, rotation, position);
  19929. if (this.rotationQuaternion) {
  19930. this.rotationQuaternion.copyFrom(rotation);
  19931. }
  19932. else {
  19933. rotation.toEulerAnglesToRef(this.rotation);
  19934. }
  19935. this.position.x = position.x;
  19936. this.position.y = position.y;
  19937. this.position.z = position.z;
  19938. this.scaling.x = scale.x;
  19939. this.scaling.y = scale.y;
  19940. this.scaling.z = scale.z;
  19941. }
  19942. this.parent = node;
  19943. return this;
  19944. };
  19945. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19946. get: function () {
  19947. return this._nonUniformScaling;
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. /** @hidden */
  19953. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19954. if (this._nonUniformScaling === value) {
  19955. return false;
  19956. }
  19957. this._nonUniformScaling = value;
  19958. return true;
  19959. };
  19960. /**
  19961. * Attach the current TransformNode to another TransformNode associated with a bone
  19962. * @param bone Bone affecting the TransformNode
  19963. * @param affectedTransformNode TransformNode associated with the bone
  19964. */
  19965. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19966. this._transformToBoneReferal = affectedTransformNode;
  19967. this.parent = bone;
  19968. if (bone.getWorldMatrix().determinant() < 0) {
  19969. this.scalingDeterminant *= -1;
  19970. }
  19971. return this;
  19972. };
  19973. TransformNode.prototype.detachFromBone = function () {
  19974. if (!this.parent) {
  19975. return this;
  19976. }
  19977. if (this.parent.getWorldMatrix().determinant() < 0) {
  19978. this.scalingDeterminant *= -1;
  19979. }
  19980. this._transformToBoneReferal = null;
  19981. this.parent = null;
  19982. return this;
  19983. };
  19984. /**
  19985. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19986. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19987. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19988. * The passed axis is also normalized.
  19989. * Returns the TransformNode.
  19990. */
  19991. TransformNode.prototype.rotate = function (axis, amount, space) {
  19992. axis.normalize();
  19993. if (!this.rotationQuaternion) {
  19994. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19995. this.rotation = BABYLON.Vector3.Zero();
  19996. }
  19997. var rotationQuaternion;
  19998. if (!space || space === BABYLON.Space.LOCAL) {
  19999. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20000. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20001. }
  20002. else {
  20003. if (this.parent) {
  20004. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20005. invertParentWorldMatrix.invert();
  20006. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20007. }
  20008. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20009. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20010. }
  20011. return this;
  20012. };
  20013. /**
  20014. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20015. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20016. * The passed axis is also normalized.
  20017. * Returns the TransformNode.
  20018. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20019. */
  20020. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20021. axis.normalize();
  20022. if (!this.rotationQuaternion) {
  20023. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20024. this.rotation.copyFromFloats(0, 0, 0);
  20025. }
  20026. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20027. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20028. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20029. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20030. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20031. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20032. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20033. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20034. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20035. return this;
  20036. };
  20037. /**
  20038. * Translates the mesh along the axis vector for the passed distance in the given space.
  20039. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20040. * Returns the TransformNode.
  20041. */
  20042. TransformNode.prototype.translate = function (axis, distance, space) {
  20043. var displacementVector = axis.scale(distance);
  20044. if (!space || space === BABYLON.Space.LOCAL) {
  20045. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20046. this.setPositionWithLocalVector(tempV3);
  20047. }
  20048. else {
  20049. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20050. }
  20051. return this;
  20052. };
  20053. /**
  20054. * Adds a rotation step to the mesh current rotation.
  20055. * x, y, z are Euler angles expressed in radians.
  20056. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20057. * This means this rotation is made in the mesh local space only.
  20058. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20059. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20060. * ```javascript
  20061. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20062. * ```
  20063. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20064. * 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.
  20065. * Returns the TransformNode.
  20066. */
  20067. TransformNode.prototype.addRotation = function (x, y, z) {
  20068. var rotationQuaternion;
  20069. if (this.rotationQuaternion) {
  20070. rotationQuaternion = this.rotationQuaternion;
  20071. }
  20072. else {
  20073. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20074. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20075. }
  20076. var accumulation = BABYLON.Tmp.Quaternion[0];
  20077. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20078. rotationQuaternion.multiplyInPlace(accumulation);
  20079. if (!this.rotationQuaternion) {
  20080. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20081. }
  20082. return this;
  20083. };
  20084. /**
  20085. * Computes the world matrix of the node
  20086. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20087. * @returns the world matrix
  20088. */
  20089. TransformNode.prototype.computeWorldMatrix = function (force) {
  20090. if (this._isWorldMatrixFrozen) {
  20091. return this._worldMatrix;
  20092. }
  20093. if (!force && this.isSynchronized()) {
  20094. this._currentRenderId = this.getScene().getRenderId();
  20095. return this._worldMatrix;
  20096. }
  20097. this._updateCache();
  20098. this._cache.position.copyFrom(this.position);
  20099. this._cache.scaling.copyFrom(this.scaling);
  20100. this._cache.pivotMatrixUpdated = false;
  20101. this._cache.billboardMode = this.billboardMode;
  20102. this._currentRenderId = this.getScene().getRenderId();
  20103. this._childRenderId = this.getScene().getRenderId();
  20104. this._isDirty = false;
  20105. // Scaling
  20106. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20107. // Rotation
  20108. //rotate, if quaternion is set and rotation was used
  20109. if (this.rotationQuaternion) {
  20110. var len = this.rotation.length();
  20111. if (len) {
  20112. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20113. this.rotation.copyFromFloats(0, 0, 0);
  20114. }
  20115. }
  20116. if (this.rotationQuaternion) {
  20117. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20118. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20119. }
  20120. else {
  20121. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20122. this._cache.rotation.copyFrom(this.rotation);
  20123. }
  20124. // Translation
  20125. var camera = this.getScene().activeCamera;
  20126. if (this.infiniteDistance && !this.parent && camera) {
  20127. var cameraWorldMatrix = camera.getWorldMatrix();
  20128. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20129. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20130. }
  20131. else {
  20132. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20133. }
  20134. // Composing transformations
  20135. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20136. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20137. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20138. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20139. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20140. // Need to decompose each rotation here
  20141. var currentPosition = BABYLON.Tmp.Vector3[3];
  20142. if (this.parent && this.parent.getWorldMatrix) {
  20143. if (this._transformToBoneReferal) {
  20144. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20145. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20146. }
  20147. else {
  20148. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20149. }
  20150. }
  20151. else {
  20152. currentPosition.copyFrom(this.position);
  20153. }
  20154. currentPosition.subtractInPlace(camera.globalPosition);
  20155. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20156. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20157. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20158. }
  20159. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20160. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20161. }
  20162. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20163. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20164. }
  20165. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20166. }
  20167. else {
  20168. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20169. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20170. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20171. }
  20172. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20173. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20174. }
  20175. // Post multiply inverse of pivotMatrix
  20176. if (this._postMultiplyPivotMatrix) {
  20177. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20178. }
  20179. // Local world
  20180. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20181. // Parent
  20182. if (this.parent && this.parent.getWorldMatrix) {
  20183. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20184. if (this._transformToBoneReferal) {
  20185. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20186. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20187. }
  20188. else {
  20189. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20190. }
  20191. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20192. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20193. this._worldMatrix.copyFrom(this._localWorld);
  20194. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20195. }
  20196. else {
  20197. if (this._transformToBoneReferal) {
  20198. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20199. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20200. }
  20201. else {
  20202. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20203. }
  20204. }
  20205. this._markSyncedWithParent();
  20206. }
  20207. else {
  20208. this._worldMatrix.copyFrom(this._localWorld);
  20209. }
  20210. // Normal matrix
  20211. if (!this.ignoreNonUniformScaling) {
  20212. if (this.scaling.isNonUniform) {
  20213. this._updateNonUniformScalingState(true);
  20214. }
  20215. else if (this.parent && this.parent._nonUniformScaling) {
  20216. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20217. }
  20218. else {
  20219. this._updateNonUniformScalingState(false);
  20220. }
  20221. }
  20222. else {
  20223. this._updateNonUniformScalingState(false);
  20224. }
  20225. this._afterComputeWorldMatrix();
  20226. // Absolute position
  20227. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20228. // Callbacks
  20229. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20230. if (!this._poseMatrix) {
  20231. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20232. }
  20233. // Cache the determinant
  20234. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20235. return this._worldMatrix;
  20236. };
  20237. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20238. };
  20239. /**
  20240. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20241. * @param func: callback function to add
  20242. *
  20243. * Returns the TransformNode.
  20244. */
  20245. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20246. this.onAfterWorldMatrixUpdateObservable.add(func);
  20247. return this;
  20248. };
  20249. /**
  20250. * Removes a registered callback function.
  20251. * Returns the TransformNode.
  20252. */
  20253. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20254. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20255. return this;
  20256. };
  20257. /**
  20258. * Clone the current transform node
  20259. * Returns the new transform node
  20260. * @param name Name of the new clone
  20261. * @param newParent New parent for the clone
  20262. * @param doNotCloneChildren Do not clone children hierarchy
  20263. */
  20264. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20265. var _this = this;
  20266. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20267. result.name = name;
  20268. result.id = name;
  20269. if (newParent) {
  20270. result.parent = newParent;
  20271. }
  20272. if (!doNotCloneChildren) {
  20273. // Children
  20274. var directDescendants = this.getDescendants(true);
  20275. for (var index = 0; index < directDescendants.length; index++) {
  20276. var child = directDescendants[index];
  20277. if (child.clone) {
  20278. child.clone(name + "." + child.name, result);
  20279. }
  20280. }
  20281. }
  20282. return result;
  20283. };
  20284. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20285. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20286. serializationObject.type = this.getClassName();
  20287. // Parent
  20288. if (this.parent) {
  20289. serializationObject.parentId = this.parent.id;
  20290. }
  20291. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20292. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20293. }
  20294. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20295. serializationObject.isEnabled = this.isEnabled();
  20296. // Parent
  20297. if (this.parent) {
  20298. serializationObject.parentId = this.parent.id;
  20299. }
  20300. return serializationObject;
  20301. };
  20302. // Statics
  20303. /**
  20304. * Returns a new TransformNode object parsed from the source provided.
  20305. * The parameter `parsedMesh` is the source.
  20306. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20307. */
  20308. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20309. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20310. if (BABYLON.Tags) {
  20311. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20312. }
  20313. if (parsedTransformNode.localMatrix) {
  20314. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20315. }
  20316. else if (parsedTransformNode.pivotMatrix) {
  20317. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20318. }
  20319. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20320. // Parent
  20321. if (parsedTransformNode.parentId) {
  20322. transformNode._waitingParentId = parsedTransformNode.parentId;
  20323. }
  20324. return transformNode;
  20325. };
  20326. /**
  20327. * Releases resources associated with this transform node.
  20328. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20329. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20330. */
  20331. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20332. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20333. // Animations
  20334. this.getScene().stopAnimation(this);
  20335. // Remove from scene
  20336. this.getScene().removeTransformNode(this);
  20337. this.onAfterWorldMatrixUpdateObservable.clear();
  20338. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20339. };
  20340. // Statics
  20341. TransformNode.BILLBOARDMODE_NONE = 0;
  20342. TransformNode.BILLBOARDMODE_X = 1;
  20343. TransformNode.BILLBOARDMODE_Y = 2;
  20344. TransformNode.BILLBOARDMODE_Z = 4;
  20345. TransformNode.BILLBOARDMODE_ALL = 7;
  20346. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20347. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20348. __decorate([
  20349. BABYLON.serializeAsVector3("position")
  20350. ], TransformNode.prototype, "_position", void 0);
  20351. __decorate([
  20352. BABYLON.serializeAsVector3("rotation")
  20353. ], TransformNode.prototype, "_rotation", void 0);
  20354. __decorate([
  20355. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20356. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20357. __decorate([
  20358. BABYLON.serializeAsVector3("scaling")
  20359. ], TransformNode.prototype, "_scaling", void 0);
  20360. __decorate([
  20361. BABYLON.serialize()
  20362. ], TransformNode.prototype, "billboardMode", void 0);
  20363. __decorate([
  20364. BABYLON.serialize()
  20365. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20366. __decorate([
  20367. BABYLON.serialize()
  20368. ], TransformNode.prototype, "infiniteDistance", void 0);
  20369. __decorate([
  20370. BABYLON.serialize()
  20371. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20372. return TransformNode;
  20373. }(BABYLON.Node));
  20374. BABYLON.TransformNode = TransformNode;
  20375. })(BABYLON || (BABYLON = {}));
  20376. //# sourceMappingURL=babylon.transformNode.js.map
  20377. var BABYLON;
  20378. (function (BABYLON) {
  20379. /** @hidden */
  20380. var _FacetDataStorage = /** @class */ (function () {
  20381. function _FacetDataStorage() {
  20382. this.facetNb = 0; // facet number
  20383. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20384. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20385. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20386. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20387. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20388. this.subDiv = {
  20389. max: 1,
  20390. X: 1,
  20391. Y: 1,
  20392. Z: 1
  20393. };
  20394. this.facetDepthSort = false; // is the facet depth sort to be computed
  20395. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20396. }
  20397. return _FacetDataStorage;
  20398. }());
  20399. /**
  20400. * Class used to store all common mesh properties
  20401. */
  20402. var AbstractMesh = /** @class */ (function (_super) {
  20403. __extends(AbstractMesh, _super);
  20404. // Constructor
  20405. /**
  20406. * Creates a new AbstractMesh
  20407. * @param name defines the name of the mesh
  20408. * @param scene defines the hosting scene
  20409. */
  20410. function AbstractMesh(name, scene) {
  20411. if (scene === void 0) { scene = null; }
  20412. var _this = _super.call(this, name, scene, false) || this;
  20413. _this._facetData = new _FacetDataStorage();
  20414. /** Gets ot sets the culling strategy to use to find visible meshes */
  20415. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20416. // Events
  20417. /**
  20418. * An event triggered when this mesh collides with another one
  20419. */
  20420. _this.onCollideObservable = new BABYLON.Observable();
  20421. /**
  20422. * An event triggered when the collision's position changes
  20423. */
  20424. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20425. /**
  20426. * An event triggered when material is changed
  20427. */
  20428. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20429. // Properties
  20430. /**
  20431. * Gets or sets the orientation for POV movement & rotation
  20432. */
  20433. _this.definedFacingForward = true;
  20434. _this._visibility = 1.0;
  20435. /** Gets or sets the alpha index used to sort transparent meshes
  20436. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20437. */
  20438. _this.alphaIndex = Number.MAX_VALUE;
  20439. /**
  20440. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20441. */
  20442. _this.isVisible = true;
  20443. /**
  20444. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20445. */
  20446. _this.isPickable = true;
  20447. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20448. _this.showSubMeshesBoundingBox = false;
  20449. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20450. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20451. */
  20452. _this.isBlocker = false;
  20453. /**
  20454. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20455. */
  20456. _this.enablePointerMoveEvents = false;
  20457. /**
  20458. * Specifies the rendering group id for this mesh (0 by default)
  20459. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20460. */
  20461. _this.renderingGroupId = 0;
  20462. _this._receiveShadows = false;
  20463. /** Defines color to use when rendering outline */
  20464. _this.outlineColor = BABYLON.Color3.Red();
  20465. /** Define width to use when rendering outline */
  20466. _this.outlineWidth = 0.02;
  20467. /** Defines color to use when rendering overlay */
  20468. _this.overlayColor = BABYLON.Color3.Red();
  20469. /** Defines alpha to use when rendering overlay */
  20470. _this.overlayAlpha = 0.5;
  20471. _this._hasVertexAlpha = false;
  20472. _this._useVertexColors = true;
  20473. _this._computeBonesUsingShaders = true;
  20474. _this._numBoneInfluencers = 4;
  20475. _this._applyFog = true;
  20476. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20477. _this.useOctreeForRenderingSelection = true;
  20478. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20479. _this.useOctreeForPicking = true;
  20480. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20481. _this.useOctreeForCollisions = true;
  20482. _this._layerMask = 0x0FFFFFFF;
  20483. /**
  20484. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20485. */
  20486. _this.alwaysSelectAsActiveMesh = false;
  20487. /**
  20488. * Gets or sets the current action manager
  20489. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20490. */
  20491. _this.actionManager = null;
  20492. // Collisions
  20493. _this._checkCollisions = false;
  20494. _this._collisionMask = -1;
  20495. _this._collisionGroup = -1;
  20496. /**
  20497. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20498. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20499. */
  20500. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20501. /**
  20502. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20503. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20504. */
  20505. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20506. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20507. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20508. // Edges
  20509. /**
  20510. * Defines edge width used when edgesRenderer is enabled
  20511. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20512. */
  20513. _this.edgesWidth = 1;
  20514. /**
  20515. * Defines edge color used when edgesRenderer is enabled
  20516. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20517. */
  20518. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20519. // Cache
  20520. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  20521. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  20522. /** @hidden */
  20523. _this._renderId = 0;
  20524. /** @hidden */
  20525. _this._intersectionsInProgress = new Array();
  20526. /** @hidden */
  20527. _this._unIndexed = false;
  20528. /** @hidden */
  20529. _this._lightSources = new Array();
  20530. /**
  20531. * An event triggered when the mesh is rebuilt.
  20532. */
  20533. _this.onRebuildObservable = new BABYLON.Observable();
  20534. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20535. if (collidedMesh === void 0) { collidedMesh = null; }
  20536. //TODO move this to the collision coordinator!
  20537. if (_this.getScene().workerCollisions)
  20538. newPosition.multiplyInPlace(_this._collider._radius);
  20539. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20540. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20541. _this.position.addInPlace(_this._diffPositionForCollisions);
  20542. }
  20543. if (collidedMesh) {
  20544. _this.onCollideObservable.notifyObservers(collidedMesh);
  20545. }
  20546. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20547. };
  20548. _this.getScene().addMesh(_this);
  20549. _this._resyncLightSources();
  20550. return _this;
  20551. }
  20552. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20553. /**
  20554. * No billboard
  20555. */
  20556. get: function () {
  20557. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20558. },
  20559. enumerable: true,
  20560. configurable: true
  20561. });
  20562. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20563. /** Billboard on X axis */
  20564. get: function () {
  20565. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20566. },
  20567. enumerable: true,
  20568. configurable: true
  20569. });
  20570. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20571. /** Billboard on Y axis */
  20572. get: function () {
  20573. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20574. },
  20575. enumerable: true,
  20576. configurable: true
  20577. });
  20578. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20579. /** Billboard on Z axis */
  20580. get: function () {
  20581. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20582. },
  20583. enumerable: true,
  20584. configurable: true
  20585. });
  20586. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20587. /** Billboard on all axes */
  20588. get: function () {
  20589. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20595. /**
  20596. * Gets the number of facets in the mesh
  20597. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20598. */
  20599. get: function () {
  20600. return this._facetData.facetNb;
  20601. },
  20602. enumerable: true,
  20603. configurable: true
  20604. });
  20605. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20606. /**
  20607. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20608. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20609. */
  20610. get: function () {
  20611. return this._facetData.partitioningSubdivisions;
  20612. },
  20613. set: function (nb) {
  20614. this._facetData.partitioningSubdivisions = nb;
  20615. },
  20616. enumerable: true,
  20617. configurable: true
  20618. });
  20619. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20620. /**
  20621. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20622. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20623. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20624. */
  20625. get: function () {
  20626. return this._facetData.partitioningBBoxRatio;
  20627. },
  20628. set: function (ratio) {
  20629. this._facetData.partitioningBBoxRatio = ratio;
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20635. /**
  20636. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20637. * Works only for updatable meshes.
  20638. * Doesn't work with multi-materials
  20639. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20640. */
  20641. get: function () {
  20642. return this._facetData.facetDepthSort;
  20643. },
  20644. set: function (sort) {
  20645. this._facetData.facetDepthSort = sort;
  20646. },
  20647. enumerable: true,
  20648. configurable: true
  20649. });
  20650. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20651. /**
  20652. * The location (Vector3) where the facet depth sort must be computed from.
  20653. * By default, the active camera position.
  20654. * Used only when facet depth sort is enabled
  20655. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20656. */
  20657. get: function () {
  20658. return this._facetData.facetDepthSortFrom;
  20659. },
  20660. set: function (location) {
  20661. this._facetData.facetDepthSortFrom = location;
  20662. },
  20663. enumerable: true,
  20664. configurable: true
  20665. });
  20666. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20667. /**
  20668. * gets a boolean indicating if facetData is enabled
  20669. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20670. */
  20671. get: function () {
  20672. return this._facetData.facetDataEnabled;
  20673. },
  20674. enumerable: true,
  20675. configurable: true
  20676. });
  20677. /** @hidden */
  20678. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20679. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20680. return false;
  20681. }
  20682. this._markSubMeshesAsMiscDirty();
  20683. return true;
  20684. };
  20685. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20686. /** Set a function to call when this mesh collides with another one */
  20687. set: function (callback) {
  20688. if (this._onCollideObserver) {
  20689. this.onCollideObservable.remove(this._onCollideObserver);
  20690. }
  20691. this._onCollideObserver = this.onCollideObservable.add(callback);
  20692. },
  20693. enumerable: true,
  20694. configurable: true
  20695. });
  20696. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20697. /** Set a function to call when the collision's position changes */
  20698. set: function (callback) {
  20699. if (this._onCollisionPositionChangeObserver) {
  20700. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20701. }
  20702. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20703. },
  20704. enumerable: true,
  20705. configurable: true
  20706. });
  20707. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20708. /**
  20709. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20710. */
  20711. get: function () {
  20712. return this._visibility;
  20713. },
  20714. /**
  20715. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20716. */
  20717. set: function (value) {
  20718. if (this._visibility === value) {
  20719. return;
  20720. }
  20721. this._visibility = value;
  20722. this._markSubMeshesAsMiscDirty();
  20723. },
  20724. enumerable: true,
  20725. configurable: true
  20726. });
  20727. Object.defineProperty(AbstractMesh.prototype, "material", {
  20728. /** Gets or sets current material */
  20729. get: function () {
  20730. return this._material;
  20731. },
  20732. set: function (value) {
  20733. if (this._material === value) {
  20734. return;
  20735. }
  20736. this._material = value;
  20737. if (this.onMaterialChangedObservable.hasObservers) {
  20738. this.onMaterialChangedObservable.notifyObservers(this);
  20739. }
  20740. if (!this.subMeshes) {
  20741. return;
  20742. }
  20743. this._unBindEffect();
  20744. },
  20745. enumerable: true,
  20746. configurable: true
  20747. });
  20748. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20749. /**
  20750. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20751. * @see http://doc.babylonjs.com/babylon101/shadows
  20752. */
  20753. get: function () {
  20754. return this._receiveShadows;
  20755. },
  20756. set: function (value) {
  20757. if (this._receiveShadows === value) {
  20758. return;
  20759. }
  20760. this._receiveShadows = value;
  20761. this._markSubMeshesAsLightDirty();
  20762. },
  20763. enumerable: true,
  20764. configurable: true
  20765. });
  20766. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20767. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20768. get: function () {
  20769. return this._hasVertexAlpha;
  20770. },
  20771. set: function (value) {
  20772. if (this._hasVertexAlpha === value) {
  20773. return;
  20774. }
  20775. this._hasVertexAlpha = value;
  20776. this._markSubMeshesAsAttributesDirty();
  20777. this._markSubMeshesAsMiscDirty();
  20778. },
  20779. enumerable: true,
  20780. configurable: true
  20781. });
  20782. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20783. /** 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) */
  20784. get: function () {
  20785. return this._useVertexColors;
  20786. },
  20787. set: function (value) {
  20788. if (this._useVertexColors === value) {
  20789. return;
  20790. }
  20791. this._useVertexColors = value;
  20792. this._markSubMeshesAsAttributesDirty();
  20793. },
  20794. enumerable: true,
  20795. configurable: true
  20796. });
  20797. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20798. /**
  20799. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20800. */
  20801. get: function () {
  20802. return this._computeBonesUsingShaders;
  20803. },
  20804. set: function (value) {
  20805. if (this._computeBonesUsingShaders === value) {
  20806. return;
  20807. }
  20808. this._computeBonesUsingShaders = value;
  20809. this._markSubMeshesAsAttributesDirty();
  20810. },
  20811. enumerable: true,
  20812. configurable: true
  20813. });
  20814. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20815. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20816. get: function () {
  20817. return this._numBoneInfluencers;
  20818. },
  20819. set: function (value) {
  20820. if (this._numBoneInfluencers === value) {
  20821. return;
  20822. }
  20823. this._numBoneInfluencers = value;
  20824. this._markSubMeshesAsAttributesDirty();
  20825. },
  20826. enumerable: true,
  20827. configurable: true
  20828. });
  20829. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20830. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20831. get: function () {
  20832. return this._applyFog;
  20833. },
  20834. set: function (value) {
  20835. if (this._applyFog === value) {
  20836. return;
  20837. }
  20838. this._applyFog = value;
  20839. this._markSubMeshesAsMiscDirty();
  20840. },
  20841. enumerable: true,
  20842. configurable: true
  20843. });
  20844. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20845. /**
  20846. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20847. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20848. */
  20849. get: function () {
  20850. return this._layerMask;
  20851. },
  20852. set: function (value) {
  20853. if (value === this._layerMask) {
  20854. return;
  20855. }
  20856. this._layerMask = value;
  20857. this._resyncLightSources();
  20858. },
  20859. enumerable: true,
  20860. configurable: true
  20861. });
  20862. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20863. /**
  20864. * Gets or sets a collision mask used to mask collisions (default is -1).
  20865. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20866. */
  20867. get: function () {
  20868. return this._collisionMask;
  20869. },
  20870. set: function (mask) {
  20871. this._collisionMask = !isNaN(mask) ? mask : -1;
  20872. },
  20873. enumerable: true,
  20874. configurable: true
  20875. });
  20876. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20877. /**
  20878. * Gets or sets the current collision group mask (-1 by default).
  20879. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20880. */
  20881. get: function () {
  20882. return this._collisionGroup;
  20883. },
  20884. set: function (mask) {
  20885. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20886. },
  20887. enumerable: true,
  20888. configurable: true
  20889. });
  20890. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20891. /** @hidden */
  20892. get: function () {
  20893. return null;
  20894. },
  20895. enumerable: true,
  20896. configurable: true
  20897. });
  20898. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20899. get: function () {
  20900. return this._skeleton;
  20901. },
  20902. /**
  20903. * Gets or sets a skeleton to apply skining transformations
  20904. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20905. */
  20906. set: function (value) {
  20907. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20908. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20909. }
  20910. if (value && value.needInitialSkinMatrix) {
  20911. value._registerMeshWithPoseMatrix(this);
  20912. }
  20913. this._skeleton = value;
  20914. if (!this._skeleton) {
  20915. this._bonesTransformMatrices = null;
  20916. }
  20917. this._markSubMeshesAsAttributesDirty();
  20918. },
  20919. enumerable: true,
  20920. configurable: true
  20921. });
  20922. /**
  20923. * Returns the string "AbstractMesh"
  20924. * @returns "AbstractMesh"
  20925. */
  20926. AbstractMesh.prototype.getClassName = function () {
  20927. return "AbstractMesh";
  20928. };
  20929. /**
  20930. * Gets a string representation of the current mesh
  20931. * @param fullDetails defines a boolean indicating if full details must be included
  20932. * @returns a string representation of the current mesh
  20933. */
  20934. AbstractMesh.prototype.toString = function (fullDetails) {
  20935. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20936. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20937. if (this._skeleton) {
  20938. ret += ", skeleton: " + this._skeleton.name;
  20939. }
  20940. if (fullDetails) {
  20941. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20942. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20943. }
  20944. return ret;
  20945. };
  20946. /** @hidden */
  20947. AbstractMesh.prototype._rebuild = function () {
  20948. this.onRebuildObservable.notifyObservers(this);
  20949. if (this._occlusionQuery) {
  20950. this._occlusionQuery = null;
  20951. }
  20952. if (!this.subMeshes) {
  20953. return;
  20954. }
  20955. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20956. var subMesh = _a[_i];
  20957. subMesh._rebuild();
  20958. }
  20959. };
  20960. /** @hidden */
  20961. AbstractMesh.prototype._resyncLightSources = function () {
  20962. this._lightSources.length = 0;
  20963. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20964. var light = _a[_i];
  20965. if (!light.isEnabled()) {
  20966. continue;
  20967. }
  20968. if (light.canAffectMesh(this)) {
  20969. this._lightSources.push(light);
  20970. }
  20971. }
  20972. this._markSubMeshesAsLightDirty();
  20973. };
  20974. /** @hidden */
  20975. AbstractMesh.prototype._resyncLighSource = function (light) {
  20976. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20977. var index = this._lightSources.indexOf(light);
  20978. if (index === -1) {
  20979. if (!isIn) {
  20980. return;
  20981. }
  20982. this._lightSources.push(light);
  20983. }
  20984. else {
  20985. if (isIn) {
  20986. return;
  20987. }
  20988. this._lightSources.splice(index, 1);
  20989. }
  20990. this._markSubMeshesAsLightDirty();
  20991. };
  20992. /** @hidden */
  20993. AbstractMesh.prototype._unBindEffect = function () {
  20994. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20995. var subMesh = _a[_i];
  20996. subMesh.setEffect(null);
  20997. }
  20998. };
  20999. /** @hidden */
  21000. AbstractMesh.prototype._removeLightSource = function (light) {
  21001. var index = this._lightSources.indexOf(light);
  21002. if (index === -1) {
  21003. return;
  21004. }
  21005. this._lightSources.splice(index, 1);
  21006. this._markSubMeshesAsLightDirty();
  21007. };
  21008. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21009. if (!this.subMeshes) {
  21010. return;
  21011. }
  21012. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21013. var subMesh = _a[_i];
  21014. if (subMesh._materialDefines) {
  21015. func(subMesh._materialDefines);
  21016. }
  21017. }
  21018. };
  21019. /** @hidden */
  21020. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21021. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21022. };
  21023. /** @hidden */
  21024. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21025. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21026. };
  21027. /** @hidden */
  21028. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21029. if (!this.subMeshes) {
  21030. return;
  21031. }
  21032. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21033. var subMesh = _a[_i];
  21034. var material = subMesh.getMaterial();
  21035. if (material) {
  21036. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21037. }
  21038. }
  21039. };
  21040. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21041. /**
  21042. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21043. */
  21044. get: function () {
  21045. return this._scaling;
  21046. },
  21047. set: function (newScaling) {
  21048. this._scaling = newScaling;
  21049. if (this.physicsImpostor) {
  21050. this.physicsImpostor.forceUpdate();
  21051. }
  21052. },
  21053. enumerable: true,
  21054. configurable: true
  21055. });
  21056. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21057. // Methods
  21058. /**
  21059. * Returns true if the mesh is blocked. Implemented by child classes
  21060. */
  21061. get: function () {
  21062. return false;
  21063. },
  21064. enumerable: true,
  21065. configurable: true
  21066. });
  21067. /**
  21068. * Returns the mesh itself by default. Implemented by child classes
  21069. * @param camera defines the camera to use to pick the right LOD level
  21070. * @returns the currentAbstractMesh
  21071. */
  21072. AbstractMesh.prototype.getLOD = function (camera) {
  21073. return this;
  21074. };
  21075. /**
  21076. * Returns 0 by default. Implemented by child classes
  21077. * @returns an integer
  21078. */
  21079. AbstractMesh.prototype.getTotalVertices = function () {
  21080. return 0;
  21081. };
  21082. /**
  21083. * Returns null by default. Implemented by child classes
  21084. * @returns null
  21085. */
  21086. AbstractMesh.prototype.getIndices = function () {
  21087. return null;
  21088. };
  21089. /**
  21090. * Returns the array of the requested vertex data kind. Implemented by child classes
  21091. * @param kind defines the vertex data kind to use
  21092. * @returns null
  21093. */
  21094. AbstractMesh.prototype.getVerticesData = function (kind) {
  21095. return null;
  21096. };
  21097. /**
  21098. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21099. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21100. * Note that a new underlying VertexBuffer object is created each call.
  21101. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21102. * @param kind defines vertex data kind:
  21103. * * BABYLON.VertexBuffer.PositionKind
  21104. * * BABYLON.VertexBuffer.UVKind
  21105. * * BABYLON.VertexBuffer.UV2Kind
  21106. * * BABYLON.VertexBuffer.UV3Kind
  21107. * * BABYLON.VertexBuffer.UV4Kind
  21108. * * BABYLON.VertexBuffer.UV5Kind
  21109. * * BABYLON.VertexBuffer.UV6Kind
  21110. * * BABYLON.VertexBuffer.ColorKind
  21111. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21112. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21113. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21114. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21115. * @param data defines the data source
  21116. * @param updatable defines if the data must be flagged as updatable (or static)
  21117. * @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
  21118. * @returns the current mesh
  21119. */
  21120. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21121. return this;
  21122. };
  21123. /**
  21124. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21125. * If the mesh has no geometry, it is simply returned as it is.
  21126. * @param kind defines vertex data kind:
  21127. * * BABYLON.VertexBuffer.PositionKind
  21128. * * BABYLON.VertexBuffer.UVKind
  21129. * * BABYLON.VertexBuffer.UV2Kind
  21130. * * BABYLON.VertexBuffer.UV3Kind
  21131. * * BABYLON.VertexBuffer.UV4Kind
  21132. * * BABYLON.VertexBuffer.UV5Kind
  21133. * * BABYLON.VertexBuffer.UV6Kind
  21134. * * BABYLON.VertexBuffer.ColorKind
  21135. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21136. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21137. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21138. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21139. * @param data defines the data source
  21140. * @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
  21141. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21142. * @returns the current mesh
  21143. */
  21144. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21145. return this;
  21146. };
  21147. /**
  21148. * Sets the mesh indices,
  21149. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21150. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21151. * @param totalVertices Defines the total number of vertices
  21152. * @returns the current mesh
  21153. */
  21154. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21155. return this;
  21156. };
  21157. /**
  21158. * Gets a boolean indicating if specific vertex data is present
  21159. * @param kind defines the vertex data kind to use
  21160. * @returns true is data kind is present
  21161. */
  21162. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21163. return false;
  21164. };
  21165. /**
  21166. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21167. * @returns a BoundingInfo
  21168. */
  21169. AbstractMesh.prototype.getBoundingInfo = function () {
  21170. if (this._masterMesh) {
  21171. return this._masterMesh.getBoundingInfo();
  21172. }
  21173. if (!this._boundingInfo) {
  21174. // this._boundingInfo is being created here
  21175. this._updateBoundingInfo();
  21176. }
  21177. // cannot be null.
  21178. return this._boundingInfo;
  21179. };
  21180. /**
  21181. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21182. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21183. * @returns the current mesh
  21184. */
  21185. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21186. if (includeDescendants === void 0) { includeDescendants = true; }
  21187. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21188. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21189. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21190. if (maxDimension === 0) {
  21191. return this;
  21192. }
  21193. var scale = 1 / maxDimension;
  21194. this.scaling.scaleInPlace(scale);
  21195. return this;
  21196. };
  21197. /**
  21198. * Overwrite the current bounding info
  21199. * @param boundingInfo defines the new bounding info
  21200. * @returns the current mesh
  21201. */
  21202. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21203. this._boundingInfo = boundingInfo;
  21204. return this;
  21205. };
  21206. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21207. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21208. get: function () {
  21209. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21210. },
  21211. enumerable: true,
  21212. configurable: true
  21213. });
  21214. /** @hidden */
  21215. AbstractMesh.prototype._preActivate = function () {
  21216. };
  21217. /** @hidden */
  21218. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21219. };
  21220. /** @hidden */
  21221. AbstractMesh.prototype._activate = function (renderId) {
  21222. this._renderId = renderId;
  21223. };
  21224. /**
  21225. * Gets the current world matrix
  21226. * @returns a Matrix
  21227. */
  21228. AbstractMesh.prototype.getWorldMatrix = function () {
  21229. if (this._masterMesh) {
  21230. return this._masterMesh.getWorldMatrix();
  21231. }
  21232. return _super.prototype.getWorldMatrix.call(this);
  21233. };
  21234. /** @hidden */
  21235. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21236. if (this._masterMesh) {
  21237. return this._masterMesh._getWorldMatrixDeterminant();
  21238. }
  21239. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21240. };
  21241. // ================================== Point of View Movement =================================
  21242. /**
  21243. * Perform relative position change from the point of view of behind the front of the mesh.
  21244. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21245. * Supports definition of mesh facing forward or backward
  21246. * @param amountRight defines the distance on the right axis
  21247. * @param amountUp defines the distance on the up axis
  21248. * @param amountForward defines the distance on the forward axis
  21249. * @returns the current mesh
  21250. */
  21251. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21252. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21253. return this;
  21254. };
  21255. /**
  21256. * Calculate relative position change from the point of view of behind the front of the mesh.
  21257. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21258. * Supports definition of mesh facing forward or backward
  21259. * @param amountRight defines the distance on the right axis
  21260. * @param amountUp defines the distance on the up axis
  21261. * @param amountForward defines the distance on the forward axis
  21262. * @returns the new displacement vector
  21263. */
  21264. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21265. var rotMatrix = new BABYLON.Matrix();
  21266. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21267. rotQuaternion.toRotationMatrix(rotMatrix);
  21268. var translationDelta = BABYLON.Vector3.Zero();
  21269. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21270. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21271. return translationDelta;
  21272. };
  21273. // ================================== Point of View Rotation =================================
  21274. /**
  21275. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21276. * Supports definition of mesh facing forward or backward
  21277. * @param flipBack defines the flip
  21278. * @param twirlClockwise defines the twirl
  21279. * @param tiltRight defines the tilt
  21280. * @returns the current mesh
  21281. */
  21282. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21283. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21284. return this;
  21285. };
  21286. /**
  21287. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21288. * Supports definition of mesh facing forward or backward.
  21289. * @param flipBack defines the flip
  21290. * @param twirlClockwise defines the twirl
  21291. * @param tiltRight defines the tilt
  21292. * @returns the new rotation vector
  21293. */
  21294. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21295. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21296. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21297. };
  21298. /**
  21299. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21300. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21301. * @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
  21302. * @returns the new bounding vectors
  21303. */
  21304. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21305. if (includeDescendants === void 0) { includeDescendants = true; }
  21306. if (predicate === void 0) { predicate = null; }
  21307. // Ensures that all world matrix will be recomputed.
  21308. this.getScene().incrementRenderId();
  21309. this.computeWorldMatrix(true);
  21310. var min;
  21311. var max;
  21312. var boundingInfo = this.getBoundingInfo();
  21313. if (!this.subMeshes) {
  21314. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21315. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21316. }
  21317. else {
  21318. min = boundingInfo.boundingBox.minimumWorld;
  21319. max = boundingInfo.boundingBox.maximumWorld;
  21320. }
  21321. if (includeDescendants) {
  21322. var descendants = this.getDescendants(false);
  21323. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21324. var descendant = descendants_1[_i];
  21325. var childMesh = descendant;
  21326. childMesh.computeWorldMatrix(true);
  21327. // Filters meshes based on custom predicate function.
  21328. if (predicate && !predicate(childMesh)) {
  21329. continue;
  21330. }
  21331. //make sure we have the needed params to get mix and max
  21332. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21333. continue;
  21334. }
  21335. var childBoundingInfo = childMesh.getBoundingInfo();
  21336. var boundingBox = childBoundingInfo.boundingBox;
  21337. var minBox = boundingBox.minimumWorld;
  21338. var maxBox = boundingBox.maximumWorld;
  21339. BABYLON.Tools.CheckExtends(minBox, min, max);
  21340. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21341. }
  21342. }
  21343. return {
  21344. min: min,
  21345. max: max
  21346. };
  21347. };
  21348. /** @hidden */
  21349. AbstractMesh.prototype._updateBoundingInfo = function () {
  21350. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21351. this._boundingInfo.update(this.worldMatrixFromCache);
  21352. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21353. return this;
  21354. };
  21355. /** @hidden */
  21356. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21357. if (!this.subMeshes) {
  21358. return this;
  21359. }
  21360. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21361. var subMesh = this.subMeshes[subIndex];
  21362. if (!subMesh.IsGlobal) {
  21363. subMesh.updateBoundingInfo(matrix);
  21364. }
  21365. }
  21366. return this;
  21367. };
  21368. /** @hidden */
  21369. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21370. // Bounding info
  21371. this._updateBoundingInfo();
  21372. };
  21373. /**
  21374. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21375. * A mesh is in the frustum if its bounding box intersects the frustum
  21376. * @param frustumPlanes defines the frustum to test
  21377. * @returns true if the mesh is in the frustum planes
  21378. */
  21379. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21380. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21381. };
  21382. /**
  21383. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21384. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21385. * @param frustumPlanes defines the frustum to test
  21386. * @returns true if the mesh is completely in the frustum planes
  21387. */
  21388. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21389. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21390. };
  21391. /**
  21392. * True if the mesh intersects another mesh or a SolidParticle object
  21393. * @param mesh defines a target mesh or SolidParticle to test
  21394. * @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)
  21395. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21396. * @returns true if there is an intersection
  21397. */
  21398. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21399. if (precise === void 0) { precise = false; }
  21400. if (!this._boundingInfo || !mesh._boundingInfo) {
  21401. return false;
  21402. }
  21403. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21404. return true;
  21405. }
  21406. if (includeDescendants) {
  21407. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21408. var child = _a[_i];
  21409. if (child.intersectsMesh(mesh, precise, true)) {
  21410. return true;
  21411. }
  21412. }
  21413. }
  21414. return false;
  21415. };
  21416. /**
  21417. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21418. * @param point defines the point to test
  21419. * @returns true if there is an intersection
  21420. */
  21421. AbstractMesh.prototype.intersectsPoint = function (point) {
  21422. if (!this._boundingInfo) {
  21423. return false;
  21424. }
  21425. return this._boundingInfo.intersectsPoint(point);
  21426. };
  21427. /**
  21428. * Gets the position of the current mesh in camera space
  21429. * @param camera defines the camera to use
  21430. * @returns a position
  21431. */
  21432. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21433. if (camera === void 0) { camera = null; }
  21434. if (!camera) {
  21435. camera = this.getScene().activeCamera;
  21436. }
  21437. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21438. };
  21439. /**
  21440. * Returns the distance from the mesh to the active camera
  21441. * @param camera defines the camera to use
  21442. * @returns the distance
  21443. */
  21444. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21445. if (camera === void 0) { camera = null; }
  21446. if (!camera) {
  21447. camera = this.getScene().activeCamera;
  21448. }
  21449. return this.absolutePosition.subtract(camera.position).length();
  21450. };
  21451. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21452. // Collisions
  21453. /**
  21454. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21455. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21456. */
  21457. get: function () {
  21458. return this._checkCollisions;
  21459. },
  21460. set: function (collisionEnabled) {
  21461. this._checkCollisions = collisionEnabled;
  21462. if (this.getScene().workerCollisions) {
  21463. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21464. }
  21465. },
  21466. enumerable: true,
  21467. configurable: true
  21468. });
  21469. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21470. /**
  21471. * Gets Collider object used to compute collisions (not physics)
  21472. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21473. */
  21474. get: function () {
  21475. return this._collider;
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. /**
  21481. * Move the mesh using collision engine
  21482. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21483. * @param displacement defines the requested displacement vector
  21484. * @returns the current mesh
  21485. */
  21486. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21487. var globalPosition = this.getAbsolutePosition();
  21488. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21489. if (!this._collider) {
  21490. this._collider = new BABYLON.Collider();
  21491. }
  21492. this._collider._radius = this.ellipsoid;
  21493. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21494. return this;
  21495. };
  21496. // Collisions
  21497. /** @hidden */
  21498. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21499. this._generatePointsArray();
  21500. if (!this._positions) {
  21501. return this;
  21502. }
  21503. // Transformation
  21504. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21505. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21506. subMesh._lastColliderWorldVertices = [];
  21507. subMesh._trianglePlanes = [];
  21508. var start = subMesh.verticesStart;
  21509. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21510. for (var i = start; i < end; i++) {
  21511. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21512. }
  21513. }
  21514. // Collide
  21515. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21516. if (collider.collisionFound) {
  21517. collider.collidedMesh = this;
  21518. }
  21519. return this;
  21520. };
  21521. /** @hidden */
  21522. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21523. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21524. var len = subMeshes.length;
  21525. for (var index = 0; index < len; index++) {
  21526. var subMesh = subMeshes.data[index];
  21527. // Bounding test
  21528. if (len > 1 && !subMesh._checkCollision(collider))
  21529. continue;
  21530. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21531. }
  21532. return this;
  21533. };
  21534. /** @hidden */
  21535. AbstractMesh.prototype._checkCollision = function (collider) {
  21536. // Bounding box test
  21537. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21538. return this;
  21539. // Transformation matrix
  21540. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  21541. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21542. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21543. return this;
  21544. };
  21545. // Picking
  21546. /** @hidden */
  21547. AbstractMesh.prototype._generatePointsArray = function () {
  21548. return false;
  21549. };
  21550. /**
  21551. * Checks if the passed Ray intersects with the mesh
  21552. * @param ray defines the ray to use
  21553. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21554. * @returns the picking info
  21555. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21556. */
  21557. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21558. var pickingInfo = new BABYLON.PickingInfo();
  21559. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21560. return pickingInfo;
  21561. }
  21562. if (!this._generatePointsArray()) {
  21563. return pickingInfo;
  21564. }
  21565. var intersectInfo = null;
  21566. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21567. var len = subMeshes.length;
  21568. for (var index = 0; index < len; index++) {
  21569. var subMesh = subMeshes.data[index];
  21570. // Bounding test
  21571. if (len > 1 && !subMesh.canIntersects(ray))
  21572. continue;
  21573. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21574. if (currentIntersectInfo) {
  21575. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21576. intersectInfo = currentIntersectInfo;
  21577. intersectInfo.subMeshId = index;
  21578. if (fastCheck) {
  21579. break;
  21580. }
  21581. }
  21582. }
  21583. }
  21584. if (intersectInfo) {
  21585. // Get picked point
  21586. var world = this.getWorldMatrix();
  21587. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21588. var direction = ray.direction.clone();
  21589. direction = direction.scale(intersectInfo.distance);
  21590. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21591. var pickedPoint = worldOrigin.add(worldDirection);
  21592. // Return result
  21593. pickingInfo.hit = true;
  21594. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21595. pickingInfo.pickedPoint = pickedPoint;
  21596. pickingInfo.pickedMesh = this;
  21597. pickingInfo.bu = intersectInfo.bu || 0;
  21598. pickingInfo.bv = intersectInfo.bv || 0;
  21599. pickingInfo.faceId = intersectInfo.faceId;
  21600. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21601. return pickingInfo;
  21602. }
  21603. return pickingInfo;
  21604. };
  21605. /**
  21606. * Clones the current mesh
  21607. * @param name defines the mesh name
  21608. * @param newParent defines the new mesh parent
  21609. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21610. * @returns the new mesh
  21611. */
  21612. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21613. return null;
  21614. };
  21615. /**
  21616. * Disposes all the submeshes of the current meshnp
  21617. * @returns the current mesh
  21618. */
  21619. AbstractMesh.prototype.releaseSubMeshes = function () {
  21620. if (this.subMeshes) {
  21621. while (this.subMeshes.length) {
  21622. this.subMeshes[0].dispose();
  21623. }
  21624. }
  21625. else {
  21626. this.subMeshes = new Array();
  21627. }
  21628. return this;
  21629. };
  21630. /**
  21631. * Releases resources associated with this abstract mesh.
  21632. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21633. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21634. */
  21635. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21636. var _this = this;
  21637. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21638. var index;
  21639. // Smart Array Retainers.
  21640. this.getScene().freeActiveMeshes();
  21641. this.getScene().freeRenderingGroups();
  21642. // Action manager
  21643. if (this.actionManager !== undefined && this.actionManager !== null) {
  21644. this.actionManager.dispose();
  21645. this.actionManager = null;
  21646. }
  21647. // Skeleton
  21648. this._skeleton = null;
  21649. // Intersections in progress
  21650. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21651. var other = this._intersectionsInProgress[index];
  21652. var pos = other._intersectionsInProgress.indexOf(this);
  21653. other._intersectionsInProgress.splice(pos, 1);
  21654. }
  21655. this._intersectionsInProgress = [];
  21656. // Lights
  21657. var lights = this.getScene().lights;
  21658. lights.forEach(function (light) {
  21659. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21660. if (meshIndex !== -1) {
  21661. light.includedOnlyMeshes.splice(meshIndex, 1);
  21662. }
  21663. meshIndex = light.excludedMeshes.indexOf(_this);
  21664. if (meshIndex !== -1) {
  21665. light.excludedMeshes.splice(meshIndex, 1);
  21666. }
  21667. // Shadow generators
  21668. var generator = light.getShadowGenerator();
  21669. if (generator) {
  21670. var shadowMap = generator.getShadowMap();
  21671. if (shadowMap && shadowMap.renderList) {
  21672. meshIndex = shadowMap.renderList.indexOf(_this);
  21673. if (meshIndex !== -1) {
  21674. shadowMap.renderList.splice(meshIndex, 1);
  21675. }
  21676. }
  21677. }
  21678. });
  21679. // SubMeshes
  21680. if (this.getClassName() !== "InstancedMesh") {
  21681. this.releaseSubMeshes();
  21682. }
  21683. // Query
  21684. var engine = this.getScene().getEngine();
  21685. if (this._occlusionQuery) {
  21686. this.isOcclusionQueryInProgress = false;
  21687. engine.deleteQuery(this._occlusionQuery);
  21688. this._occlusionQuery = null;
  21689. }
  21690. // Engine
  21691. engine.wipeCaches();
  21692. // Remove from scene
  21693. this.getScene().removeMesh(this);
  21694. if (disposeMaterialAndTextures) {
  21695. if (this.material) {
  21696. this.material.dispose(false, true);
  21697. }
  21698. }
  21699. if (!doNotRecurse) {
  21700. // Particles
  21701. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21702. if (this.getScene().particleSystems[index].emitter === this) {
  21703. this.getScene().particleSystems[index].dispose();
  21704. index--;
  21705. }
  21706. }
  21707. }
  21708. // facet data
  21709. if (this._facetData.facetDataEnabled) {
  21710. this.disableFacetData();
  21711. }
  21712. this.onAfterWorldMatrixUpdateObservable.clear();
  21713. this.onCollideObservable.clear();
  21714. this.onCollisionPositionChangeObservable.clear();
  21715. this.onRebuildObservable.clear();
  21716. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21717. };
  21718. /**
  21719. * Adds the passed mesh as a child to the current mesh
  21720. * @param mesh defines the child mesh
  21721. * @returns the current mesh
  21722. */
  21723. AbstractMesh.prototype.addChild = function (mesh) {
  21724. mesh.setParent(this);
  21725. return this;
  21726. };
  21727. /**
  21728. * Removes the passed mesh from the current mesh children list
  21729. * @param mesh defines the child mesh
  21730. * @returns the current mesh
  21731. */
  21732. AbstractMesh.prototype.removeChild = function (mesh) {
  21733. mesh.setParent(null);
  21734. return this;
  21735. };
  21736. // Facet data
  21737. /** @hidden */
  21738. AbstractMesh.prototype._initFacetData = function () {
  21739. var data = this._facetData;
  21740. if (!data.facetNormals) {
  21741. data.facetNormals = new Array();
  21742. }
  21743. if (!data.facetPositions) {
  21744. data.facetPositions = new Array();
  21745. }
  21746. if (!data.facetPartitioning) {
  21747. data.facetPartitioning = new Array();
  21748. }
  21749. data.facetNb = (this.getIndices().length / 3) | 0;
  21750. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21751. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21752. for (var f = 0; f < data.facetNb; f++) {
  21753. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21754. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21755. }
  21756. data.facetDataEnabled = true;
  21757. return this;
  21758. };
  21759. /**
  21760. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21761. * This method can be called within the render loop.
  21762. * 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
  21763. * @returns the current mesh
  21764. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21765. */
  21766. AbstractMesh.prototype.updateFacetData = function () {
  21767. var data = this._facetData;
  21768. if (!data.facetDataEnabled) {
  21769. this._initFacetData();
  21770. }
  21771. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21772. var indices = this.getIndices();
  21773. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21774. var bInfo = this.getBoundingInfo();
  21775. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21776. // init arrays, matrix and sort function on first call
  21777. data.facetDepthSortEnabled = true;
  21778. if (indices instanceof Uint16Array) {
  21779. data.depthSortedIndices = new Uint16Array(indices);
  21780. }
  21781. else if (indices instanceof Uint32Array) {
  21782. data.depthSortedIndices = new Uint32Array(indices);
  21783. }
  21784. else {
  21785. var needs32bits = false;
  21786. for (var i = 0; i < indices.length; i++) {
  21787. if (indices[i] > 65535) {
  21788. needs32bits = true;
  21789. break;
  21790. }
  21791. }
  21792. if (needs32bits) {
  21793. data.depthSortedIndices = new Uint32Array(indices);
  21794. }
  21795. else {
  21796. data.depthSortedIndices = new Uint16Array(indices);
  21797. }
  21798. }
  21799. data.facetDepthSortFunction = function (f1, f2) {
  21800. return (f2.sqDistance - f1.sqDistance);
  21801. };
  21802. if (!data.facetDepthSortFrom) {
  21803. var camera = this.getScene().activeCamera;
  21804. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21805. }
  21806. data.depthSortedFacets = [];
  21807. for (var f = 0; f < data.facetNb; f++) {
  21808. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21809. data.depthSortedFacets.push(depthSortedFacet);
  21810. }
  21811. data.invertedMatrix = BABYLON.Matrix.Identity();
  21812. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21813. }
  21814. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21815. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21816. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21817. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  21818. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  21819. data.subDiv.max = data.partitioningSubdivisions;
  21820. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21821. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  21822. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  21823. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  21824. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  21825. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  21826. // set the parameters for ComputeNormals()
  21827. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  21828. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  21829. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21830. data.facetParameters.bInfo = bInfo;
  21831. data.facetParameters.bbSize = data.bbSize;
  21832. data.facetParameters.subDiv = data.subDiv;
  21833. data.facetParameters.ratio = this.partitioningBBoxRatio;
  21834. data.facetParameters.depthSort = data.facetDepthSort;
  21835. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21836. this.computeWorldMatrix(true);
  21837. this._worldMatrix.invertToRef(data.invertedMatrix);
  21838. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  21839. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  21840. }
  21841. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  21842. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  21843. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21844. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  21845. var l = (data.depthSortedIndices.length / 3) | 0;
  21846. for (var f = 0; f < l; f++) {
  21847. var sind = data.depthSortedFacets[f].ind;
  21848. data.depthSortedIndices[f * 3] = indices[sind];
  21849. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21850. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21851. }
  21852. this.updateIndices(data.depthSortedIndices);
  21853. }
  21854. return this;
  21855. };
  21856. /**
  21857. * Returns the facetLocalNormals array.
  21858. * The normals are expressed in the mesh local spac
  21859. * @returns an array of Vector3
  21860. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21861. */
  21862. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21863. if (!this._facetData.facetNormals) {
  21864. this.updateFacetData();
  21865. }
  21866. return this._facetData.facetNormals;
  21867. };
  21868. /**
  21869. * Returns the facetLocalPositions array.
  21870. * The facet positions are expressed in the mesh local space
  21871. * @returns an array of Vector3
  21872. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21873. */
  21874. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21875. if (!this._facetData.facetPositions) {
  21876. this.updateFacetData();
  21877. }
  21878. return this._facetData.facetPositions;
  21879. };
  21880. /**
  21881. * Returns the facetLocalPartioning array
  21882. * @returns an array of array of numbers
  21883. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21884. */
  21885. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21886. if (!this._facetData.facetPartitioning) {
  21887. this.updateFacetData();
  21888. }
  21889. return this._facetData.facetPartitioning;
  21890. };
  21891. /**
  21892. * Returns the i-th facet position in the world system.
  21893. * This method allocates a new Vector3 per call
  21894. * @param i defines the facet index
  21895. * @returns a new Vector3
  21896. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21897. */
  21898. AbstractMesh.prototype.getFacetPosition = function (i) {
  21899. var pos = BABYLON.Vector3.Zero();
  21900. this.getFacetPositionToRef(i, pos);
  21901. return pos;
  21902. };
  21903. /**
  21904. * Sets the reference Vector3 with the i-th facet position in the world system
  21905. * @param i defines the facet index
  21906. * @param ref defines the target vector
  21907. * @returns the current mesh
  21908. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21909. */
  21910. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21911. var localPos = (this.getFacetLocalPositions())[i];
  21912. var world = this.getWorldMatrix();
  21913. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21914. return this;
  21915. };
  21916. /**
  21917. * Returns the i-th facet normal in the world system.
  21918. * This method allocates a new Vector3 per call
  21919. * @param i defines the facet index
  21920. * @returns a new Vector3
  21921. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21922. */
  21923. AbstractMesh.prototype.getFacetNormal = function (i) {
  21924. var norm = BABYLON.Vector3.Zero();
  21925. this.getFacetNormalToRef(i, norm);
  21926. return norm;
  21927. };
  21928. /**
  21929. * Sets the reference Vector3 with the i-th facet normal in the world system
  21930. * @param i defines the facet index
  21931. * @param ref defines the target vector
  21932. * @returns the current mesh
  21933. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21934. */
  21935. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21936. var localNorm = (this.getFacetLocalNormals())[i];
  21937. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21938. return this;
  21939. };
  21940. /**
  21941. * 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)
  21942. * @param x defines x coordinate
  21943. * @param y defines y coordinate
  21944. * @param z defines z coordinate
  21945. * @returns the array of facet indexes
  21946. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21947. */
  21948. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21949. var bInfo = this.getBoundingInfo();
  21950. var data = this._facetData;
  21951. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  21952. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  21953. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  21954. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  21955. return null;
  21956. }
  21957. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  21958. };
  21959. /**
  21960. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21961. * @param projected sets as the (x,y,z) world projection on the facet
  21962. * @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
  21963. * @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
  21964. * @param x defines x coordinate
  21965. * @param y defines y coordinate
  21966. * @param z defines z coordinate
  21967. * @returns the face index if found (or null instead)
  21968. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21969. */
  21970. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21971. if (checkFace === void 0) { checkFace = false; }
  21972. if (facing === void 0) { facing = true; }
  21973. var world = this.getWorldMatrix();
  21974. var invMat = BABYLON.Tmp.Matrix[5];
  21975. world.invertToRef(invMat);
  21976. var invVect = BABYLON.Tmp.Vector3[8];
  21977. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21978. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21979. if (projected) {
  21980. // tranform the local computed projected vector to world coordinates
  21981. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21982. }
  21983. return closest;
  21984. };
  21985. /**
  21986. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21987. * @param projected sets as the (x,y,z) local projection on the facet
  21988. * @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
  21989. * @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
  21990. * @param x defines x coordinate
  21991. * @param y defines y coordinate
  21992. * @param z defines z coordinate
  21993. * @returns the face index if found (or null instead)
  21994. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21995. */
  21996. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21997. if (checkFace === void 0) { checkFace = false; }
  21998. if (facing === void 0) { facing = true; }
  21999. var closest = null;
  22000. var tmpx = 0.0;
  22001. var tmpy = 0.0;
  22002. var tmpz = 0.0;
  22003. var d = 0.0; // tmp dot facet normal * facet position
  22004. var t0 = 0.0;
  22005. var projx = 0.0;
  22006. var projy = 0.0;
  22007. var projz = 0.0;
  22008. // Get all the facets in the same partitioning block than (x, y, z)
  22009. var facetPositions = this.getFacetLocalPositions();
  22010. var facetNormals = this.getFacetLocalNormals();
  22011. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22012. if (!facetsInBlock) {
  22013. return null;
  22014. }
  22015. // Get the closest facet to (x, y, z)
  22016. var shortest = Number.MAX_VALUE; // init distance vars
  22017. var tmpDistance = shortest;
  22018. var fib; // current facet in the block
  22019. var norm; // current facet normal
  22020. var p0; // current facet barycenter position
  22021. // loop on all the facets in the current partitioning block
  22022. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22023. fib = facetsInBlock[idx];
  22024. norm = facetNormals[fib];
  22025. p0 = facetPositions[fib];
  22026. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22027. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22028. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22029. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22030. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22031. projx = x + norm.x * t0;
  22032. projy = y + norm.y * t0;
  22033. projz = z + norm.z * t0;
  22034. tmpx = projx - x;
  22035. tmpy = projy - y;
  22036. tmpz = projz - z;
  22037. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22038. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22039. shortest = tmpDistance;
  22040. closest = fib;
  22041. if (projected) {
  22042. projected.x = projx;
  22043. projected.y = projy;
  22044. projected.z = projz;
  22045. }
  22046. }
  22047. }
  22048. }
  22049. return closest;
  22050. };
  22051. /**
  22052. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22053. * @returns the parameters
  22054. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22055. */
  22056. AbstractMesh.prototype.getFacetDataParameters = function () {
  22057. return this._facetData.facetParameters;
  22058. };
  22059. /**
  22060. * Disables the feature FacetData and frees the related memory
  22061. * @returns the current mesh
  22062. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22063. */
  22064. AbstractMesh.prototype.disableFacetData = function () {
  22065. if (this._facetData.facetDataEnabled) {
  22066. this._facetData.facetDataEnabled = false;
  22067. this._facetData.facetPositions = new Array();
  22068. this._facetData.facetNormals = new Array();
  22069. this._facetData.facetPartitioning = new Array();
  22070. this._facetData.facetParameters = null;
  22071. this._facetData.depthSortedIndices = new Uint32Array(0);
  22072. }
  22073. return this;
  22074. };
  22075. /**
  22076. * Updates the AbstractMesh indices array
  22077. * @param indices defines the data source
  22078. * @returns the current mesh
  22079. */
  22080. AbstractMesh.prototype.updateIndices = function (indices) {
  22081. return this;
  22082. };
  22083. /**
  22084. * Creates new normals data for the mesh
  22085. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22086. * @returns the current mesh
  22087. */
  22088. AbstractMesh.prototype.createNormals = function (updatable) {
  22089. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22090. var indices = this.getIndices();
  22091. var normals;
  22092. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22093. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22094. }
  22095. else {
  22096. normals = [];
  22097. }
  22098. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22099. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22100. return this;
  22101. };
  22102. /**
  22103. * Align the mesh with a normal
  22104. * @param normal defines the normal to use
  22105. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22106. * @returns the current mesh
  22107. */
  22108. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22109. if (!upDirection) {
  22110. upDirection = BABYLON.Axis.Y;
  22111. }
  22112. var axisX = BABYLON.Tmp.Vector3[0];
  22113. var axisZ = BABYLON.Tmp.Vector3[1];
  22114. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22115. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22116. if (this.rotationQuaternion) {
  22117. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22118. }
  22119. else {
  22120. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22121. }
  22122. return this;
  22123. };
  22124. /** @hidden */
  22125. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22126. return false;
  22127. };
  22128. /** No occlusion */
  22129. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22130. /** Occlusion set to optimisitic */
  22131. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22132. /** Occlusion set to strict */
  22133. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22134. /** Use an accurante occlusion algorithm */
  22135. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22136. /** Use a conservative occlusion algorithm */
  22137. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22138. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22139. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22140. /** Culling strategy with bounding sphere only and then frustum culling */
  22141. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22142. return AbstractMesh;
  22143. }(BABYLON.TransformNode));
  22144. BABYLON.AbstractMesh = AbstractMesh;
  22145. })(BABYLON || (BABYLON = {}));
  22146. //# sourceMappingURL=babylon.abstractMesh.js.map
  22147. var BABYLON;
  22148. (function (BABYLON) {
  22149. /**
  22150. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22151. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22152. * 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.
  22153. */
  22154. var Light = /** @class */ (function (_super) {
  22155. __extends(Light, _super);
  22156. /**
  22157. * Creates a Light object in the scene.
  22158. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22159. * @param name The firendly name of the light
  22160. * @param scene The scene the light belongs too
  22161. */
  22162. function Light(name, scene) {
  22163. var _this = _super.call(this, name, scene) || this;
  22164. /**
  22165. * Diffuse gives the basic color to an object.
  22166. */
  22167. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22168. /**
  22169. * Specular produces a highlight color on an object.
  22170. * Note: This is note affecting PBR materials.
  22171. */
  22172. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22173. /**
  22174. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22175. * falling off base on range or angle.
  22176. * This can be set to any values in Light.FALLOFF_x.
  22177. *
  22178. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22179. * other types of materials.
  22180. */
  22181. _this.falloffType = Light.FALLOFF_DEFAULT;
  22182. /**
  22183. * Strength of the light.
  22184. * Note: By default it is define in the framework own unit.
  22185. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22186. */
  22187. _this.intensity = 1.0;
  22188. _this._range = Number.MAX_VALUE;
  22189. _this._inverseSquaredRange = 0;
  22190. /**
  22191. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22192. * of light.
  22193. */
  22194. _this._photometricScale = 1.0;
  22195. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22196. _this._radius = 0.00001;
  22197. /**
  22198. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22199. * exceeding the number allowed of the materials.
  22200. */
  22201. _this.renderPriority = 0;
  22202. _this._shadowEnabled = true;
  22203. _this._excludeWithLayerMask = 0;
  22204. _this._includeOnlyWithLayerMask = 0;
  22205. _this._lightmapMode = 0;
  22206. /**
  22207. * @hidden Internal use only.
  22208. */
  22209. _this._excludedMeshesIds = new Array();
  22210. /**
  22211. * @hidden Internal use only.
  22212. */
  22213. _this._includedOnlyMeshesIds = new Array();
  22214. _this.getScene().addLight(_this);
  22215. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22216. _this._buildUniformLayout();
  22217. _this.includedOnlyMeshes = new Array();
  22218. _this.excludedMeshes = new Array();
  22219. _this._resyncMeshes();
  22220. return _this;
  22221. }
  22222. Object.defineProperty(Light.prototype, "range", {
  22223. /**
  22224. * Defines how far from the source the light is impacting in scene units.
  22225. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22226. */
  22227. get: function () {
  22228. return this._range;
  22229. },
  22230. /**
  22231. * Defines how far from the source the light is impacting in scene units.
  22232. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22233. */
  22234. set: function (value) {
  22235. this._range = value;
  22236. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22237. },
  22238. enumerable: true,
  22239. configurable: true
  22240. });
  22241. Object.defineProperty(Light.prototype, "intensityMode", {
  22242. /**
  22243. * Gets the photometric scale used to interpret the intensity.
  22244. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22245. */
  22246. get: function () {
  22247. return this._intensityMode;
  22248. },
  22249. /**
  22250. * Sets the photometric scale used to interpret the intensity.
  22251. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22252. */
  22253. set: function (value) {
  22254. this._intensityMode = value;
  22255. this._computePhotometricScale();
  22256. },
  22257. enumerable: true,
  22258. configurable: true
  22259. });
  22260. ;
  22261. ;
  22262. Object.defineProperty(Light.prototype, "radius", {
  22263. /**
  22264. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22265. */
  22266. get: function () {
  22267. return this._radius;
  22268. },
  22269. /**
  22270. * sets the light radius used by PBR Materials to simulate soft area lights.
  22271. */
  22272. set: function (value) {
  22273. this._radius = value;
  22274. this._computePhotometricScale();
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. ;
  22280. ;
  22281. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22282. /**
  22283. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22284. * the current shadow generator.
  22285. */
  22286. get: function () {
  22287. return this._shadowEnabled;
  22288. },
  22289. /**
  22290. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22291. * the current shadow generator.
  22292. */
  22293. set: function (value) {
  22294. if (this._shadowEnabled === value) {
  22295. return;
  22296. }
  22297. this._shadowEnabled = value;
  22298. this._markMeshesAsLightDirty();
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22304. /**
  22305. * Gets the only meshes impacted by this light.
  22306. */
  22307. get: function () {
  22308. return this._includedOnlyMeshes;
  22309. },
  22310. /**
  22311. * Sets the only meshes impacted by this light.
  22312. */
  22313. set: function (value) {
  22314. this._includedOnlyMeshes = value;
  22315. this._hookArrayForIncludedOnly(value);
  22316. },
  22317. enumerable: true,
  22318. configurable: true
  22319. });
  22320. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22321. /**
  22322. * Gets the meshes not impacted by this light.
  22323. */
  22324. get: function () {
  22325. return this._excludedMeshes;
  22326. },
  22327. /**
  22328. * Sets the meshes not impacted by this light.
  22329. */
  22330. set: function (value) {
  22331. this._excludedMeshes = value;
  22332. this._hookArrayForExcluded(value);
  22333. },
  22334. enumerable: true,
  22335. configurable: true
  22336. });
  22337. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22338. /**
  22339. * Gets the layer id use to find what meshes are not impacted by the light.
  22340. * Inactive if 0
  22341. */
  22342. get: function () {
  22343. return this._excludeWithLayerMask;
  22344. },
  22345. /**
  22346. * Sets the layer id use to find what meshes are not impacted by the light.
  22347. * Inactive if 0
  22348. */
  22349. set: function (value) {
  22350. this._excludeWithLayerMask = value;
  22351. this._resyncMeshes();
  22352. },
  22353. enumerable: true,
  22354. configurable: true
  22355. });
  22356. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22357. /**
  22358. * Gets the layer id use to find what meshes are impacted by the light.
  22359. * Inactive if 0
  22360. */
  22361. get: function () {
  22362. return this._includeOnlyWithLayerMask;
  22363. },
  22364. /**
  22365. * Sets the layer id use to find what meshes are impacted by the light.
  22366. * Inactive if 0
  22367. */
  22368. set: function (value) {
  22369. this._includeOnlyWithLayerMask = value;
  22370. this._resyncMeshes();
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. Object.defineProperty(Light.prototype, "lightmapMode", {
  22376. /**
  22377. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22378. */
  22379. get: function () {
  22380. return this._lightmapMode;
  22381. },
  22382. /**
  22383. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22384. */
  22385. set: function (value) {
  22386. if (this._lightmapMode === value) {
  22387. return;
  22388. }
  22389. this._lightmapMode = value;
  22390. this._markMeshesAsLightDirty();
  22391. },
  22392. enumerable: true,
  22393. configurable: true
  22394. });
  22395. /**
  22396. * Returns the string "Light".
  22397. * @returns the class name
  22398. */
  22399. Light.prototype.getClassName = function () {
  22400. return "Light";
  22401. };
  22402. /**
  22403. * Converts the light information to a readable string for debug purpose.
  22404. * @param fullDetails Supports for multiple levels of logging within scene loading
  22405. * @returns the human readable light info
  22406. */
  22407. Light.prototype.toString = function (fullDetails) {
  22408. var ret = "Name: " + this.name;
  22409. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22410. if (this.animations) {
  22411. for (var i = 0; i < this.animations.length; i++) {
  22412. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22413. }
  22414. }
  22415. if (fullDetails) {
  22416. }
  22417. return ret;
  22418. };
  22419. /** @hidden */
  22420. Light.prototype._syncParentEnabledState = function () {
  22421. _super.prototype._syncParentEnabledState.call(this);
  22422. this._resyncMeshes();
  22423. };
  22424. /**
  22425. * Set the enabled state of this node.
  22426. * @param value - the new enabled state
  22427. */
  22428. Light.prototype.setEnabled = function (value) {
  22429. _super.prototype.setEnabled.call(this, value);
  22430. this._resyncMeshes();
  22431. };
  22432. /**
  22433. * Returns the Light associated shadow generator if any.
  22434. * @return the associated shadow generator.
  22435. */
  22436. Light.prototype.getShadowGenerator = function () {
  22437. return this._shadowGenerator;
  22438. };
  22439. /**
  22440. * Returns a Vector3, the absolute light position in the World.
  22441. * @returns the world space position of the light
  22442. */
  22443. Light.prototype.getAbsolutePosition = function () {
  22444. return BABYLON.Vector3.Zero();
  22445. };
  22446. /**
  22447. * Specifies if the light will affect the passed mesh.
  22448. * @param mesh The mesh to test against the light
  22449. * @return true the mesh is affected otherwise, false.
  22450. */
  22451. Light.prototype.canAffectMesh = function (mesh) {
  22452. if (!mesh) {
  22453. return true;
  22454. }
  22455. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22456. return false;
  22457. }
  22458. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22459. return false;
  22460. }
  22461. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22462. return false;
  22463. }
  22464. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22465. return false;
  22466. }
  22467. return true;
  22468. };
  22469. /**
  22470. * Sort function to order lights for rendering.
  22471. * @param a First Light object to compare to second.
  22472. * @param b Second Light object to compare first.
  22473. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22474. */
  22475. Light.CompareLightsPriority = function (a, b) {
  22476. //shadow-casting lights have priority over non-shadow-casting lights
  22477. //the renderPrioirty is a secondary sort criterion
  22478. if (a.shadowEnabled !== b.shadowEnabled) {
  22479. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22480. }
  22481. return b.renderPriority - a.renderPriority;
  22482. };
  22483. /**
  22484. * Releases resources associated with this node.
  22485. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22486. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22487. */
  22488. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22489. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22490. if (this._shadowGenerator) {
  22491. this._shadowGenerator.dispose();
  22492. this._shadowGenerator = null;
  22493. }
  22494. // Animations
  22495. this.getScene().stopAnimation(this);
  22496. // Remove from meshes
  22497. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22498. var mesh = _a[_i];
  22499. mesh._removeLightSource(this);
  22500. }
  22501. this._uniformBuffer.dispose();
  22502. // Remove from scene
  22503. this.getScene().removeLight(this);
  22504. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22505. };
  22506. /**
  22507. * Returns the light type ID (integer).
  22508. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22509. */
  22510. Light.prototype.getTypeID = function () {
  22511. return 0;
  22512. };
  22513. /**
  22514. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22515. * @returns the scaled intensity in intensity mode unit
  22516. */
  22517. Light.prototype.getScaledIntensity = function () {
  22518. return this._photometricScale * this.intensity;
  22519. };
  22520. /**
  22521. * Returns a new Light object, named "name", from the current one.
  22522. * @param name The name of the cloned light
  22523. * @returns the new created light
  22524. */
  22525. Light.prototype.clone = function (name) {
  22526. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22527. if (!constructor) {
  22528. return null;
  22529. }
  22530. return BABYLON.SerializationHelper.Clone(constructor, this);
  22531. };
  22532. /**
  22533. * Serializes the current light into a Serialization object.
  22534. * @returns the serialized object.
  22535. */
  22536. Light.prototype.serialize = function () {
  22537. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22538. // Type
  22539. serializationObject.type = this.getTypeID();
  22540. // Parent
  22541. if (this.parent) {
  22542. serializationObject.parentId = this.parent.id;
  22543. }
  22544. // Inclusion / exclusions
  22545. if (this.excludedMeshes.length > 0) {
  22546. serializationObject.excludedMeshesIds = [];
  22547. this.excludedMeshes.forEach(function (mesh) {
  22548. serializationObject.excludedMeshesIds.push(mesh.id);
  22549. });
  22550. }
  22551. if (this.includedOnlyMeshes.length > 0) {
  22552. serializationObject.includedOnlyMeshesIds = [];
  22553. this.includedOnlyMeshes.forEach(function (mesh) {
  22554. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22555. });
  22556. }
  22557. // Animations
  22558. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22559. serializationObject.ranges = this.serializeAnimationRanges();
  22560. return serializationObject;
  22561. };
  22562. /**
  22563. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22564. * This new light is named "name" and added to the passed scene.
  22565. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22566. * @param name The friendly name of the light
  22567. * @param scene The scene the new light will belong to
  22568. * @returns the constructor function
  22569. */
  22570. Light.GetConstructorFromName = function (type, name, scene) {
  22571. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22572. if (constructorFunc) {
  22573. return constructorFunc;
  22574. }
  22575. // Default to no light for none present once.
  22576. return null;
  22577. };
  22578. /**
  22579. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22580. * @param parsedLight The JSON representation of the light
  22581. * @param scene The scene to create the parsed light in
  22582. * @returns the created light after parsing
  22583. */
  22584. Light.Parse = function (parsedLight, scene) {
  22585. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22586. if (!constructor) {
  22587. return null;
  22588. }
  22589. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22590. // Inclusion / exclusions
  22591. if (parsedLight.excludedMeshesIds) {
  22592. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22593. }
  22594. if (parsedLight.includedOnlyMeshesIds) {
  22595. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22596. }
  22597. // Parent
  22598. if (parsedLight.parentId) {
  22599. light._waitingParentId = parsedLight.parentId;
  22600. }
  22601. // Animations
  22602. if (parsedLight.animations) {
  22603. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22604. var parsedAnimation = parsedLight.animations[animationIndex];
  22605. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22606. }
  22607. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22608. }
  22609. if (parsedLight.autoAnimate) {
  22610. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22611. }
  22612. return light;
  22613. };
  22614. Light.prototype._hookArrayForExcluded = function (array) {
  22615. var _this = this;
  22616. var oldPush = array.push;
  22617. array.push = function () {
  22618. var items = [];
  22619. for (var _i = 0; _i < arguments.length; _i++) {
  22620. items[_i] = arguments[_i];
  22621. }
  22622. var result = oldPush.apply(array, items);
  22623. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22624. var item = items_1[_a];
  22625. item._resyncLighSource(_this);
  22626. }
  22627. return result;
  22628. };
  22629. var oldSplice = array.splice;
  22630. array.splice = function (index, deleteCount) {
  22631. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22632. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22633. var item = deleted_1[_i];
  22634. item._resyncLighSource(_this);
  22635. }
  22636. return deleted;
  22637. };
  22638. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22639. var item = array_1[_i];
  22640. item._resyncLighSource(this);
  22641. }
  22642. };
  22643. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22644. var _this = this;
  22645. var oldPush = array.push;
  22646. array.push = function () {
  22647. var items = [];
  22648. for (var _i = 0; _i < arguments.length; _i++) {
  22649. items[_i] = arguments[_i];
  22650. }
  22651. var result = oldPush.apply(array, items);
  22652. _this._resyncMeshes();
  22653. return result;
  22654. };
  22655. var oldSplice = array.splice;
  22656. array.splice = function (index, deleteCount) {
  22657. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22658. _this._resyncMeshes();
  22659. return deleted;
  22660. };
  22661. this._resyncMeshes();
  22662. };
  22663. Light.prototype._resyncMeshes = function () {
  22664. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22665. var mesh = _a[_i];
  22666. mesh._resyncLighSource(this);
  22667. }
  22668. };
  22669. /**
  22670. * Forces the meshes to update their light related information in their rendering used effects
  22671. * @hidden Internal Use Only
  22672. */
  22673. Light.prototype._markMeshesAsLightDirty = function () {
  22674. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22675. var mesh = _a[_i];
  22676. if (mesh._lightSources.indexOf(this) !== -1) {
  22677. mesh._markSubMeshesAsLightDirty();
  22678. }
  22679. }
  22680. };
  22681. /**
  22682. * Recomputes the cached photometric scale if needed.
  22683. */
  22684. Light.prototype._computePhotometricScale = function () {
  22685. this._photometricScale = this._getPhotometricScale();
  22686. this.getScene().resetCachedMaterial();
  22687. };
  22688. /**
  22689. * Returns the Photometric Scale according to the light type and intensity mode.
  22690. */
  22691. Light.prototype._getPhotometricScale = function () {
  22692. var photometricScale = 0.0;
  22693. var lightTypeID = this.getTypeID();
  22694. //get photometric mode
  22695. var photometricMode = this.intensityMode;
  22696. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22697. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22698. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22699. }
  22700. else {
  22701. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22702. }
  22703. }
  22704. //compute photometric scale
  22705. switch (lightTypeID) {
  22706. case Light.LIGHTTYPEID_POINTLIGHT:
  22707. case Light.LIGHTTYPEID_SPOTLIGHT:
  22708. switch (photometricMode) {
  22709. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22710. photometricScale = 1.0 / (4.0 * Math.PI);
  22711. break;
  22712. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22713. photometricScale = 1.0;
  22714. break;
  22715. case Light.INTENSITYMODE_LUMINANCE:
  22716. photometricScale = this.radius * this.radius;
  22717. break;
  22718. }
  22719. break;
  22720. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22721. switch (photometricMode) {
  22722. case Light.INTENSITYMODE_ILLUMINANCE:
  22723. photometricScale = 1.0;
  22724. break;
  22725. case Light.INTENSITYMODE_LUMINANCE:
  22726. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22727. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22728. var apexAngleRadians = this.radius;
  22729. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22730. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22731. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22732. photometricScale = solidAngle;
  22733. break;
  22734. }
  22735. break;
  22736. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22737. // No fall off in hemisperic light.
  22738. photometricScale = 1.0;
  22739. break;
  22740. }
  22741. return photometricScale;
  22742. };
  22743. /**
  22744. * Reorder the light in the scene according to their defined priority.
  22745. * @hidden Internal Use Only
  22746. */
  22747. Light.prototype._reorderLightsInScene = function () {
  22748. var scene = this.getScene();
  22749. if (this._renderPriority != 0) {
  22750. scene.requireLightSorting = true;
  22751. }
  22752. this.getScene().sortLightsByPriority();
  22753. };
  22754. /**
  22755. * Falloff Default: light is falling off following the material specification:
  22756. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22757. */
  22758. Light.FALLOFF_DEFAULT = 0;
  22759. /**
  22760. * Falloff Physical: light is falling off following the inverse squared distance law.
  22761. */
  22762. Light.FALLOFF_PHYSICAL = 1;
  22763. /**
  22764. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22765. * to enhance interoperability with other engines.
  22766. */
  22767. Light.FALLOFF_GLTF = 2;
  22768. /**
  22769. * Falloff Standard: light is falling off like in the standard material
  22770. * to enhance interoperability with other materials.
  22771. */
  22772. Light.FALLOFF_STANDARD = 3;
  22773. //lightmapMode Consts
  22774. /**
  22775. * If every light affecting the material is in this lightmapMode,
  22776. * material.lightmapTexture adds or multiplies
  22777. * (depends on material.useLightmapAsShadowmap)
  22778. * after every other light calculations.
  22779. */
  22780. Light.LIGHTMAP_DEFAULT = 0;
  22781. /**
  22782. * material.lightmapTexture as only diffuse lighting from this light
  22783. * adds only specular lighting from this light
  22784. * adds dynamic shadows
  22785. */
  22786. Light.LIGHTMAP_SPECULAR = 1;
  22787. /**
  22788. * material.lightmapTexture as only lighting
  22789. * no light calculation from this light
  22790. * only adds dynamic shadows from this light
  22791. */
  22792. Light.LIGHTMAP_SHADOWSONLY = 2;
  22793. // Intensity Mode Consts
  22794. /**
  22795. * Each light type uses the default quantity according to its type:
  22796. * point/spot lights use luminous intensity
  22797. * directional lights use illuminance
  22798. */
  22799. Light.INTENSITYMODE_AUTOMATIC = 0;
  22800. /**
  22801. * lumen (lm)
  22802. */
  22803. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22804. /**
  22805. * candela (lm/sr)
  22806. */
  22807. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22808. /**
  22809. * lux (lm/m^2)
  22810. */
  22811. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22812. /**
  22813. * nit (cd/m^2)
  22814. */
  22815. Light.INTENSITYMODE_LUMINANCE = 4;
  22816. // Light types ids const.
  22817. /**
  22818. * Light type const id of the point light.
  22819. */
  22820. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22821. /**
  22822. * Light type const id of the directional light.
  22823. */
  22824. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22825. /**
  22826. * Light type const id of the spot light.
  22827. */
  22828. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22829. /**
  22830. * Light type const id of the hemispheric light.
  22831. */
  22832. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22833. __decorate([
  22834. BABYLON.serializeAsColor3()
  22835. ], Light.prototype, "diffuse", void 0);
  22836. __decorate([
  22837. BABYLON.serializeAsColor3()
  22838. ], Light.prototype, "specular", void 0);
  22839. __decorate([
  22840. BABYLON.serialize()
  22841. ], Light.prototype, "falloffType", void 0);
  22842. __decorate([
  22843. BABYLON.serialize()
  22844. ], Light.prototype, "intensity", void 0);
  22845. __decorate([
  22846. BABYLON.serialize()
  22847. ], Light.prototype, "range", null);
  22848. __decorate([
  22849. BABYLON.serialize()
  22850. ], Light.prototype, "intensityMode", null);
  22851. __decorate([
  22852. BABYLON.serialize()
  22853. ], Light.prototype, "radius", null);
  22854. __decorate([
  22855. BABYLON.serialize()
  22856. ], Light.prototype, "_renderPriority", void 0);
  22857. __decorate([
  22858. BABYLON.expandToProperty("_reorderLightsInScene")
  22859. ], Light.prototype, "renderPriority", void 0);
  22860. __decorate([
  22861. BABYLON.serialize("shadowEnabled")
  22862. ], Light.prototype, "_shadowEnabled", void 0);
  22863. __decorate([
  22864. BABYLON.serialize("excludeWithLayerMask")
  22865. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22866. __decorate([
  22867. BABYLON.serialize("includeOnlyWithLayerMask")
  22868. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22869. __decorate([
  22870. BABYLON.serialize("lightmapMode")
  22871. ], Light.prototype, "_lightmapMode", void 0);
  22872. return Light;
  22873. }(BABYLON.Node));
  22874. BABYLON.Light = Light;
  22875. })(BABYLON || (BABYLON = {}));
  22876. //# sourceMappingURL=babylon.light.js.map
  22877. var BABYLON;
  22878. (function (BABYLON) {
  22879. /**
  22880. * This is the base class of all the camera used in the application.
  22881. * @see http://doc.babylonjs.com/features/cameras
  22882. */
  22883. var Camera = /** @class */ (function (_super) {
  22884. __extends(Camera, _super);
  22885. /**
  22886. * Instantiates a new camera object.
  22887. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22888. * @see http://doc.babylonjs.com/features/cameras
  22889. * @param name Defines the name of the camera in the scene
  22890. * @param position Defines the position of the camera
  22891. * @param scene Defines the scene the camera belongs too
  22892. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22893. */
  22894. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22895. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22896. var _this = _super.call(this, name, scene) || this;
  22897. /**
  22898. * The vector the camera should consider as up.
  22899. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22900. */
  22901. _this.upVector = BABYLON.Vector3.Up();
  22902. /**
  22903. * Define the current limit on the left side for an orthographic camera
  22904. * In scene unit
  22905. */
  22906. _this.orthoLeft = null;
  22907. /**
  22908. * Define the current limit on the right side for an orthographic camera
  22909. * In scene unit
  22910. */
  22911. _this.orthoRight = null;
  22912. /**
  22913. * Define the current limit on the bottom side for an orthographic camera
  22914. * In scene unit
  22915. */
  22916. _this.orthoBottom = null;
  22917. /**
  22918. * Define the current limit on the top side for an orthographic camera
  22919. * In scene unit
  22920. */
  22921. _this.orthoTop = null;
  22922. /**
  22923. * Field Of View is set in Radians. (default is 0.8)
  22924. */
  22925. _this.fov = 0.8;
  22926. /**
  22927. * Define the minimum distance the camera can see from.
  22928. * This is important to note that the depth buffer are not infinite and the closer it starts
  22929. * the more your scene might encounter depth fighting issue.
  22930. */
  22931. _this.minZ = 1;
  22932. /**
  22933. * Define the maximum distance the camera can see to.
  22934. * This is important to note that the depth buffer are not infinite and the further it end
  22935. * the more your scene might encounter depth fighting issue.
  22936. */
  22937. _this.maxZ = 10000.0;
  22938. /**
  22939. * Define the default inertia of the camera.
  22940. * This helps giving a smooth feeling to the camera movement.
  22941. */
  22942. _this.inertia = 0.9;
  22943. /**
  22944. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22945. */
  22946. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22947. /**
  22948. * Define wether the camera is intermediate.
  22949. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22950. */
  22951. _this.isIntermediate = false;
  22952. /**
  22953. * Define the viewport of the camera.
  22954. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22955. */
  22956. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22957. /**
  22958. * Restricts the camera to viewing objects with the same layerMask.
  22959. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22960. */
  22961. _this.layerMask = 0x0FFFFFFF;
  22962. /**
  22963. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22964. */
  22965. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22966. /**
  22967. * Rig mode of the camera.
  22968. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22969. * This is normally controlled byt the camera themselves as internal use.
  22970. */
  22971. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22972. /**
  22973. * Defines the list of custom render target the camera should render to.
  22974. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22975. * else in the scene.
  22976. */
  22977. _this.customRenderTargets = new Array();
  22978. /**
  22979. * Observable triggered when the camera view matrix has changed.
  22980. */
  22981. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22982. /**
  22983. * Observable triggered when the camera Projection matrix has changed.
  22984. */
  22985. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22986. /**
  22987. * Observable triggered when the inputs have been processed.
  22988. */
  22989. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22990. /**
  22991. * Observable triggered when reset has been called and applied to the camera.
  22992. */
  22993. _this.onRestoreStateObservable = new BABYLON.Observable();
  22994. /** @hidden */
  22995. _this._rigCameras = new Array();
  22996. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22997. /** @hidden */
  22998. _this._skipRendering = false;
  22999. /** @hidden */
  23000. _this._projectionMatrix = new BABYLON.Matrix();
  23001. /** @hidden */
  23002. _this._postProcesses = new Array();
  23003. /** @hidden */
  23004. _this._activeMeshes = new BABYLON.SmartArray(256);
  23005. _this._globalPosition = BABYLON.Vector3.Zero();
  23006. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23007. _this._doNotComputeProjectionMatrix = false;
  23008. _this._transformMatrix = BABYLON.Matrix.Zero();
  23009. _this._refreshFrustumPlanes = true;
  23010. _this.getScene().addCamera(_this);
  23011. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23012. _this.getScene().activeCamera = _this;
  23013. }
  23014. _this.position = position;
  23015. return _this;
  23016. }
  23017. /**
  23018. * Store current camera state (fov, position, etc..)
  23019. * @returns the camera
  23020. */
  23021. Camera.prototype.storeState = function () {
  23022. this._stateStored = true;
  23023. this._storedFov = this.fov;
  23024. return this;
  23025. };
  23026. /**
  23027. * Restores the camera state values if it has been stored. You must call storeState() first
  23028. */
  23029. Camera.prototype._restoreStateValues = function () {
  23030. if (!this._stateStored) {
  23031. return false;
  23032. }
  23033. this.fov = this._storedFov;
  23034. return true;
  23035. };
  23036. /**
  23037. * Restored camera state. You must call storeState() first.
  23038. * @returns true if restored and false otherwise
  23039. */
  23040. Camera.prototype.restoreState = function () {
  23041. if (this._restoreStateValues()) {
  23042. this.onRestoreStateObservable.notifyObservers(this);
  23043. return true;
  23044. }
  23045. return false;
  23046. };
  23047. /**
  23048. * Gets the class name of the camera.
  23049. * @returns the class name
  23050. */
  23051. Camera.prototype.getClassName = function () {
  23052. return "Camera";
  23053. };
  23054. /**
  23055. * Gets a string representation of the camera usefull for debug purpose.
  23056. * @param fullDetails Defines that a more verboe level of logging is required
  23057. * @returns the string representation
  23058. */
  23059. Camera.prototype.toString = function (fullDetails) {
  23060. var ret = "Name: " + this.name;
  23061. ret += ", type: " + this.getClassName();
  23062. if (this.animations) {
  23063. for (var i = 0; i < this.animations.length; i++) {
  23064. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23065. }
  23066. }
  23067. if (fullDetails) {
  23068. }
  23069. return ret;
  23070. };
  23071. Object.defineProperty(Camera.prototype, "globalPosition", {
  23072. /**
  23073. * Gets the current world space position of the camera.
  23074. */
  23075. get: function () {
  23076. return this._globalPosition;
  23077. },
  23078. enumerable: true,
  23079. configurable: true
  23080. });
  23081. /**
  23082. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23083. * @returns the active meshe list
  23084. */
  23085. Camera.prototype.getActiveMeshes = function () {
  23086. return this._activeMeshes;
  23087. };
  23088. /**
  23089. * Check wether a mesh is part of the current active mesh list of the camera
  23090. * @param mesh Defines the mesh to check
  23091. * @returns true if active, false otherwise
  23092. */
  23093. Camera.prototype.isActiveMesh = function (mesh) {
  23094. return (this._activeMeshes.indexOf(mesh) !== -1);
  23095. };
  23096. /**
  23097. * Is this camera ready to be used/rendered
  23098. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23099. * @return true if the camera is ready
  23100. */
  23101. Camera.prototype.isReady = function (completeCheck) {
  23102. if (completeCheck === void 0) { completeCheck = false; }
  23103. if (completeCheck) {
  23104. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23105. var pp = _a[_i];
  23106. if (pp && !pp.isReady()) {
  23107. return false;
  23108. }
  23109. }
  23110. }
  23111. return _super.prototype.isReady.call(this, completeCheck);
  23112. };
  23113. /** @hidden */
  23114. Camera.prototype._initCache = function () {
  23115. _super.prototype._initCache.call(this);
  23116. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23117. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23118. this._cache.mode = undefined;
  23119. this._cache.minZ = undefined;
  23120. this._cache.maxZ = undefined;
  23121. this._cache.fov = undefined;
  23122. this._cache.fovMode = undefined;
  23123. this._cache.aspectRatio = undefined;
  23124. this._cache.orthoLeft = undefined;
  23125. this._cache.orthoRight = undefined;
  23126. this._cache.orthoBottom = undefined;
  23127. this._cache.orthoTop = undefined;
  23128. this._cache.renderWidth = undefined;
  23129. this._cache.renderHeight = undefined;
  23130. };
  23131. /** @hidden */
  23132. Camera.prototype._updateCache = function (ignoreParentClass) {
  23133. if (!ignoreParentClass) {
  23134. _super.prototype._updateCache.call(this);
  23135. }
  23136. this._cache.position.copyFrom(this.position);
  23137. this._cache.upVector.copyFrom(this.upVector);
  23138. };
  23139. /** @hidden */
  23140. Camera.prototype._isSynchronized = function () {
  23141. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23142. };
  23143. /** @hidden */
  23144. Camera.prototype._isSynchronizedViewMatrix = function () {
  23145. if (!_super.prototype._isSynchronized.call(this))
  23146. return false;
  23147. return this._cache.position.equals(this.position)
  23148. && this._cache.upVector.equals(this.upVector)
  23149. && this.isSynchronizedWithParent();
  23150. };
  23151. /** @hidden */
  23152. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23153. var check = this._cache.mode === this.mode
  23154. && this._cache.minZ === this.minZ
  23155. && this._cache.maxZ === this.maxZ;
  23156. if (!check) {
  23157. return false;
  23158. }
  23159. var engine = this.getEngine();
  23160. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23161. check = this._cache.fov === this.fov
  23162. && this._cache.fovMode === this.fovMode
  23163. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23164. }
  23165. else {
  23166. check = this._cache.orthoLeft === this.orthoLeft
  23167. && this._cache.orthoRight === this.orthoRight
  23168. && this._cache.orthoBottom === this.orthoBottom
  23169. && this._cache.orthoTop === this.orthoTop
  23170. && this._cache.renderWidth === engine.getRenderWidth()
  23171. && this._cache.renderHeight === engine.getRenderHeight();
  23172. }
  23173. return check;
  23174. };
  23175. /**
  23176. * Attach the input controls to a specific dom element to get the input from.
  23177. * @param element Defines the element the controls should be listened from
  23178. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23179. */
  23180. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23181. };
  23182. /**
  23183. * Detach the current controls from the specified dom element.
  23184. * @param element Defines the element to stop listening the inputs from
  23185. */
  23186. Camera.prototype.detachControl = function (element) {
  23187. };
  23188. /**
  23189. * Update the camera state according to the different inputs gathered during the frame.
  23190. */
  23191. Camera.prototype.update = function () {
  23192. this._checkInputs();
  23193. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23194. this._updateRigCameras();
  23195. }
  23196. };
  23197. /** @hidden */
  23198. Camera.prototype._checkInputs = function () {
  23199. this.onAfterCheckInputsObservable.notifyObservers(this);
  23200. };
  23201. Object.defineProperty(Camera.prototype, "rigCameras", {
  23202. /** @hidden */
  23203. get: function () {
  23204. return this._rigCameras;
  23205. },
  23206. enumerable: true,
  23207. configurable: true
  23208. });
  23209. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23210. /**
  23211. * Gets the post process used by the rig cameras
  23212. */
  23213. get: function () {
  23214. return this._rigPostProcess;
  23215. },
  23216. enumerable: true,
  23217. configurable: true
  23218. });
  23219. /**
  23220. * Internal, gets the first post proces.
  23221. * @returns the first post process to be run on this camera.
  23222. */
  23223. Camera.prototype._getFirstPostProcess = function () {
  23224. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23225. if (this._postProcesses[ppIndex] !== null) {
  23226. return this._postProcesses[ppIndex];
  23227. }
  23228. }
  23229. return null;
  23230. };
  23231. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23232. // invalidate framebuffer
  23233. var firstPostProcess = this._getFirstPostProcess();
  23234. if (firstPostProcess) {
  23235. firstPostProcess.markTextureDirty();
  23236. }
  23237. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23238. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23239. var cam = this._rigCameras[i];
  23240. var rigPostProcess = cam._rigPostProcess;
  23241. // for VR rig, there does not have to be a post process
  23242. if (rigPostProcess) {
  23243. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23244. if (isPass) {
  23245. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23246. cam.isIntermediate = this._postProcesses.length === 0;
  23247. }
  23248. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23249. rigPostProcess.markTextureDirty();
  23250. }
  23251. else {
  23252. cam._postProcesses = this._postProcesses.slice(0);
  23253. }
  23254. }
  23255. };
  23256. /**
  23257. * Attach a post process to the camera.
  23258. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23259. * @param postProcess The post process to attach to the camera
  23260. * @param insertAt The position of the post process in case several of them are in use in the scene
  23261. * @returns the position the post process has been inserted at
  23262. */
  23263. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23264. if (insertAt === void 0) { insertAt = null; }
  23265. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23266. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23267. return 0;
  23268. }
  23269. if (insertAt == null || insertAt < 0) {
  23270. this._postProcesses.push(postProcess);
  23271. }
  23272. else if (this._postProcesses[insertAt] === null) {
  23273. this._postProcesses[insertAt] = postProcess;
  23274. }
  23275. else {
  23276. this._postProcesses.splice(insertAt, 0, postProcess);
  23277. }
  23278. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23279. return this._postProcesses.indexOf(postProcess);
  23280. };
  23281. /**
  23282. * Detach a post process to the camera.
  23283. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23284. * @param postProcess The post process to detach from the camera
  23285. */
  23286. Camera.prototype.detachPostProcess = function (postProcess) {
  23287. var idx = this._postProcesses.indexOf(postProcess);
  23288. if (idx !== -1) {
  23289. this._postProcesses[idx] = null;
  23290. }
  23291. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23292. };
  23293. /**
  23294. * Gets the current world matrix of the camera
  23295. */
  23296. Camera.prototype.getWorldMatrix = function () {
  23297. if (this._isSynchronizedViewMatrix()) {
  23298. return this._worldMatrix;
  23299. }
  23300. // Getting the the view matrix will also compute the world matrix.
  23301. this.getViewMatrix();
  23302. return this._worldMatrix;
  23303. };
  23304. /** @hidden */
  23305. Camera.prototype._getViewMatrix = function () {
  23306. return BABYLON.Matrix.Identity();
  23307. };
  23308. /**
  23309. * Gets the current view matrix of the camera.
  23310. * @param force forces the camera to recompute the matrix without looking at the cached state
  23311. * @returns the view matrix
  23312. */
  23313. Camera.prototype.getViewMatrix = function (force) {
  23314. if (!force && this._isSynchronizedViewMatrix()) {
  23315. return this._computedViewMatrix;
  23316. }
  23317. this.updateCache();
  23318. this._computedViewMatrix = this._getViewMatrix();
  23319. this._currentRenderId = this.getScene().getRenderId();
  23320. this._childRenderId = this._currentRenderId;
  23321. this._refreshFrustumPlanes = true;
  23322. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23323. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23324. }
  23325. this.onViewMatrixChangedObservable.notifyObservers(this);
  23326. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23327. return this._computedViewMatrix;
  23328. };
  23329. /**
  23330. * Freeze the projection matrix.
  23331. * It will prevent the cache check of the camera projection compute and can speed up perf
  23332. * if no parameter of the camera are meant to change
  23333. * @param projection Defines manually a projection if necessary
  23334. */
  23335. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23336. this._doNotComputeProjectionMatrix = true;
  23337. if (projection !== undefined) {
  23338. this._projectionMatrix = projection;
  23339. }
  23340. };
  23341. ;
  23342. /**
  23343. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23344. */
  23345. Camera.prototype.unfreezeProjectionMatrix = function () {
  23346. this._doNotComputeProjectionMatrix = false;
  23347. };
  23348. ;
  23349. /**
  23350. * Gets the current projection matrix of the camera.
  23351. * @param force forces the camera to recompute the matrix without looking at the cached state
  23352. * @returns the projection matrix
  23353. */
  23354. Camera.prototype.getProjectionMatrix = function (force) {
  23355. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23356. return this._projectionMatrix;
  23357. }
  23358. // Cache
  23359. this._cache.mode = this.mode;
  23360. this._cache.minZ = this.minZ;
  23361. this._cache.maxZ = this.maxZ;
  23362. // Matrix
  23363. this._refreshFrustumPlanes = true;
  23364. var engine = this.getEngine();
  23365. var scene = this.getScene();
  23366. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23367. this._cache.fov = this.fov;
  23368. this._cache.fovMode = this.fovMode;
  23369. this._cache.aspectRatio = engine.getAspectRatio(this);
  23370. if (this.minZ <= 0) {
  23371. this.minZ = 0.1;
  23372. }
  23373. if (scene.useRightHandedSystem) {
  23374. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23375. }
  23376. else {
  23377. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23378. }
  23379. }
  23380. else {
  23381. var halfWidth = engine.getRenderWidth() / 2.0;
  23382. var halfHeight = engine.getRenderHeight() / 2.0;
  23383. if (scene.useRightHandedSystem) {
  23384. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23385. }
  23386. else {
  23387. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23388. }
  23389. this._cache.orthoLeft = this.orthoLeft;
  23390. this._cache.orthoRight = this.orthoRight;
  23391. this._cache.orthoBottom = this.orthoBottom;
  23392. this._cache.orthoTop = this.orthoTop;
  23393. this._cache.renderWidth = engine.getRenderWidth();
  23394. this._cache.renderHeight = engine.getRenderHeight();
  23395. }
  23396. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23397. return this._projectionMatrix;
  23398. };
  23399. /**
  23400. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23401. * @returns a Matrix
  23402. */
  23403. Camera.prototype.getTransformationMatrix = function () {
  23404. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23405. return this._transformMatrix;
  23406. };
  23407. Camera.prototype._updateFrustumPlanes = function () {
  23408. if (!this._refreshFrustumPlanes) {
  23409. return;
  23410. }
  23411. this.getTransformationMatrix();
  23412. if (!this._frustumPlanes) {
  23413. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23414. }
  23415. else {
  23416. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23417. }
  23418. this._refreshFrustumPlanes = false;
  23419. };
  23420. /**
  23421. * Checks if a cullable object (mesh...) is in the camera frustum
  23422. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23423. * @param target The object to check
  23424. * @returns true if the object is in frustum otherwise false
  23425. */
  23426. Camera.prototype.isInFrustum = function (target) {
  23427. this._updateFrustumPlanes();
  23428. return target.isInFrustum(this._frustumPlanes);
  23429. };
  23430. /**
  23431. * Checks if a cullable object (mesh...) is in the camera frustum
  23432. * Unlike isInFrustum this cheks the full bounding box
  23433. * @param target The object to check
  23434. * @returns true if the object is in frustum otherwise false
  23435. */
  23436. Camera.prototype.isCompletelyInFrustum = function (target) {
  23437. this._updateFrustumPlanes();
  23438. return target.isCompletelyInFrustum(this._frustumPlanes);
  23439. };
  23440. /**
  23441. * Gets a ray in the forward direction from the camera.
  23442. * @param length Defines the length of the ray to create
  23443. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23444. * @param origin Defines the start point of the ray which defaults to the camera position
  23445. * @returns the forward ray
  23446. */
  23447. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23448. if (length === void 0) { length = 100; }
  23449. if (!transform) {
  23450. transform = this.getWorldMatrix();
  23451. }
  23452. if (!origin) {
  23453. origin = this.position;
  23454. }
  23455. var forward = new BABYLON.Vector3(0, 0, 1);
  23456. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23457. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23458. return new BABYLON.Ray(origin, direction, length);
  23459. };
  23460. /**
  23461. * Releases resources associated with this node.
  23462. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23463. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23464. */
  23465. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23466. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23467. // Observables
  23468. this.onViewMatrixChangedObservable.clear();
  23469. this.onProjectionMatrixChangedObservable.clear();
  23470. this.onAfterCheckInputsObservable.clear();
  23471. this.onRestoreStateObservable.clear();
  23472. // Inputs
  23473. if (this.inputs) {
  23474. this.inputs.clear();
  23475. }
  23476. // Animations
  23477. this.getScene().stopAnimation(this);
  23478. // Remove from scene
  23479. this.getScene().removeCamera(this);
  23480. while (this._rigCameras.length > 0) {
  23481. var camera = this._rigCameras.pop();
  23482. if (camera) {
  23483. camera.dispose();
  23484. }
  23485. }
  23486. // Postprocesses
  23487. if (this._rigPostProcess) {
  23488. this._rigPostProcess.dispose(this);
  23489. this._rigPostProcess = null;
  23490. this._postProcesses = [];
  23491. }
  23492. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23493. this._rigPostProcess = null;
  23494. this._postProcesses = [];
  23495. }
  23496. else {
  23497. var i = this._postProcesses.length;
  23498. while (--i >= 0) {
  23499. var postProcess = this._postProcesses[i];
  23500. if (postProcess) {
  23501. postProcess.dispose(this);
  23502. }
  23503. }
  23504. }
  23505. // Render targets
  23506. var i = this.customRenderTargets.length;
  23507. while (--i >= 0) {
  23508. this.customRenderTargets[i].dispose();
  23509. }
  23510. this.customRenderTargets = [];
  23511. // Active Meshes
  23512. this._activeMeshes.dispose();
  23513. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23514. };
  23515. Object.defineProperty(Camera.prototype, "leftCamera", {
  23516. /**
  23517. * Gets the left camera of a rig setup in case of Rigged Camera
  23518. */
  23519. get: function () {
  23520. if (this._rigCameras.length < 1) {
  23521. return null;
  23522. }
  23523. return this._rigCameras[0];
  23524. },
  23525. enumerable: true,
  23526. configurable: true
  23527. });
  23528. Object.defineProperty(Camera.prototype, "rightCamera", {
  23529. /**
  23530. * Gets the right camera of a rig setup in case of Rigged Camera
  23531. */
  23532. get: function () {
  23533. if (this._rigCameras.length < 2) {
  23534. return null;
  23535. }
  23536. return this._rigCameras[1];
  23537. },
  23538. enumerable: true,
  23539. configurable: true
  23540. });
  23541. /**
  23542. * Gets the left camera target of a rig setup in case of Rigged Camera
  23543. * @returns the target position
  23544. */
  23545. Camera.prototype.getLeftTarget = function () {
  23546. if (this._rigCameras.length < 1) {
  23547. return null;
  23548. }
  23549. return this._rigCameras[0].getTarget();
  23550. };
  23551. /**
  23552. * Gets the right camera target of a rig setup in case of Rigged Camera
  23553. * @returns the target position
  23554. */
  23555. Camera.prototype.getRightTarget = function () {
  23556. if (this._rigCameras.length < 2) {
  23557. return null;
  23558. }
  23559. return this._rigCameras[1].getTarget();
  23560. };
  23561. /**
  23562. * @hidden
  23563. */
  23564. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23565. if (this.cameraRigMode === mode) {
  23566. return;
  23567. }
  23568. while (this._rigCameras.length > 0) {
  23569. var camera = this._rigCameras.pop();
  23570. if (camera) {
  23571. camera.dispose();
  23572. }
  23573. }
  23574. this.cameraRigMode = mode;
  23575. this._cameraRigParams = {};
  23576. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23577. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23578. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23579. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23580. // create the rig cameras, unless none
  23581. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23582. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23583. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23584. if (leftCamera && rightCamera) {
  23585. this._rigCameras.push(leftCamera);
  23586. this._rigCameras.push(rightCamera);
  23587. }
  23588. }
  23589. switch (this.cameraRigMode) {
  23590. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23591. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23592. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23593. break;
  23594. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23595. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23596. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23597. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23598. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23599. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23600. break;
  23601. case Camera.RIG_MODE_VR:
  23602. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23603. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23604. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23605. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23606. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23607. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23608. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23609. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23610. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23611. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23612. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23613. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23614. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23615. if (metrics.compensateDistortion) {
  23616. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23617. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23618. }
  23619. break;
  23620. case Camera.RIG_MODE_WEBVR:
  23621. if (rigParams.vrDisplay) {
  23622. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23623. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23624. //Left eye
  23625. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23626. this._rigCameras[0].setCameraRigParameter("left", true);
  23627. //leaving this for future reference
  23628. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23629. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23630. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23631. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23632. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23633. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23634. this._rigCameras[0].parent = this;
  23635. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23636. //Right eye
  23637. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23638. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23639. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23640. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23641. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23642. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23643. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23644. this._rigCameras[1].parent = this;
  23645. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23646. if (Camera.UseAlternateWebVRRendering) {
  23647. this._rigCameras[1]._skipRendering = true;
  23648. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23649. }
  23650. }
  23651. break;
  23652. }
  23653. this._cascadePostProcessesToRigCams();
  23654. this.update();
  23655. };
  23656. Camera.prototype._getVRProjectionMatrix = function () {
  23657. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23658. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23659. return this._projectionMatrix;
  23660. };
  23661. Camera.prototype._updateCameraRotationMatrix = function () {
  23662. //Here for WebVR
  23663. };
  23664. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23665. //Here for WebVR
  23666. };
  23667. /**
  23668. * This function MUST be overwritten by the different WebVR cameras available.
  23669. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23670. */
  23671. Camera.prototype._getWebVRProjectionMatrix = function () {
  23672. return BABYLON.Matrix.Identity();
  23673. };
  23674. /**
  23675. * This function MUST be overwritten by the different WebVR cameras available.
  23676. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23677. */
  23678. Camera.prototype._getWebVRViewMatrix = function () {
  23679. return BABYLON.Matrix.Identity();
  23680. };
  23681. /** @hidden */
  23682. Camera.prototype.setCameraRigParameter = function (name, value) {
  23683. if (!this._cameraRigParams) {
  23684. this._cameraRigParams = {};
  23685. }
  23686. this._cameraRigParams[name] = value;
  23687. //provisionnally:
  23688. if (name === "interaxialDistance") {
  23689. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23690. }
  23691. };
  23692. /**
  23693. * needs to be overridden by children so sub has required properties to be copied
  23694. * @hidden
  23695. */
  23696. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23697. return null;
  23698. };
  23699. /**
  23700. * May need to be overridden by children
  23701. * @hidden
  23702. */
  23703. Camera.prototype._updateRigCameras = function () {
  23704. for (var i = 0; i < this._rigCameras.length; i++) {
  23705. this._rigCameras[i].minZ = this.minZ;
  23706. this._rigCameras[i].maxZ = this.maxZ;
  23707. this._rigCameras[i].fov = this.fov;
  23708. }
  23709. // only update viewport when ANAGLYPH
  23710. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23711. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23712. }
  23713. };
  23714. /** @hidden */
  23715. Camera.prototype._setupInputs = function () {
  23716. };
  23717. /**
  23718. * Serialiaze the camera setup to a json represention
  23719. * @returns the JSON representation
  23720. */
  23721. Camera.prototype.serialize = function () {
  23722. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23723. // Type
  23724. serializationObject.type = this.getClassName();
  23725. // Parent
  23726. if (this.parent) {
  23727. serializationObject.parentId = this.parent.id;
  23728. }
  23729. if (this.inputs) {
  23730. this.inputs.serialize(serializationObject);
  23731. }
  23732. // Animations
  23733. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23734. serializationObject.ranges = this.serializeAnimationRanges();
  23735. return serializationObject;
  23736. };
  23737. /**
  23738. * Clones the current camera.
  23739. * @param name The cloned camera name
  23740. * @returns the cloned camera
  23741. */
  23742. Camera.prototype.clone = function (name) {
  23743. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23744. };
  23745. /**
  23746. * Gets the direction of the camera relative to a given local axis.
  23747. * @param localAxis Defines the reference axis to provide a relative direction.
  23748. * @return the direction
  23749. */
  23750. Camera.prototype.getDirection = function (localAxis) {
  23751. var result = BABYLON.Vector3.Zero();
  23752. this.getDirectionToRef(localAxis, result);
  23753. return result;
  23754. };
  23755. /**
  23756. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23757. * @param localAxis Defines the reference axis to provide a relative direction.
  23758. * @param result Defines the vector to store the result in
  23759. */
  23760. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23761. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23762. };
  23763. /**
  23764. * Gets a camera constructor for a given camera type
  23765. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23766. * @param name The name of the camera the result will be able to instantiate
  23767. * @param scene The scene the result will construct the camera in
  23768. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23769. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23770. * @returns a factory method to construc the camera
  23771. */
  23772. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23773. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23774. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23775. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23776. interaxial_distance: interaxial_distance,
  23777. isStereoscopicSideBySide: isStereoscopicSideBySide
  23778. });
  23779. if (constructorFunc) {
  23780. return constructorFunc;
  23781. }
  23782. // Default to universal camera
  23783. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23784. };
  23785. /**
  23786. * Compute the world matrix of the camera.
  23787. * @returns the camera workd matrix
  23788. */
  23789. Camera.prototype.computeWorldMatrix = function () {
  23790. return this.getWorldMatrix();
  23791. };
  23792. /**
  23793. * Parse a JSON and creates the camera from the parsed information
  23794. * @param parsedCamera The JSON to parse
  23795. * @param scene The scene to instantiate the camera in
  23796. * @returns the newly constructed camera
  23797. */
  23798. Camera.Parse = function (parsedCamera, scene) {
  23799. var type = parsedCamera.type;
  23800. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23801. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23802. // Parent
  23803. if (parsedCamera.parentId) {
  23804. camera._waitingParentId = parsedCamera.parentId;
  23805. }
  23806. //If camera has an input manager, let it parse inputs settings
  23807. if (camera.inputs) {
  23808. camera.inputs.parse(parsedCamera);
  23809. camera._setupInputs();
  23810. }
  23811. if (camera.setPosition) { // need to force position
  23812. camera.position.copyFromFloats(0, 0, 0);
  23813. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23814. }
  23815. // Target
  23816. if (parsedCamera.target) {
  23817. if (camera.setTarget) {
  23818. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23819. }
  23820. }
  23821. // Apply 3d rig, when found
  23822. if (parsedCamera.cameraRigMode) {
  23823. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23824. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23825. }
  23826. // Animations
  23827. if (parsedCamera.animations) {
  23828. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23829. var parsedAnimation = parsedCamera.animations[animationIndex];
  23830. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23831. }
  23832. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23833. }
  23834. if (parsedCamera.autoAnimate) {
  23835. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23836. }
  23837. return camera;
  23838. };
  23839. /**
  23840. * This is the default projection mode used by the cameras.
  23841. * It helps recreating a feeling of perspective and better appreciate depth.
  23842. * This is the best way to simulate real life cameras.
  23843. */
  23844. Camera.PERSPECTIVE_CAMERA = 0;
  23845. /**
  23846. * This helps creating camera with an orthographic mode.
  23847. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23848. */
  23849. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23850. /**
  23851. * This is the default FOV mode for perspective cameras.
  23852. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23853. */
  23854. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23855. /**
  23856. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23857. */
  23858. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23859. /**
  23860. * This specifies ther is no need for a camera rig.
  23861. * Basically only one eye is rendered corresponding to the camera.
  23862. */
  23863. Camera.RIG_MODE_NONE = 0;
  23864. /**
  23865. * Simulates a camera Rig with one blue eye and one red eye.
  23866. * This can be use with 3d blue and red glasses.
  23867. */
  23868. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23869. /**
  23870. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23871. */
  23872. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23873. /**
  23874. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23875. */
  23876. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23877. /**
  23878. * Defines that both eyes of the camera will be rendered over under each other.
  23879. */
  23880. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23881. /**
  23882. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23883. */
  23884. Camera.RIG_MODE_VR = 20;
  23885. /**
  23886. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23887. */
  23888. Camera.RIG_MODE_WEBVR = 21;
  23889. /**
  23890. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23891. */
  23892. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23893. /**
  23894. * @hidden
  23895. * Might be removed once multiview will be a thing
  23896. */
  23897. Camera.UseAlternateWebVRRendering = false;
  23898. __decorate([
  23899. BABYLON.serializeAsVector3()
  23900. ], Camera.prototype, "position", void 0);
  23901. __decorate([
  23902. BABYLON.serializeAsVector3()
  23903. ], Camera.prototype, "upVector", void 0);
  23904. __decorate([
  23905. BABYLON.serialize()
  23906. ], Camera.prototype, "orthoLeft", void 0);
  23907. __decorate([
  23908. BABYLON.serialize()
  23909. ], Camera.prototype, "orthoRight", void 0);
  23910. __decorate([
  23911. BABYLON.serialize()
  23912. ], Camera.prototype, "orthoBottom", void 0);
  23913. __decorate([
  23914. BABYLON.serialize()
  23915. ], Camera.prototype, "orthoTop", void 0);
  23916. __decorate([
  23917. BABYLON.serialize()
  23918. ], Camera.prototype, "fov", void 0);
  23919. __decorate([
  23920. BABYLON.serialize()
  23921. ], Camera.prototype, "minZ", void 0);
  23922. __decorate([
  23923. BABYLON.serialize()
  23924. ], Camera.prototype, "maxZ", void 0);
  23925. __decorate([
  23926. BABYLON.serialize()
  23927. ], Camera.prototype, "inertia", void 0);
  23928. __decorate([
  23929. BABYLON.serialize()
  23930. ], Camera.prototype, "mode", void 0);
  23931. __decorate([
  23932. BABYLON.serialize()
  23933. ], Camera.prototype, "layerMask", void 0);
  23934. __decorate([
  23935. BABYLON.serialize()
  23936. ], Camera.prototype, "fovMode", void 0);
  23937. __decorate([
  23938. BABYLON.serialize()
  23939. ], Camera.prototype, "cameraRigMode", void 0);
  23940. __decorate([
  23941. BABYLON.serialize()
  23942. ], Camera.prototype, "interaxialDistance", void 0);
  23943. __decorate([
  23944. BABYLON.serialize()
  23945. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23946. return Camera;
  23947. }(BABYLON.Node));
  23948. BABYLON.Camera = Camera;
  23949. })(BABYLON || (BABYLON = {}));
  23950. //# sourceMappingURL=babylon.camera.js.map
  23951. var BABYLON;
  23952. (function (BABYLON) {
  23953. /**
  23954. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23955. * It is enable to manage the different groups as well as the different necessary sort functions.
  23956. * This should not be used directly aside of the few static configurations
  23957. */
  23958. var RenderingManager = /** @class */ (function () {
  23959. /**
  23960. * Instantiates a new rendering group for a particular scene
  23961. * @param scene Defines the scene the groups belongs to
  23962. */
  23963. function RenderingManager(scene) {
  23964. /**
  23965. * @hidden
  23966. */
  23967. this._useSceneAutoClearSetup = false;
  23968. this._renderingGroups = new Array();
  23969. this._autoClearDepthStencil = {};
  23970. this._customOpaqueSortCompareFn = {};
  23971. this._customAlphaTestSortCompareFn = {};
  23972. this._customTransparentSortCompareFn = {};
  23973. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23974. this._scene = scene;
  23975. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23976. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23977. }
  23978. }
  23979. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23980. if (depth === void 0) { depth = true; }
  23981. if (stencil === void 0) { stencil = true; }
  23982. if (this._depthStencilBufferAlreadyCleaned) {
  23983. return;
  23984. }
  23985. this._scene.getEngine().clear(null, false, depth, stencil);
  23986. this._depthStencilBufferAlreadyCleaned = true;
  23987. };
  23988. /**
  23989. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23990. * @hidden
  23991. */
  23992. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23993. // Update the observable context (not null as it only goes away on dispose)
  23994. var info = this._renderingGroupInfo;
  23995. info.scene = this._scene;
  23996. info.camera = this._scene.activeCamera;
  23997. // Dispatch sprites
  23998. if (this._scene.spriteManagers && renderSprites) {
  23999. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24000. var manager = this._scene.spriteManagers[index];
  24001. this.dispatchSprites(manager);
  24002. }
  24003. }
  24004. // Render
  24005. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24006. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24007. var renderingGroup = this._renderingGroups[index];
  24008. if (!renderingGroup)
  24009. continue;
  24010. var renderingGroupMask = Math.pow(2, index);
  24011. info.renderingGroupId = index;
  24012. // Before Observable
  24013. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24014. // Clear depth/stencil if needed
  24015. if (RenderingManager.AUTOCLEAR) {
  24016. var autoClear = this._useSceneAutoClearSetup ?
  24017. this._scene.getAutoClearDepthStencilSetup(index) :
  24018. this._autoClearDepthStencil[index];
  24019. if (autoClear && autoClear.autoClear) {
  24020. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24021. }
  24022. }
  24023. // Render
  24024. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24025. var step = _a[_i];
  24026. step.action(index);
  24027. }
  24028. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24029. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24030. var step = _c[_b];
  24031. step.action(index);
  24032. }
  24033. // After Observable
  24034. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24035. }
  24036. };
  24037. /**
  24038. * Resets the different information of the group to prepare a new frame
  24039. * @hidden
  24040. */
  24041. RenderingManager.prototype.reset = function () {
  24042. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24043. var renderingGroup = this._renderingGroups[index];
  24044. if (renderingGroup) {
  24045. renderingGroup.prepare();
  24046. }
  24047. }
  24048. };
  24049. /**
  24050. * Dispose and release the group and its associated resources.
  24051. * @hidden
  24052. */
  24053. RenderingManager.prototype.dispose = function () {
  24054. this.freeRenderingGroups();
  24055. this._renderingGroups.length = 0;
  24056. this._renderingGroupInfo = null;
  24057. };
  24058. /**
  24059. * Clear the info related to rendering groups preventing retention points during dispose.
  24060. */
  24061. RenderingManager.prototype.freeRenderingGroups = function () {
  24062. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24063. var renderingGroup = this._renderingGroups[index];
  24064. if (renderingGroup) {
  24065. renderingGroup.dispose();
  24066. }
  24067. }
  24068. };
  24069. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24070. if (this._renderingGroups[renderingGroupId] === undefined) {
  24071. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24072. }
  24073. };
  24074. /**
  24075. * Add a sprite manager to the rendering manager in order to render it this frame.
  24076. * @param spriteManager Define the sprite manager to render
  24077. */
  24078. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24079. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24080. this._prepareRenderingGroup(renderingGroupId);
  24081. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24082. };
  24083. /**
  24084. * Add a particle system to the rendering manager in order to render it this frame.
  24085. * @param particleSystem Define the particle system to render
  24086. */
  24087. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24088. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24089. this._prepareRenderingGroup(renderingGroupId);
  24090. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24091. };
  24092. /**
  24093. * Add a submesh to the manager in order to render it this frame
  24094. * @param subMesh The submesh to dispatch
  24095. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24096. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24097. */
  24098. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24099. if (mesh === undefined) {
  24100. mesh = subMesh.getMesh();
  24101. }
  24102. var renderingGroupId = mesh.renderingGroupId || 0;
  24103. this._prepareRenderingGroup(renderingGroupId);
  24104. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24105. };
  24106. /**
  24107. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24108. * This allowed control for front to back rendering or reversly depending of the special needs.
  24109. *
  24110. * @param renderingGroupId The rendering group id corresponding to its index
  24111. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24112. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24113. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24114. */
  24115. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24116. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24117. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24118. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24119. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24120. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24121. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24122. if (this._renderingGroups[renderingGroupId]) {
  24123. var group = this._renderingGroups[renderingGroupId];
  24124. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24125. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24126. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24127. }
  24128. };
  24129. /**
  24130. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24131. *
  24132. * @param renderingGroupId The rendering group id corresponding to its index
  24133. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24134. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24135. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24136. */
  24137. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24138. if (depth === void 0) { depth = true; }
  24139. if (stencil === void 0) { stencil = true; }
  24140. this._autoClearDepthStencil[renderingGroupId] = {
  24141. autoClear: autoClearDepthStencil,
  24142. depth: depth,
  24143. stencil: stencil
  24144. };
  24145. };
  24146. /**
  24147. * Gets the current auto clear configuration for one rendering group of the rendering
  24148. * manager.
  24149. * @param index the rendering group index to get the information for
  24150. * @returns The auto clear setup for the requested rendering group
  24151. */
  24152. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24153. return this._autoClearDepthStencil[index];
  24154. };
  24155. /**
  24156. * The max id used for rendering groups (not included)
  24157. */
  24158. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24159. /**
  24160. * The min id used for rendering groups (included)
  24161. */
  24162. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24163. /**
  24164. * Used to globally prevent autoclearing scenes.
  24165. */
  24166. RenderingManager.AUTOCLEAR = true;
  24167. return RenderingManager;
  24168. }());
  24169. BABYLON.RenderingManager = RenderingManager;
  24170. })(BABYLON || (BABYLON = {}));
  24171. //# sourceMappingURL=babylon.renderingManager.js.map
  24172. var BABYLON;
  24173. (function (BABYLON) {
  24174. /**
  24175. * This represents the object necessary to create a rendering group.
  24176. * This is exclusively used and created by the rendering manager.
  24177. * To modify the behavior, you use the available helpers in your scene or meshes.
  24178. * @hidden
  24179. */
  24180. var RenderingGroup = /** @class */ (function () {
  24181. /**
  24182. * Creates a new rendering group.
  24183. * @param index The rendering group index
  24184. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24185. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24186. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24187. */
  24188. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24189. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24190. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24191. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24192. this.index = index;
  24193. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24194. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24195. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24196. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24197. this._particleSystems = new BABYLON.SmartArray(256);
  24198. this._spriteManagers = new BABYLON.SmartArray(256);
  24199. this._edgesRenderers = new BABYLON.SmartArray(16);
  24200. this._scene = scene;
  24201. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24202. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24203. this.transparentSortCompareFn = transparentSortCompareFn;
  24204. }
  24205. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24206. /**
  24207. * Set the opaque sort comparison function.
  24208. * If null the sub meshes will be render in the order they were created
  24209. */
  24210. set: function (value) {
  24211. this._opaqueSortCompareFn = value;
  24212. if (value) {
  24213. this._renderOpaque = this.renderOpaqueSorted;
  24214. }
  24215. else {
  24216. this._renderOpaque = RenderingGroup.renderUnsorted;
  24217. }
  24218. },
  24219. enumerable: true,
  24220. configurable: true
  24221. });
  24222. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24223. /**
  24224. * Set the alpha test sort comparison function.
  24225. * If null the sub meshes will be render in the order they were created
  24226. */
  24227. set: function (value) {
  24228. this._alphaTestSortCompareFn = value;
  24229. if (value) {
  24230. this._renderAlphaTest = this.renderAlphaTestSorted;
  24231. }
  24232. else {
  24233. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24234. }
  24235. },
  24236. enumerable: true,
  24237. configurable: true
  24238. });
  24239. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24240. /**
  24241. * Set the transparent sort comparison function.
  24242. * If null the sub meshes will be render in the order they were created
  24243. */
  24244. set: function (value) {
  24245. if (value) {
  24246. this._transparentSortCompareFn = value;
  24247. }
  24248. else {
  24249. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24250. }
  24251. this._renderTransparent = this.renderTransparentSorted;
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. /**
  24257. * Render all the sub meshes contained in the group.
  24258. * @param customRenderFunction Used to override the default render behaviour of the group.
  24259. * @returns true if rendered some submeshes.
  24260. */
  24261. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24262. if (customRenderFunction) {
  24263. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24264. return;
  24265. }
  24266. var engine = this._scene.getEngine();
  24267. // Depth only
  24268. if (this._depthOnlySubMeshes.length !== 0) {
  24269. engine.setColorWrite(false);
  24270. this._renderAlphaTest(this._depthOnlySubMeshes);
  24271. engine.setColorWrite(true);
  24272. }
  24273. // Opaque
  24274. if (this._opaqueSubMeshes.length !== 0) {
  24275. this._renderOpaque(this._opaqueSubMeshes);
  24276. }
  24277. // Alpha test
  24278. if (this._alphaTestSubMeshes.length !== 0) {
  24279. this._renderAlphaTest(this._alphaTestSubMeshes);
  24280. }
  24281. var stencilState = engine.getStencilBuffer();
  24282. engine.setStencilBuffer(false);
  24283. // Sprites
  24284. if (renderSprites) {
  24285. this._renderSprites();
  24286. }
  24287. // Particles
  24288. if (renderParticles) {
  24289. this._renderParticles(activeMeshes);
  24290. }
  24291. if (this.onBeforeTransparentRendering) {
  24292. this.onBeforeTransparentRendering();
  24293. }
  24294. // Transparent
  24295. if (this._transparentSubMeshes.length !== 0) {
  24296. this._renderTransparent(this._transparentSubMeshes);
  24297. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24298. }
  24299. // Set back stencil to false in case it changes before the edge renderer.
  24300. engine.setStencilBuffer(false);
  24301. // Edges
  24302. if (this._edgesRenderers.length) {
  24303. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24304. this._edgesRenderers.data[edgesRendererIndex].render();
  24305. }
  24306. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24307. }
  24308. // Restore Stencil state.
  24309. engine.setStencilBuffer(stencilState);
  24310. };
  24311. /**
  24312. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24313. * @param subMeshes The submeshes to render
  24314. */
  24315. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24316. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24317. };
  24318. /**
  24319. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24320. * @param subMeshes The submeshes to render
  24321. */
  24322. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24323. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24324. };
  24325. /**
  24326. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24327. * @param subMeshes The submeshes to render
  24328. */
  24329. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24330. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24331. };
  24332. /**
  24333. * Renders the submeshes in a specified order.
  24334. * @param subMeshes The submeshes to sort before render
  24335. * @param sortCompareFn The comparison function use to sort
  24336. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24337. * @param transparent Specifies to activate blending if true
  24338. */
  24339. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24340. var subIndex = 0;
  24341. var subMesh;
  24342. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24343. for (; subIndex < subMeshes.length; subIndex++) {
  24344. subMesh = subMeshes.data[subIndex];
  24345. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24346. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24347. }
  24348. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24349. if (sortCompareFn) {
  24350. sortedArray.sort(sortCompareFn);
  24351. }
  24352. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24353. subMesh = sortedArray[subIndex];
  24354. if (transparent) {
  24355. var material = subMesh.getMaterial();
  24356. if (material && material.needDepthPrePass) {
  24357. var engine = material.getScene().getEngine();
  24358. engine.setColorWrite(false);
  24359. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24360. subMesh.render(false);
  24361. engine.setColorWrite(true);
  24362. }
  24363. }
  24364. subMesh.render(transparent);
  24365. }
  24366. };
  24367. /**
  24368. * Renders the submeshes in the order they were dispatched (no sort applied).
  24369. * @param subMeshes The submeshes to render
  24370. */
  24371. RenderingGroup.renderUnsorted = function (subMeshes) {
  24372. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24373. var submesh = subMeshes.data[subIndex];
  24374. submesh.render(false);
  24375. }
  24376. };
  24377. /**
  24378. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24379. * are rendered back to front if in the same alpha index.
  24380. *
  24381. * @param a The first submesh
  24382. * @param b The second submesh
  24383. * @returns The result of the comparison
  24384. */
  24385. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24386. // Alpha index first
  24387. if (a._alphaIndex > b._alphaIndex) {
  24388. return 1;
  24389. }
  24390. if (a._alphaIndex < b._alphaIndex) {
  24391. return -1;
  24392. }
  24393. // Then distance to camera
  24394. return RenderingGroup.backToFrontSortCompare(a, b);
  24395. };
  24396. /**
  24397. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24398. * are rendered back to front.
  24399. *
  24400. * @param a The first submesh
  24401. * @param b The second submesh
  24402. * @returns The result of the comparison
  24403. */
  24404. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24405. // Then distance to camera
  24406. if (a._distanceToCamera < b._distanceToCamera) {
  24407. return 1;
  24408. }
  24409. if (a._distanceToCamera > b._distanceToCamera) {
  24410. return -1;
  24411. }
  24412. return 0;
  24413. };
  24414. /**
  24415. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24416. * are rendered front to back (prevent overdraw).
  24417. *
  24418. * @param a The first submesh
  24419. * @param b The second submesh
  24420. * @returns The result of the comparison
  24421. */
  24422. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24423. // Then distance to camera
  24424. if (a._distanceToCamera < b._distanceToCamera) {
  24425. return -1;
  24426. }
  24427. if (a._distanceToCamera > b._distanceToCamera) {
  24428. return 1;
  24429. }
  24430. return 0;
  24431. };
  24432. /**
  24433. * Resets the different lists of submeshes to prepare a new frame.
  24434. */
  24435. RenderingGroup.prototype.prepare = function () {
  24436. this._opaqueSubMeshes.reset();
  24437. this._transparentSubMeshes.reset();
  24438. this._alphaTestSubMeshes.reset();
  24439. this._depthOnlySubMeshes.reset();
  24440. this._particleSystems.reset();
  24441. this._spriteManagers.reset();
  24442. this._edgesRenderers.reset();
  24443. };
  24444. RenderingGroup.prototype.dispose = function () {
  24445. this._opaqueSubMeshes.dispose();
  24446. this._transparentSubMeshes.dispose();
  24447. this._alphaTestSubMeshes.dispose();
  24448. this._depthOnlySubMeshes.dispose();
  24449. this._particleSystems.dispose();
  24450. this._spriteManagers.dispose();
  24451. this._edgesRenderers.dispose();
  24452. };
  24453. /**
  24454. * Inserts the submesh in its correct queue depending on its material.
  24455. * @param subMesh The submesh to dispatch
  24456. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24457. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24458. */
  24459. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24460. // Get mesh and materials if not provided
  24461. if (mesh === undefined) {
  24462. mesh = subMesh.getMesh();
  24463. }
  24464. if (material === undefined) {
  24465. material = subMesh.getMaterial();
  24466. }
  24467. if (material === null || material === undefined) {
  24468. return;
  24469. }
  24470. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24471. this._transparentSubMeshes.push(subMesh);
  24472. }
  24473. else if (material.needAlphaTesting()) { // Alpha test
  24474. if (material.needDepthPrePass) {
  24475. this._depthOnlySubMeshes.push(subMesh);
  24476. }
  24477. this._alphaTestSubMeshes.push(subMesh);
  24478. }
  24479. else {
  24480. if (material.needDepthPrePass) {
  24481. this._depthOnlySubMeshes.push(subMesh);
  24482. }
  24483. this._opaqueSubMeshes.push(subMesh); // Opaque
  24484. }
  24485. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24486. this._edgesRenderers.push(mesh._edgesRenderer);
  24487. }
  24488. };
  24489. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24490. this._spriteManagers.push(spriteManager);
  24491. };
  24492. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24493. this._particleSystems.push(particleSystem);
  24494. };
  24495. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24496. if (this._particleSystems.length === 0) {
  24497. return;
  24498. }
  24499. // Particles
  24500. var activeCamera = this._scene.activeCamera;
  24501. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24502. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24503. var particleSystem = this._particleSystems.data[particleIndex];
  24504. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24505. continue;
  24506. }
  24507. var emitter = particleSystem.emitter;
  24508. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24509. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24510. }
  24511. }
  24512. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24513. };
  24514. RenderingGroup.prototype._renderSprites = function () {
  24515. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24516. return;
  24517. }
  24518. // Sprites
  24519. var activeCamera = this._scene.activeCamera;
  24520. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24521. for (var id = 0; id < this._spriteManagers.length; id++) {
  24522. var spriteManager = this._spriteManagers.data[id];
  24523. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24524. spriteManager.render();
  24525. }
  24526. }
  24527. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24528. };
  24529. return RenderingGroup;
  24530. }());
  24531. BABYLON.RenderingGroup = RenderingGroup;
  24532. })(BABYLON || (BABYLON = {}));
  24533. //# sourceMappingURL=babylon.renderingGroup.js.map
  24534. var BABYLON;
  24535. (function (BABYLON) {
  24536. /**
  24537. * Groups all the scene component constants in one place to ease maintenance.
  24538. * @hidden
  24539. */
  24540. var SceneComponentConstants = /** @class */ (function () {
  24541. function SceneComponentConstants() {
  24542. }
  24543. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24544. SceneComponentConstants.NAME_LAYER = "Layer";
  24545. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24546. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24547. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24548. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24549. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24550. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24551. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24552. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24553. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24554. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24555. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24556. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24557. SceneComponentConstants.NAME_OCTREE = "Octree";
  24558. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24559. SceneComponentConstants.NAME_AUDIO = "Audio";
  24560. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24561. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24562. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24563. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24564. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24565. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24566. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24567. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24568. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24569. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24570. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24571. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24572. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24573. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24574. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24575. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24576. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24577. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24578. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24579. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24580. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24581. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24582. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24583. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24584. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24585. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24586. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24587. return SceneComponentConstants;
  24588. }());
  24589. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24590. /**
  24591. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24592. * @hidden
  24593. */
  24594. var Stage = /** @class */ (function (_super) {
  24595. __extends(Stage, _super);
  24596. /**
  24597. * Hide ctor from the rest of the world.
  24598. * @param items The items to add.
  24599. */
  24600. function Stage(items) {
  24601. return _super.apply(this, items) || this;
  24602. }
  24603. /**
  24604. * Creates a new Stage.
  24605. * @returns A new instance of a Stage
  24606. */
  24607. Stage.Create = function () {
  24608. return Object.create(Stage.prototype);
  24609. };
  24610. /**
  24611. * Registers a step in an ordered way in the targeted stage.
  24612. * @param index Defines the position to register the step in
  24613. * @param component Defines the component attached to the step
  24614. * @param action Defines the action to launch during the step
  24615. */
  24616. Stage.prototype.registerStep = function (index, component, action) {
  24617. var i = 0;
  24618. var maxIndex = Number.MAX_VALUE;
  24619. for (; i < this.length && i < maxIndex; i++) {
  24620. var step = this[i];
  24621. maxIndex = step.index;
  24622. }
  24623. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24624. };
  24625. /**
  24626. * Clears all the steps from the stage.
  24627. */
  24628. Stage.prototype.clear = function () {
  24629. this.length = 0;
  24630. };
  24631. return Stage;
  24632. }(Array));
  24633. BABYLON.Stage = Stage;
  24634. })(BABYLON || (BABYLON = {}));
  24635. //# sourceMappingURL=babylon.sceneComponent.js.map
  24636. var BABYLON;
  24637. (function (BABYLON) {
  24638. /**
  24639. * Base class of the scene acting as a container for the different elements composing a scene.
  24640. * This class is dynamically extended by the different components of the scene increasing
  24641. * flexibility and reducing coupling
  24642. */
  24643. var AbstractScene = /** @class */ (function () {
  24644. function AbstractScene() {
  24645. /**
  24646. * Gets the list of root nodes (ie. nodes with no parent)
  24647. */
  24648. this.rootNodes = new Array();
  24649. /** All of the cameras added to this scene
  24650. * @see http://doc.babylonjs.com/babylon101/cameras
  24651. */
  24652. this.cameras = new Array();
  24653. /**
  24654. * All of the lights added to this scene
  24655. * @see http://doc.babylonjs.com/babylon101/lights
  24656. */
  24657. this.lights = new Array();
  24658. /**
  24659. * All of the (abstract) meshes added to this scene
  24660. */
  24661. this.meshes = new Array();
  24662. /**
  24663. * The list of skeletons added to the scene
  24664. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24665. */
  24666. this.skeletons = new Array();
  24667. /**
  24668. * All of the particle systems added to this scene
  24669. * @see http://doc.babylonjs.com/babylon101/particles
  24670. */
  24671. this.particleSystems = new Array();
  24672. /**
  24673. * Gets a list of Animations associated with the scene
  24674. */
  24675. this.animations = [];
  24676. /**
  24677. * All of the animation groups added to this scene
  24678. * @see http://doc.babylonjs.com/how_to/group
  24679. */
  24680. this.animationGroups = new Array();
  24681. /**
  24682. * All of the multi-materials added to this scene
  24683. * @see http://doc.babylonjs.com/how_to/multi_materials
  24684. */
  24685. this.multiMaterials = new Array();
  24686. /**
  24687. * All of the materials added to this scene
  24688. * @see http://doc.babylonjs.com/babylon101/materials
  24689. */
  24690. this.materials = new Array();
  24691. /**
  24692. * The list of morph target managers added to the scene
  24693. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24694. */
  24695. this.morphTargetManagers = new Array();
  24696. /**
  24697. * The list of geometries used in the scene.
  24698. */
  24699. this.geometries = new Array();
  24700. /**
  24701. * All of the tranform nodes added to this scene
  24702. * @see http://doc.babylonjs.com/how_to/transformnode
  24703. */
  24704. this.transformNodes = new Array();
  24705. /**
  24706. * ActionManagers available on the scene.
  24707. */
  24708. this.actionManagers = new Array();
  24709. /**
  24710. * Textures to keep.
  24711. */
  24712. this.textures = new Array();
  24713. }
  24714. /**
  24715. * Adds a parser in the list of available ones
  24716. * @param name Defines the name of the parser
  24717. * @param parser Defines the parser to add
  24718. */
  24719. AbstractScene.AddParser = function (name, parser) {
  24720. this._BabylonFileParsers[name] = parser;
  24721. };
  24722. /**
  24723. * Gets a general parser from the list of avaialble ones
  24724. * @param name Defines the name of the parser
  24725. * @returns the requested parser or null
  24726. */
  24727. AbstractScene.GetParser = function (name) {
  24728. if (this._BabylonFileParsers[name]) {
  24729. return this._BabylonFileParsers[name];
  24730. }
  24731. return null;
  24732. };
  24733. /**
  24734. * Adds n individual parser in the list of available ones
  24735. * @param name Defines the name of the parser
  24736. * @param parser Defines the parser to add
  24737. */
  24738. AbstractScene.AddIndividualParser = function (name, parser) {
  24739. this._IndividualBabylonFileParsers[name] = parser;
  24740. };
  24741. /**
  24742. * Gets an individual parser from the list of avaialble ones
  24743. * @param name Defines the name of the parser
  24744. * @returns the requested parser or null
  24745. */
  24746. AbstractScene.GetIndividualParser = function (name) {
  24747. if (this._IndividualBabylonFileParsers[name]) {
  24748. return this._IndividualBabylonFileParsers[name];
  24749. }
  24750. return null;
  24751. };
  24752. /**
  24753. * Parser json data and populate both a scene and its associated container object
  24754. * @param jsonData Defines the data to parse
  24755. * @param scene Defines the scene to parse the data for
  24756. * @param container Defines the container attached to the parsing sequence
  24757. * @param rootUrl Defines the root url of the data
  24758. */
  24759. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24760. for (var parserName in this._BabylonFileParsers) {
  24761. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24762. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24763. }
  24764. }
  24765. };
  24766. /**
  24767. * Stores the list of available parsers in the application.
  24768. */
  24769. AbstractScene._BabylonFileParsers = {};
  24770. /**
  24771. * Stores the list of available individual parsers in the application.
  24772. */
  24773. AbstractScene._IndividualBabylonFileParsers = {};
  24774. return AbstractScene;
  24775. }());
  24776. BABYLON.AbstractScene = AbstractScene;
  24777. })(BABYLON || (BABYLON = {}));
  24778. //# sourceMappingURL=babylon.abstractScene.js.map
  24779. var BABYLON;
  24780. (function (BABYLON) {
  24781. /** @hidden */
  24782. var ClickInfo = /** @class */ (function () {
  24783. function ClickInfo() {
  24784. this._singleClick = false;
  24785. this._doubleClick = false;
  24786. this._hasSwiped = false;
  24787. this._ignore = false;
  24788. }
  24789. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24790. get: function () {
  24791. return this._singleClick;
  24792. },
  24793. set: function (b) {
  24794. this._singleClick = b;
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24800. get: function () {
  24801. return this._doubleClick;
  24802. },
  24803. set: function (b) {
  24804. this._doubleClick = b;
  24805. },
  24806. enumerable: true,
  24807. configurable: true
  24808. });
  24809. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24810. get: function () {
  24811. return this._hasSwiped;
  24812. },
  24813. set: function (b) {
  24814. this._hasSwiped = b;
  24815. },
  24816. enumerable: true,
  24817. configurable: true
  24818. });
  24819. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24820. get: function () {
  24821. return this._ignore;
  24822. },
  24823. set: function (b) {
  24824. this._ignore = b;
  24825. },
  24826. enumerable: true,
  24827. configurable: true
  24828. });
  24829. return ClickInfo;
  24830. }());
  24831. /**
  24832. * This class is used by the onRenderingGroupObservable
  24833. */
  24834. var RenderingGroupInfo = /** @class */ (function () {
  24835. function RenderingGroupInfo() {
  24836. }
  24837. return RenderingGroupInfo;
  24838. }());
  24839. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24840. /**
  24841. * Represents a scene to be rendered by the engine.
  24842. * @see http://doc.babylonjs.com/features/scene
  24843. */
  24844. var Scene = /** @class */ (function (_super) {
  24845. __extends(Scene, _super);
  24846. /**
  24847. * Creates a new Scene
  24848. * @param engine defines the engine to use to render this scene
  24849. */
  24850. function Scene(engine) {
  24851. var _this = _super.call(this) || this;
  24852. // Members
  24853. /**
  24854. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24855. */
  24856. _this.autoClear = true;
  24857. /**
  24858. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24859. */
  24860. _this.autoClearDepthAndStencil = true;
  24861. /**
  24862. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24863. */
  24864. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24865. /**
  24866. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24867. */
  24868. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24869. _this._forceWireframe = false;
  24870. _this._forcePointsCloud = false;
  24871. /**
  24872. * Gets or sets a boolean indicating if animations are enabled
  24873. */
  24874. _this.animationsEnabled = true;
  24875. _this._animationPropertiesOverride = null;
  24876. /**
  24877. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24878. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24879. */
  24880. _this.useConstantAnimationDeltaTime = false;
  24881. /**
  24882. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24883. * Please note that it requires to run a ray cast through the scene on every frame
  24884. */
  24885. _this.constantlyUpdateMeshUnderPointer = false;
  24886. /**
  24887. * Defines the HTML cursor to use when hovering over interactive elements
  24888. */
  24889. _this.hoverCursor = "pointer";
  24890. /**
  24891. * Defines the HTML default cursor to use (empty by default)
  24892. */
  24893. _this.defaultCursor = "";
  24894. /**
  24895. * This is used to call preventDefault() on pointer down
  24896. * in order to block unwanted artifacts like system double clicks
  24897. */
  24898. _this.preventDefaultOnPointerDown = true;
  24899. // Metadata
  24900. /**
  24901. * Gets or sets user defined metadata
  24902. */
  24903. _this.metadata = null;
  24904. /**
  24905. * Use this array to add regular expressions used to disable offline support for specific urls
  24906. */
  24907. _this.disableOfflineSupportExceptionRules = new Array();
  24908. /**
  24909. * An event triggered when the scene is disposed.
  24910. */
  24911. _this.onDisposeObservable = new BABYLON.Observable();
  24912. _this._onDisposeObserver = null;
  24913. /**
  24914. * An event triggered before rendering the scene (right after animations and physics)
  24915. */
  24916. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24917. _this._onBeforeRenderObserver = null;
  24918. /**
  24919. * An event triggered after rendering the scene
  24920. */
  24921. _this.onAfterRenderObservable = new BABYLON.Observable();
  24922. _this._onAfterRenderObserver = null;
  24923. /**
  24924. * An event triggered before animating the scene
  24925. */
  24926. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24927. /**
  24928. * An event triggered after animations processing
  24929. */
  24930. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24931. /**
  24932. * An event triggered before draw calls are ready to be sent
  24933. */
  24934. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24935. /**
  24936. * An event triggered after draw calls have been sent
  24937. */
  24938. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24939. /**
  24940. * An event triggered when the scene is ready
  24941. */
  24942. _this.onReadyObservable = new BABYLON.Observable();
  24943. /**
  24944. * An event triggered before rendering a camera
  24945. */
  24946. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24947. _this._onBeforeCameraRenderObserver = null;
  24948. /**
  24949. * An event triggered after rendering a camera
  24950. */
  24951. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24952. _this._onAfterCameraRenderObserver = null;
  24953. /**
  24954. * An event triggered when active meshes evaluation is about to start
  24955. */
  24956. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24957. /**
  24958. * An event triggered when active meshes evaluation is done
  24959. */
  24960. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24961. /**
  24962. * An event triggered when particles rendering is about to start
  24963. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24964. */
  24965. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24966. /**
  24967. * An event triggered when particles rendering is done
  24968. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24969. */
  24970. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24971. /**
  24972. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24973. */
  24974. _this.onDataLoadedObservable = new BABYLON.Observable();
  24975. /**
  24976. * An event triggered when a camera is created
  24977. */
  24978. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24979. /**
  24980. * An event triggered when a camera is removed
  24981. */
  24982. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24983. /**
  24984. * An event triggered when a light is created
  24985. */
  24986. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24987. /**
  24988. * An event triggered when a light is removed
  24989. */
  24990. _this.onLightRemovedObservable = new BABYLON.Observable();
  24991. /**
  24992. * An event triggered when a geometry is created
  24993. */
  24994. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24995. /**
  24996. * An event triggered when a geometry is removed
  24997. */
  24998. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24999. /**
  25000. * An event triggered when a transform node is created
  25001. */
  25002. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25003. /**
  25004. * An event triggered when a transform node is removed
  25005. */
  25006. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25007. /**
  25008. * An event triggered when a mesh is created
  25009. */
  25010. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25011. /**
  25012. * An event triggered when a mesh is removed
  25013. */
  25014. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25015. /**
  25016. * An event triggered when a material is created
  25017. */
  25018. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25019. /**
  25020. * An event triggered when a material is removed
  25021. */
  25022. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25023. /**
  25024. * An event triggered when a texture is created
  25025. */
  25026. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25027. /**
  25028. * An event triggered when a texture is removed
  25029. */
  25030. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25031. /**
  25032. * An event triggered when render targets are about to be rendered
  25033. * Can happen multiple times per frame.
  25034. */
  25035. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25036. /**
  25037. * An event triggered when render targets were rendered.
  25038. * Can happen multiple times per frame.
  25039. */
  25040. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25041. /**
  25042. * An event triggered before calculating deterministic simulation step
  25043. */
  25044. _this.onBeforeStepObservable = new BABYLON.Observable();
  25045. /**
  25046. * An event triggered after calculating deterministic simulation step
  25047. */
  25048. _this.onAfterStepObservable = new BABYLON.Observable();
  25049. /**
  25050. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25051. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25052. * 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)
  25053. */
  25054. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25055. /**
  25056. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25057. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25058. * 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)
  25059. */
  25060. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25061. /**
  25062. * This Observable will when a mesh has been imported into the scene.
  25063. */
  25064. _this.onMeshImportedObservable = new BABYLON.Observable();
  25065. // Animations
  25066. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25067. /**
  25068. * 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).
  25069. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25070. */
  25071. _this.onPrePointerObservable = new BABYLON.Observable();
  25072. /**
  25073. * Observable event triggered each time an input event is received from the rendering canvas
  25074. */
  25075. _this.onPointerObservable = new BABYLON.Observable();
  25076. _this._meshPickProceed = false;
  25077. _this._currentPickResult = null;
  25078. _this._previousPickResult = null;
  25079. _this._totalPointersPressed = 0;
  25080. _this._doubleClickOccured = false;
  25081. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25082. _this.cameraToUseForPointers = null;
  25083. _this._pointerX = 0;
  25084. _this._pointerY = 0;
  25085. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25086. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25087. _this._startingPointerTime = 0;
  25088. _this._previousStartingPointerTime = 0;
  25089. _this._pointerCaptures = {};
  25090. // Deterministic lockstep
  25091. _this._timeAccumulator = 0;
  25092. _this._currentStepId = 0;
  25093. _this._currentInternalStep = 0;
  25094. // Keyboard
  25095. /**
  25096. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25097. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25098. */
  25099. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25100. /**
  25101. * Observable event triggered each time an keyboard event is received from the hosting window
  25102. */
  25103. _this.onKeyboardObservable = new BABYLON.Observable();
  25104. // Coordinates system
  25105. _this._useRightHandedSystem = false;
  25106. // Fog
  25107. _this._fogEnabled = true;
  25108. _this._fogMode = Scene.FOGMODE_NONE;
  25109. /**
  25110. * Gets or sets the fog color to use
  25111. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25112. * (Default is Color3(0.2, 0.2, 0.3))
  25113. */
  25114. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25115. /**
  25116. * Gets or sets the fog density to use
  25117. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25118. * (Default is 0.1)
  25119. */
  25120. _this.fogDensity = 0.1;
  25121. /**
  25122. * Gets or sets the fog start distance to use
  25123. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25124. * (Default is 0)
  25125. */
  25126. _this.fogStart = 0;
  25127. /**
  25128. * Gets or sets the fog end distance to use
  25129. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25130. * (Default is 1000)
  25131. */
  25132. _this.fogEnd = 1000.0;
  25133. // Lights
  25134. _this._shadowsEnabled = true;
  25135. _this._lightsEnabled = true;
  25136. /** All of the active cameras added to this scene. */
  25137. _this.activeCameras = new Array();
  25138. // Textures
  25139. _this._texturesEnabled = true;
  25140. // Particles
  25141. /**
  25142. * Gets or sets a boolean indicating if particles are enabled on this scene
  25143. */
  25144. _this.particlesEnabled = true;
  25145. // Sprites
  25146. /**
  25147. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25148. */
  25149. _this.spritesEnabled = true;
  25150. // Skeletons
  25151. _this._skeletonsEnabled = true;
  25152. // Lens flares
  25153. /**
  25154. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25155. */
  25156. _this.lensFlaresEnabled = true;
  25157. // Collisions
  25158. /**
  25159. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25160. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25161. */
  25162. _this.collisionsEnabled = true;
  25163. /**
  25164. * Defines the gravity applied to this scene (used only for collisions)
  25165. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25166. */
  25167. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25168. // Postprocesses
  25169. /**
  25170. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25171. */
  25172. _this.postProcessesEnabled = true;
  25173. /**
  25174. * The list of postprocesses added to the scene
  25175. */
  25176. _this.postProcesses = new Array();
  25177. // Customs render targets
  25178. /**
  25179. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25180. */
  25181. _this.renderTargetsEnabled = true;
  25182. /**
  25183. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25184. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25185. */
  25186. _this.dumpNextRenderTargets = false;
  25187. /**
  25188. * The list of user defined render targets added to the scene
  25189. */
  25190. _this.customRenderTargets = new Array();
  25191. /**
  25192. * Gets the list of meshes imported to the scene through SceneLoader
  25193. */
  25194. _this.importedMeshesFiles = new Array();
  25195. // Probes
  25196. /**
  25197. * Gets or sets a boolean indicating if probes are enabled on this scene
  25198. */
  25199. _this.probesEnabled = true;
  25200. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25201. // Procedural textures
  25202. /**
  25203. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25204. */
  25205. _this.proceduralTexturesEnabled = true;
  25206. // Performance counters
  25207. _this._totalVertices = new BABYLON.PerfCounter();
  25208. /** @hidden */
  25209. _this._activeIndices = new BABYLON.PerfCounter();
  25210. /** @hidden */
  25211. _this._activeParticles = new BABYLON.PerfCounter();
  25212. /** @hidden */
  25213. _this._activeBones = new BABYLON.PerfCounter();
  25214. _this._animationTime = 0;
  25215. /**
  25216. * Gets or sets a general scale for animation speed
  25217. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25218. */
  25219. _this.animationTimeScale = 1;
  25220. _this._renderId = 0;
  25221. _this._frameId = 0;
  25222. _this._executeWhenReadyTimeoutId = -1;
  25223. _this._intermediateRendering = false;
  25224. _this._viewUpdateFlag = -1;
  25225. _this._projectionUpdateFlag = -1;
  25226. _this._alternateViewUpdateFlag = -1;
  25227. _this._alternateProjectionUpdateFlag = -1;
  25228. /** @hidden */
  25229. _this._toBeDisposed = new Array(256);
  25230. _this._activeRequests = new Array();
  25231. _this._pendingData = new Array();
  25232. _this._isDisposed = false;
  25233. /**
  25234. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25235. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25236. */
  25237. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25238. _this._activeMeshes = new BABYLON.SmartArray(256);
  25239. _this._processedMaterials = new BABYLON.SmartArray(256);
  25240. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25241. /** @hidden */
  25242. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25243. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25244. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25245. /** @hidden */
  25246. _this._activeAnimatables = new Array();
  25247. _this._transformMatrix = BABYLON.Matrix.Zero();
  25248. _this._useAlternateCameraConfiguration = false;
  25249. _this._alternateRendering = false;
  25250. /**
  25251. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25252. * This is useful if there are more lights that the maximum simulteanous authorized
  25253. */
  25254. _this.requireLightSorting = false;
  25255. /**
  25256. * @hidden
  25257. * Backing store of defined scene components.
  25258. */
  25259. _this._components = [];
  25260. /**
  25261. * @hidden
  25262. * Backing store of defined scene components.
  25263. */
  25264. _this._serializableComponents = [];
  25265. /**
  25266. * List of components to register on the next registration step.
  25267. */
  25268. _this._transientComponents = [];
  25269. /**
  25270. * @hidden
  25271. * Defines the actions happening before camera updates.
  25272. */
  25273. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25274. /**
  25275. * @hidden
  25276. * Defines the actions happening before clear the canvas.
  25277. */
  25278. _this._beforeClearStage = BABYLON.Stage.Create();
  25279. /**
  25280. * @hidden
  25281. * Defines the actions when collecting render targets for the frame.
  25282. */
  25283. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25284. /**
  25285. * @hidden
  25286. * Defines the actions happening for one camera in the frame.
  25287. */
  25288. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25289. /**
  25290. * @hidden
  25291. * Defines the actions happening during the per mesh ready checks.
  25292. */
  25293. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25294. /**
  25295. * @hidden
  25296. * Defines the actions happening before evaluate active mesh checks.
  25297. */
  25298. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25299. /**
  25300. * @hidden
  25301. * Defines the actions happening during the evaluate sub mesh checks.
  25302. */
  25303. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25304. /**
  25305. * @hidden
  25306. * Defines the actions happening during the active mesh stage.
  25307. */
  25308. _this._activeMeshStage = BABYLON.Stage.Create();
  25309. /**
  25310. * @hidden
  25311. * Defines the actions happening during the per camera render target step.
  25312. */
  25313. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25314. /**
  25315. * @hidden
  25316. * Defines the actions happening just before the active camera is drawing.
  25317. */
  25318. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25319. /**
  25320. * @hidden
  25321. * Defines the actions happening just before a rendering group is drawing.
  25322. */
  25323. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25324. /**
  25325. * @hidden
  25326. * Defines the actions happening just before a mesh is drawing.
  25327. */
  25328. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25329. /**
  25330. * @hidden
  25331. * Defines the actions happening just after a mesh has been drawn.
  25332. */
  25333. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25334. /**
  25335. * @hidden
  25336. * Defines the actions happening just after a rendering group has been drawn.
  25337. */
  25338. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25339. /**
  25340. * @hidden
  25341. * Defines the actions happening just after the active camera has been drawn.
  25342. */
  25343. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25344. /**
  25345. * @hidden
  25346. * Defines the actions happening just after rendering all cameras and computing intersections.
  25347. */
  25348. _this._afterRenderStage = BABYLON.Stage.Create();
  25349. /**
  25350. * @hidden
  25351. * Defines the actions happening when a pointer move event happens.
  25352. */
  25353. _this._pointerMoveStage = BABYLON.Stage.Create();
  25354. /**
  25355. * @hidden
  25356. * Defines the actions happening when a pointer down event happens.
  25357. */
  25358. _this._pointerDownStage = BABYLON.Stage.Create();
  25359. /**
  25360. * @hidden
  25361. * Defines the actions happening when a pointer up event happens.
  25362. */
  25363. _this._pointerUpStage = BABYLON.Stage.Create();
  25364. _this._defaultMeshCandidates = {
  25365. data: [],
  25366. length: 0
  25367. };
  25368. _this._defaultSubMeshCandidates = {
  25369. data: [],
  25370. length: 0
  25371. };
  25372. _this._activeMeshesFrozen = false;
  25373. /** @hidden */
  25374. _this._allowPostProcessClearColor = true;
  25375. /**
  25376. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25377. */
  25378. _this.getDeterministicFrameTime = function () {
  25379. return 1000.0 / 60.0; // frame time in ms
  25380. };
  25381. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25382. _this._blockMaterialDirtyMechanism = false;
  25383. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25384. _this._engine.scenes.push(_this);
  25385. _this._uid = null;
  25386. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25387. if (BABYLON.PostProcessManager) {
  25388. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25389. }
  25390. if (BABYLON.Tools.IsWindowObjectExist()) {
  25391. _this.attachControl();
  25392. }
  25393. //collision coordinator initialization. For now legacy per default.
  25394. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25395. // Uniform Buffer
  25396. _this._createUbo();
  25397. // Default Image processing definition
  25398. if (BABYLON.ImageProcessingConfiguration) {
  25399. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25400. }
  25401. _this.setDefaultCandidateProviders();
  25402. return _this;
  25403. }
  25404. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25405. /**
  25406. * Texture used in all pbr material as the reflection texture.
  25407. * As in the majority of the scene they are the same (exception for multi room and so on),
  25408. * this is easier to reference from here than from all the materials.
  25409. */
  25410. get: function () {
  25411. return this._environmentTexture;
  25412. },
  25413. /**
  25414. * Texture used in all pbr material as the reflection texture.
  25415. * As in the majority of the scene they are the same (exception for multi room and so on),
  25416. * this is easier to set here than in all the materials.
  25417. */
  25418. set: function (value) {
  25419. if (this._environmentTexture === value) {
  25420. return;
  25421. }
  25422. this._environmentTexture = value;
  25423. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25424. },
  25425. enumerable: true,
  25426. configurable: true
  25427. });
  25428. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25429. /**
  25430. * Default image processing configuration used either in the rendering
  25431. * Forward main pass or through the imageProcessingPostProcess if present.
  25432. * As in the majority of the scene they are the same (exception for multi camera),
  25433. * this is easier to reference from here than from all the materials and post process.
  25434. *
  25435. * No setter as we it is a shared configuration, you can set the values instead.
  25436. */
  25437. get: function () {
  25438. return this._imageProcessingConfiguration;
  25439. },
  25440. enumerable: true,
  25441. configurable: true
  25442. });
  25443. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25444. get: function () {
  25445. return this._forceWireframe;
  25446. },
  25447. /**
  25448. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25449. */
  25450. set: function (value) {
  25451. if (this._forceWireframe === value) {
  25452. return;
  25453. }
  25454. this._forceWireframe = value;
  25455. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25456. },
  25457. enumerable: true,
  25458. configurable: true
  25459. });
  25460. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25461. get: function () {
  25462. return this._forcePointsCloud;
  25463. },
  25464. /**
  25465. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25466. */
  25467. set: function (value) {
  25468. if (this._forcePointsCloud === value) {
  25469. return;
  25470. }
  25471. this._forcePointsCloud = value;
  25472. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25473. },
  25474. enumerable: true,
  25475. configurable: true
  25476. });
  25477. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25478. /**
  25479. * Gets or sets the animation properties override
  25480. */
  25481. get: function () {
  25482. return this._animationPropertiesOverride;
  25483. },
  25484. set: function (value) {
  25485. this._animationPropertiesOverride = value;
  25486. },
  25487. enumerable: true,
  25488. configurable: true
  25489. });
  25490. Object.defineProperty(Scene.prototype, "onDispose", {
  25491. /** Sets a function to be executed when this scene is disposed. */
  25492. set: function (callback) {
  25493. if (this._onDisposeObserver) {
  25494. this.onDisposeObservable.remove(this._onDisposeObserver);
  25495. }
  25496. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25497. },
  25498. enumerable: true,
  25499. configurable: true
  25500. });
  25501. Object.defineProperty(Scene.prototype, "beforeRender", {
  25502. /** Sets a function to be executed before rendering this scene */
  25503. set: function (callback) {
  25504. if (this._onBeforeRenderObserver) {
  25505. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25506. }
  25507. if (callback) {
  25508. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25509. }
  25510. },
  25511. enumerable: true,
  25512. configurable: true
  25513. });
  25514. Object.defineProperty(Scene.prototype, "afterRender", {
  25515. /** Sets a function to be executed after rendering this scene */
  25516. set: function (callback) {
  25517. if (this._onAfterRenderObserver) {
  25518. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25519. }
  25520. if (callback) {
  25521. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25522. }
  25523. },
  25524. enumerable: true,
  25525. configurable: true
  25526. });
  25527. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25528. /** Sets a function to be executed before rendering a camera*/
  25529. set: function (callback) {
  25530. if (this._onBeforeCameraRenderObserver) {
  25531. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25532. }
  25533. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25534. },
  25535. enumerable: true,
  25536. configurable: true
  25537. });
  25538. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25539. /** Sets a function to be executed after rendering a camera*/
  25540. set: function (callback) {
  25541. if (this._onAfterCameraRenderObserver) {
  25542. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25543. }
  25544. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25545. },
  25546. enumerable: true,
  25547. configurable: true
  25548. });
  25549. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25550. /**
  25551. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25552. */
  25553. get: function () {
  25554. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25555. },
  25556. enumerable: true,
  25557. configurable: true
  25558. });
  25559. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25560. get: function () {
  25561. return this._useRightHandedSystem;
  25562. },
  25563. /**
  25564. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25565. */
  25566. set: function (value) {
  25567. if (this._useRightHandedSystem === value) {
  25568. return;
  25569. }
  25570. this._useRightHandedSystem = value;
  25571. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25572. },
  25573. enumerable: true,
  25574. configurable: true
  25575. });
  25576. /**
  25577. * Sets the step Id used by deterministic lock step
  25578. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25579. * @param newStepId defines the step Id
  25580. */
  25581. Scene.prototype.setStepId = function (newStepId) {
  25582. this._currentStepId = newStepId;
  25583. };
  25584. ;
  25585. /**
  25586. * Gets the step Id used by deterministic lock step
  25587. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25588. * @returns the step Id
  25589. */
  25590. Scene.prototype.getStepId = function () {
  25591. return this._currentStepId;
  25592. };
  25593. ;
  25594. /**
  25595. * Gets the internal step used by deterministic lock step
  25596. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25597. * @returns the internal step
  25598. */
  25599. Scene.prototype.getInternalStep = function () {
  25600. return this._currentInternalStep;
  25601. };
  25602. ;
  25603. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25604. get: function () {
  25605. return this._fogEnabled;
  25606. },
  25607. /**
  25608. * Gets or sets a boolean indicating if fog is enabled on this scene
  25609. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25610. * (Default is true)
  25611. */
  25612. set: function (value) {
  25613. if (this._fogEnabled === value) {
  25614. return;
  25615. }
  25616. this._fogEnabled = value;
  25617. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25618. },
  25619. enumerable: true,
  25620. configurable: true
  25621. });
  25622. Object.defineProperty(Scene.prototype, "fogMode", {
  25623. get: function () {
  25624. return this._fogMode;
  25625. },
  25626. /**
  25627. * Gets or sets the fog mode to use
  25628. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25629. * | mode | value |
  25630. * | --- | --- |
  25631. * | FOGMODE_NONE | 0 |
  25632. * | FOGMODE_EXP | 1 |
  25633. * | FOGMODE_EXP2 | 2 |
  25634. * | FOGMODE_LINEAR | 3 |
  25635. */
  25636. set: function (value) {
  25637. if (this._fogMode === value) {
  25638. return;
  25639. }
  25640. this._fogMode = value;
  25641. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25642. },
  25643. enumerable: true,
  25644. configurable: true
  25645. });
  25646. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25647. get: function () {
  25648. return this._shadowsEnabled;
  25649. },
  25650. /**
  25651. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25652. */
  25653. set: function (value) {
  25654. if (this._shadowsEnabled === value) {
  25655. return;
  25656. }
  25657. this._shadowsEnabled = value;
  25658. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25659. },
  25660. enumerable: true,
  25661. configurable: true
  25662. });
  25663. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25664. get: function () {
  25665. return this._lightsEnabled;
  25666. },
  25667. /**
  25668. * Gets or sets a boolean indicating if lights are enabled on this scene
  25669. */
  25670. set: function (value) {
  25671. if (this._lightsEnabled === value) {
  25672. return;
  25673. }
  25674. this._lightsEnabled = value;
  25675. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25676. },
  25677. enumerable: true,
  25678. configurable: true
  25679. });
  25680. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25681. /** The default material used on meshes when no material is affected */
  25682. get: function () {
  25683. if (!this._defaultMaterial) {
  25684. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25685. }
  25686. return this._defaultMaterial;
  25687. },
  25688. /** The default material used on meshes when no material is affected */
  25689. set: function (value) {
  25690. this._defaultMaterial = value;
  25691. },
  25692. enumerable: true,
  25693. configurable: true
  25694. });
  25695. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25696. get: function () {
  25697. return this._texturesEnabled;
  25698. },
  25699. /**
  25700. * Gets or sets a boolean indicating if textures are enabled on this scene
  25701. */
  25702. set: function (value) {
  25703. if (this._texturesEnabled === value) {
  25704. return;
  25705. }
  25706. this._texturesEnabled = value;
  25707. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25708. },
  25709. enumerable: true,
  25710. configurable: true
  25711. });
  25712. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25713. get: function () {
  25714. return this._skeletonsEnabled;
  25715. },
  25716. /**
  25717. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25718. */
  25719. set: function (value) {
  25720. if (this._skeletonsEnabled === value) {
  25721. return;
  25722. }
  25723. this._skeletonsEnabled = value;
  25724. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25725. },
  25726. enumerable: true,
  25727. configurable: true
  25728. });
  25729. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25730. /** @hidden */
  25731. get: function () {
  25732. return this._alternateRendering;
  25733. },
  25734. enumerable: true,
  25735. configurable: true
  25736. });
  25737. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25738. /**
  25739. * Gets the list of frustum planes (built from the active camera)
  25740. */
  25741. get: function () {
  25742. return this._frustumPlanes;
  25743. },
  25744. enumerable: true,
  25745. configurable: true
  25746. });
  25747. /**
  25748. * Registers the transient components if needed.
  25749. */
  25750. Scene.prototype._registerTransientComponents = function () {
  25751. // Register components that have been associated lately to the scene.
  25752. if (this._transientComponents.length > 0) {
  25753. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25754. var component = _a[_i];
  25755. component.register();
  25756. }
  25757. this._transientComponents = [];
  25758. }
  25759. };
  25760. /**
  25761. * @hidden
  25762. * Add a component to the scene.
  25763. * Note that the ccomponent could be registered on th next frame if this is called after
  25764. * the register component stage.
  25765. * @param component Defines the component to add to the scene
  25766. */
  25767. Scene.prototype._addComponent = function (component) {
  25768. this._components.push(component);
  25769. this._transientComponents.push(component);
  25770. var serializableComponent = component;
  25771. if (serializableComponent.addFromContainer) {
  25772. this._serializableComponents.push(serializableComponent);
  25773. }
  25774. };
  25775. /**
  25776. * @hidden
  25777. * Gets a component from the scene.
  25778. * @param name defines the name of the component to retrieve
  25779. * @returns the component or null if not present
  25780. */
  25781. Scene.prototype._getComponent = function (name) {
  25782. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25783. var component = _a[_i];
  25784. if (component.name === name) {
  25785. return component;
  25786. }
  25787. }
  25788. return null;
  25789. };
  25790. /**
  25791. * @hidden
  25792. */
  25793. Scene.prototype._getDefaultMeshCandidates = function () {
  25794. this._defaultMeshCandidates.data = this.meshes;
  25795. this._defaultMeshCandidates.length = this.meshes.length;
  25796. return this._defaultMeshCandidates;
  25797. };
  25798. /**
  25799. * @hidden
  25800. */
  25801. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25802. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25803. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25804. return this._defaultSubMeshCandidates;
  25805. };
  25806. /**
  25807. * Sets the default candidate providers for the scene.
  25808. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25809. * and getCollidingSubMeshCandidates to their default function
  25810. */
  25811. Scene.prototype.setDefaultCandidateProviders = function () {
  25812. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25813. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25814. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25815. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25816. };
  25817. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25818. /**
  25819. * Gets a boolean indicating if collisions are processed on a web worker
  25820. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25821. */
  25822. get: function () {
  25823. return this._workerCollisions;
  25824. },
  25825. set: function (enabled) {
  25826. if (!BABYLON.CollisionCoordinatorLegacy) {
  25827. return;
  25828. }
  25829. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25830. this._workerCollisions = enabled;
  25831. if (this.collisionCoordinator) {
  25832. this.collisionCoordinator.destroy();
  25833. }
  25834. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25835. this.collisionCoordinator.init(this);
  25836. },
  25837. enumerable: true,
  25838. configurable: true
  25839. });
  25840. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25841. /**
  25842. * Gets the mesh that is currently under the pointer
  25843. */
  25844. get: function () {
  25845. return this._pointerOverMesh;
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. Object.defineProperty(Scene.prototype, "pointerX", {
  25851. /**
  25852. * Gets the current on-screen X position of the pointer
  25853. */
  25854. get: function () {
  25855. return this._pointerX;
  25856. },
  25857. enumerable: true,
  25858. configurable: true
  25859. });
  25860. Object.defineProperty(Scene.prototype, "pointerY", {
  25861. /**
  25862. * Gets the current on-screen Y position of the pointer
  25863. */
  25864. get: function () {
  25865. return this._pointerY;
  25866. },
  25867. enumerable: true,
  25868. configurable: true
  25869. });
  25870. /**
  25871. * Gets the cached material (ie. the latest rendered one)
  25872. * @returns the cached material
  25873. */
  25874. Scene.prototype.getCachedMaterial = function () {
  25875. return this._cachedMaterial;
  25876. };
  25877. /**
  25878. * Gets the cached effect (ie. the latest rendered one)
  25879. * @returns the cached effect
  25880. */
  25881. Scene.prototype.getCachedEffect = function () {
  25882. return this._cachedEffect;
  25883. };
  25884. /**
  25885. * Gets the cached visibility state (ie. the latest rendered one)
  25886. * @returns the cached visibility state
  25887. */
  25888. Scene.prototype.getCachedVisibility = function () {
  25889. return this._cachedVisibility;
  25890. };
  25891. /**
  25892. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25893. * @param material defines the current material
  25894. * @param effect defines the current effect
  25895. * @param visibility defines the current visibility state
  25896. * @returns true if one parameter is not cached
  25897. */
  25898. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25899. if (visibility === void 0) { visibility = 1; }
  25900. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25901. };
  25902. /**
  25903. * Gets the engine associated with the scene
  25904. * @returns an Engine
  25905. */
  25906. Scene.prototype.getEngine = function () {
  25907. return this._engine;
  25908. };
  25909. /**
  25910. * Gets the total number of vertices rendered per frame
  25911. * @returns the total number of vertices rendered per frame
  25912. */
  25913. Scene.prototype.getTotalVertices = function () {
  25914. return this._totalVertices.current;
  25915. };
  25916. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25917. /**
  25918. * Gets the performance counter for total vertices
  25919. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25920. */
  25921. get: function () {
  25922. return this._totalVertices;
  25923. },
  25924. enumerable: true,
  25925. configurable: true
  25926. });
  25927. /**
  25928. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25929. * @returns the total number of active indices rendered per frame
  25930. */
  25931. Scene.prototype.getActiveIndices = function () {
  25932. return this._activeIndices.current;
  25933. };
  25934. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25935. /**
  25936. * Gets the performance counter for active indices
  25937. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25938. */
  25939. get: function () {
  25940. return this._activeIndices;
  25941. },
  25942. enumerable: true,
  25943. configurable: true
  25944. });
  25945. /**
  25946. * Gets the total number of active particles rendered per frame
  25947. * @returns the total number of active particles rendered per frame
  25948. */
  25949. Scene.prototype.getActiveParticles = function () {
  25950. return this._activeParticles.current;
  25951. };
  25952. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25953. /**
  25954. * Gets the performance counter for active particles
  25955. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25956. */
  25957. get: function () {
  25958. return this._activeParticles;
  25959. },
  25960. enumerable: true,
  25961. configurable: true
  25962. });
  25963. /**
  25964. * Gets the total number of active bones rendered per frame
  25965. * @returns the total number of active bones rendered per frame
  25966. */
  25967. Scene.prototype.getActiveBones = function () {
  25968. return this._activeBones.current;
  25969. };
  25970. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25971. /**
  25972. * Gets the performance counter for active bones
  25973. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25974. */
  25975. get: function () {
  25976. return this._activeBones;
  25977. },
  25978. enumerable: true,
  25979. configurable: true
  25980. });
  25981. /** @hidden */
  25982. Scene.prototype.getInterFramePerfCounter = function () {
  25983. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25984. return 0;
  25985. };
  25986. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25987. /** @hidden */
  25988. get: function () {
  25989. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25990. return null;
  25991. },
  25992. enumerable: true,
  25993. configurable: true
  25994. });
  25995. /** @hidden */
  25996. Scene.prototype.getLastFrameDuration = function () {
  25997. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25998. return 0;
  25999. };
  26000. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26001. /** @hidden */
  26002. get: function () {
  26003. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26004. return null;
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. /** @hidden */
  26010. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26011. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26012. return 0;
  26013. };
  26014. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26015. /** @hidden */
  26016. get: function () {
  26017. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26018. return null;
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. /**
  26024. * Gets the array of active meshes
  26025. * @returns an array of AbstractMesh
  26026. */
  26027. Scene.prototype.getActiveMeshes = function () {
  26028. return this._activeMeshes;
  26029. };
  26030. /** @hidden */
  26031. Scene.prototype.getRenderTargetsDuration = function () {
  26032. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26033. return 0;
  26034. };
  26035. /** @hidden */
  26036. Scene.prototype.getRenderDuration = function () {
  26037. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26038. return 0;
  26039. };
  26040. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26041. /** @hidden */
  26042. get: function () {
  26043. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26044. return null;
  26045. },
  26046. enumerable: true,
  26047. configurable: true
  26048. });
  26049. /** @hidden */
  26050. Scene.prototype.getParticlesDuration = function () {
  26051. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26052. return 0;
  26053. };
  26054. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26055. /** @hidden */
  26056. get: function () {
  26057. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26058. return null;
  26059. },
  26060. enumerable: true,
  26061. configurable: true
  26062. });
  26063. /** @hidden */
  26064. Scene.prototype.getSpritesDuration = function () {
  26065. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26066. return 0;
  26067. };
  26068. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26069. /** @hidden */
  26070. get: function () {
  26071. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26072. return null;
  26073. },
  26074. enumerable: true,
  26075. configurable: true
  26076. });
  26077. /**
  26078. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26079. * @returns a number
  26080. */
  26081. Scene.prototype.getAnimationRatio = function () {
  26082. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26083. };
  26084. /**
  26085. * Gets an unique Id for the current render phase
  26086. * @returns a number
  26087. */
  26088. Scene.prototype.getRenderId = function () {
  26089. return this._renderId;
  26090. };
  26091. /**
  26092. * Gets an unique Id for the current frame
  26093. * @returns a number
  26094. */
  26095. Scene.prototype.getFrameId = function () {
  26096. return this._frameId;
  26097. };
  26098. /** Call this function if you want to manually increment the render Id*/
  26099. Scene.prototype.incrementRenderId = function () {
  26100. this._renderId++;
  26101. };
  26102. Scene.prototype._updatePointerPosition = function (evt) {
  26103. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26104. if (!canvasRect) {
  26105. return;
  26106. }
  26107. this._pointerX = evt.clientX - canvasRect.left;
  26108. this._pointerY = evt.clientY - canvasRect.top;
  26109. this._unTranslatedPointerX = this._pointerX;
  26110. this._unTranslatedPointerY = this._pointerY;
  26111. };
  26112. Scene.prototype._createUbo = function () {
  26113. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26114. this._sceneUbo.addUniform("viewProjection", 16);
  26115. this._sceneUbo.addUniform("view", 16);
  26116. };
  26117. Scene.prototype._createAlternateUbo = function () {
  26118. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26119. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26120. this._alternateSceneUbo.addUniform("view", 16);
  26121. };
  26122. // Pointers handling
  26123. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26124. if (pointerInfo.pickInfo) {
  26125. if (!pointerInfo.pickInfo.ray) {
  26126. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26127. }
  26128. }
  26129. };
  26130. /**
  26131. * Use this method to simulate a pointer move on a mesh
  26132. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26133. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26134. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26135. * @returns the current scene
  26136. */
  26137. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26138. var evt = new PointerEvent("pointermove", pointerEventInit);
  26139. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26140. return this;
  26141. }
  26142. return this._processPointerMove(pickResult, evt);
  26143. };
  26144. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26145. var canvas = this._engine.getRenderingCanvas();
  26146. if (!canvas) {
  26147. return this;
  26148. }
  26149. // Restore pointer
  26150. canvas.style.cursor = this.defaultCursor;
  26151. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26152. if (isMeshPicked) {
  26153. this.setPointerOverMesh(pickResult.pickedMesh);
  26154. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26155. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26156. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26157. }
  26158. else {
  26159. canvas.style.cursor = this.hoverCursor;
  26160. }
  26161. }
  26162. }
  26163. else {
  26164. this.setPointerOverMesh(null);
  26165. }
  26166. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26167. var step = _a[_i];
  26168. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26169. }
  26170. if (pickResult) {
  26171. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26172. if (this.onPointerMove) {
  26173. this.onPointerMove(evt, pickResult, type);
  26174. }
  26175. if (this.onPointerObservable.hasObservers()) {
  26176. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26177. this._setRayOnPointerInfo(pi);
  26178. this.onPointerObservable.notifyObservers(pi, type);
  26179. }
  26180. }
  26181. return this;
  26182. };
  26183. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26184. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26185. if (pickResult) {
  26186. pi.ray = pickResult.ray;
  26187. }
  26188. this.onPrePointerObservable.notifyObservers(pi, type);
  26189. if (pi.skipOnPointerObservable) {
  26190. return true;
  26191. }
  26192. else {
  26193. return false;
  26194. }
  26195. };
  26196. /**
  26197. * Use this method to simulate a pointer down on a mesh
  26198. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26199. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26200. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26201. * @returns the current scene
  26202. */
  26203. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26204. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26205. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26206. return this;
  26207. }
  26208. return this._processPointerDown(pickResult, evt);
  26209. };
  26210. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26211. var _this = this;
  26212. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26213. this._pickedDownMesh = pickResult.pickedMesh;
  26214. var actionManager = pickResult.pickedMesh.actionManager;
  26215. if (actionManager) {
  26216. if (actionManager.hasPickTriggers) {
  26217. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26218. switch (evt.button) {
  26219. case 0:
  26220. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26221. break;
  26222. case 1:
  26223. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26224. break;
  26225. case 2:
  26226. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26227. break;
  26228. }
  26229. }
  26230. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26231. window.setTimeout(function () {
  26232. 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);
  26233. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26234. if (_this._totalPointersPressed !== 0 &&
  26235. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26236. !_this._isPointerSwiping()) {
  26237. _this._startingPointerTime = 0;
  26238. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26239. }
  26240. }
  26241. }, Scene.LongPressDelay);
  26242. }
  26243. }
  26244. }
  26245. else {
  26246. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26247. var step = _a[_i];
  26248. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26249. }
  26250. }
  26251. if (pickResult) {
  26252. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26253. if (this.onPointerDown) {
  26254. this.onPointerDown(evt, pickResult, type);
  26255. }
  26256. if (this.onPointerObservable.hasObservers()) {
  26257. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26258. this._setRayOnPointerInfo(pi);
  26259. this.onPointerObservable.notifyObservers(pi, type);
  26260. }
  26261. }
  26262. return this;
  26263. };
  26264. /**
  26265. * Use this method to simulate a pointer up on a mesh
  26266. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26267. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26268. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26269. * @returns the current scene
  26270. */
  26271. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26272. var evt = new PointerEvent("pointerup", pointerEventInit);
  26273. var clickInfo = new ClickInfo();
  26274. clickInfo.singleClick = true;
  26275. clickInfo.ignore = true;
  26276. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26277. return this;
  26278. }
  26279. return this._processPointerUp(pickResult, evt, clickInfo);
  26280. };
  26281. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26282. if (pickResult && pickResult && pickResult.pickedMesh) {
  26283. this._pickedUpMesh = pickResult.pickedMesh;
  26284. if (this._pickedDownMesh === this._pickedUpMesh) {
  26285. if (this.onPointerPick) {
  26286. this.onPointerPick(evt, pickResult);
  26287. }
  26288. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26289. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26290. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26291. this._setRayOnPointerInfo(pi);
  26292. this.onPointerObservable.notifyObservers(pi, type_1);
  26293. }
  26294. }
  26295. if (pickResult.pickedMesh.actionManager) {
  26296. if (clickInfo.ignore) {
  26297. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26298. }
  26299. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26300. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26301. }
  26302. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26303. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26304. }
  26305. }
  26306. }
  26307. else {
  26308. if (!clickInfo.ignore) {
  26309. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26310. var step = _a[_i];
  26311. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26312. }
  26313. }
  26314. }
  26315. if (this._pickedDownMesh &&
  26316. this._pickedDownMesh.actionManager &&
  26317. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26318. this._pickedDownMesh !== this._pickedUpMesh) {
  26319. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26320. }
  26321. var type = BABYLON.PointerEventTypes.POINTERUP;
  26322. if (this.onPointerObservable.hasObservers()) {
  26323. if (!clickInfo.ignore) {
  26324. if (!clickInfo.hasSwiped) {
  26325. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26326. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26327. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26328. this._setRayOnPointerInfo(pi);
  26329. this.onPointerObservable.notifyObservers(pi, type_2);
  26330. }
  26331. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26332. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26333. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26334. this._setRayOnPointerInfo(pi);
  26335. this.onPointerObservable.notifyObservers(pi, type_3);
  26336. }
  26337. }
  26338. }
  26339. else {
  26340. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26341. this._setRayOnPointerInfo(pi);
  26342. this.onPointerObservable.notifyObservers(pi, type);
  26343. }
  26344. }
  26345. if (this.onPointerUp) {
  26346. this.onPointerUp(evt, pickResult, type);
  26347. }
  26348. return this;
  26349. };
  26350. /**
  26351. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26352. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26353. * @returns true if the pointer was captured
  26354. */
  26355. Scene.prototype.isPointerCaptured = function (pointerId) {
  26356. if (pointerId === void 0) { pointerId = 0; }
  26357. return this._pointerCaptures[pointerId];
  26358. };
  26359. /** @hidden */
  26360. Scene.prototype._isPointerSwiping = function () {
  26361. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26362. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26363. };
  26364. /**
  26365. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26366. * @param attachUp defines if you want to attach events to pointerup
  26367. * @param attachDown defines if you want to attach events to pointerdown
  26368. * @param attachMove defines if you want to attach events to pointermove
  26369. */
  26370. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26371. var _this = this;
  26372. if (attachUp === void 0) { attachUp = true; }
  26373. if (attachDown === void 0) { attachDown = true; }
  26374. if (attachMove === void 0) { attachMove = true; }
  26375. this._initActionManager = function (act, clickInfo) {
  26376. if (!_this._meshPickProceed) {
  26377. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26378. _this._currentPickResult = pickResult;
  26379. if (pickResult) {
  26380. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26381. }
  26382. _this._meshPickProceed = true;
  26383. }
  26384. return act;
  26385. };
  26386. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26387. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26388. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26389. btn !== _this._previousButtonPressed) {
  26390. _this._doubleClickOccured = false;
  26391. clickInfo.singleClick = true;
  26392. clickInfo.ignore = false;
  26393. cb(clickInfo, _this._currentPickResult);
  26394. }
  26395. };
  26396. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26397. var clickInfo = new ClickInfo();
  26398. _this._currentPickResult = null;
  26399. var act = null;
  26400. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26401. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26402. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26403. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26404. act = _this._initActionManager(act, clickInfo);
  26405. if (act)
  26406. checkPicking = act.hasPickTriggers;
  26407. }
  26408. if (checkPicking) {
  26409. var btn = evt.button;
  26410. clickInfo.hasSwiped = _this._isPointerSwiping();
  26411. if (!clickInfo.hasSwiped) {
  26412. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26413. if (!checkSingleClickImmediately) {
  26414. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26415. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26416. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26417. act = _this._initActionManager(act, clickInfo);
  26418. if (act)
  26419. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26420. }
  26421. }
  26422. if (checkSingleClickImmediately) {
  26423. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26424. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26425. btn !== _this._previousButtonPressed) {
  26426. clickInfo.singleClick = true;
  26427. cb(clickInfo, _this._currentPickResult);
  26428. }
  26429. }
  26430. // at least one double click is required to be check and exclusive double click is enabled
  26431. else {
  26432. // wait that no double click has been raised during the double click delay
  26433. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26434. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26435. }
  26436. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26437. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26438. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26439. act = _this._initActionManager(act, clickInfo);
  26440. if (act)
  26441. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26442. }
  26443. if (checkDoubleClick) {
  26444. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26445. if (btn === _this._previousButtonPressed &&
  26446. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26447. !_this._doubleClickOccured) {
  26448. // pointer has not moved for 2 clicks, it's a double click
  26449. if (!clickInfo.hasSwiped &&
  26450. !_this._isPointerSwiping()) {
  26451. _this._previousStartingPointerTime = 0;
  26452. _this._doubleClickOccured = true;
  26453. clickInfo.doubleClick = true;
  26454. clickInfo.ignore = false;
  26455. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26456. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26457. }
  26458. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26459. cb(clickInfo, _this._currentPickResult);
  26460. }
  26461. // if the two successive clicks are too far, it's just two simple clicks
  26462. else {
  26463. _this._doubleClickOccured = false;
  26464. _this._previousStartingPointerTime = _this._startingPointerTime;
  26465. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26466. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26467. _this._previousButtonPressed = btn;
  26468. if (Scene.ExclusiveDoubleClickMode) {
  26469. if (_this._previousDelayedSimpleClickTimeout) {
  26470. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26471. }
  26472. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26473. cb(clickInfo, _this._previousPickResult);
  26474. }
  26475. else {
  26476. cb(clickInfo, _this._currentPickResult);
  26477. }
  26478. }
  26479. }
  26480. // just the first click of the double has been raised
  26481. else {
  26482. _this._doubleClickOccured = false;
  26483. _this._previousStartingPointerTime = _this._startingPointerTime;
  26484. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26485. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26486. _this._previousButtonPressed = btn;
  26487. }
  26488. }
  26489. }
  26490. }
  26491. clickInfo.ignore = true;
  26492. cb(clickInfo, _this._currentPickResult);
  26493. };
  26494. this._onPointerMove = function (evt) {
  26495. _this._updatePointerPosition(evt);
  26496. // PreObservable support
  26497. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26498. return;
  26499. }
  26500. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26501. return;
  26502. }
  26503. if (!_this.pointerMovePredicate) {
  26504. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26505. }
  26506. // Meshes
  26507. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26508. _this._processPointerMove(pickResult, evt);
  26509. };
  26510. this._onPointerDown = function (evt) {
  26511. _this._totalPointersPressed++;
  26512. _this._pickedDownMesh = null;
  26513. _this._meshPickProceed = false;
  26514. _this._updatePointerPosition(evt);
  26515. if (_this.preventDefaultOnPointerDown && canvas) {
  26516. evt.preventDefault();
  26517. canvas.focus();
  26518. }
  26519. // PreObservable support
  26520. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26521. return;
  26522. }
  26523. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26524. return;
  26525. }
  26526. _this._pointerCaptures[evt.pointerId] = true;
  26527. _this._startingPointerPosition.x = _this._pointerX;
  26528. _this._startingPointerPosition.y = _this._pointerY;
  26529. _this._startingPointerTime = Date.now();
  26530. if (!_this.pointerDownPredicate) {
  26531. _this.pointerDownPredicate = function (mesh) {
  26532. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26533. };
  26534. }
  26535. // Meshes
  26536. _this._pickedDownMesh = null;
  26537. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26538. _this._processPointerDown(pickResult, evt);
  26539. };
  26540. this._onPointerUp = function (evt) {
  26541. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26542. return; // So we need to test it the pointer down was pressed before.
  26543. }
  26544. _this._totalPointersPressed--;
  26545. _this._pickedUpMesh = null;
  26546. _this._meshPickProceed = false;
  26547. _this._updatePointerPosition(evt);
  26548. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26549. // PreObservable support
  26550. if (_this.onPrePointerObservable.hasObservers()) {
  26551. if (!clickInfo.ignore) {
  26552. if (!clickInfo.hasSwiped) {
  26553. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26554. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26555. return;
  26556. }
  26557. }
  26558. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26559. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26560. return;
  26561. }
  26562. }
  26563. }
  26564. }
  26565. else {
  26566. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26567. return;
  26568. }
  26569. }
  26570. }
  26571. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26572. return;
  26573. }
  26574. _this._pointerCaptures[evt.pointerId] = false;
  26575. if (!_this.pointerUpPredicate) {
  26576. _this.pointerUpPredicate = function (mesh) {
  26577. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26578. };
  26579. }
  26580. // Meshes
  26581. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26582. _this._initActionManager(null, clickInfo);
  26583. }
  26584. if (!pickResult) {
  26585. pickResult = _this._currentPickResult;
  26586. }
  26587. _this._processPointerUp(pickResult, evt, clickInfo);
  26588. _this._previousPickResult = _this._currentPickResult;
  26589. });
  26590. };
  26591. this._onKeyDown = function (evt) {
  26592. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26593. if (_this.onPreKeyboardObservable.hasObservers()) {
  26594. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26595. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26596. if (pi.skipOnPointerObservable) {
  26597. return;
  26598. }
  26599. }
  26600. if (_this.onKeyboardObservable.hasObservers()) {
  26601. var pi = new BABYLON.KeyboardInfo(type, evt);
  26602. _this.onKeyboardObservable.notifyObservers(pi, type);
  26603. }
  26604. if (_this.actionManager) {
  26605. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26606. }
  26607. };
  26608. this._onKeyUp = function (evt) {
  26609. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26610. if (_this.onPreKeyboardObservable.hasObservers()) {
  26611. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26612. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26613. if (pi.skipOnPointerObservable) {
  26614. return;
  26615. }
  26616. }
  26617. if (_this.onKeyboardObservable.hasObservers()) {
  26618. var pi = new BABYLON.KeyboardInfo(type, evt);
  26619. _this.onKeyboardObservable.notifyObservers(pi, type);
  26620. }
  26621. if (_this.actionManager) {
  26622. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26623. }
  26624. };
  26625. var engine = this.getEngine();
  26626. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26627. if (!canvas) {
  26628. return;
  26629. }
  26630. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26631. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26632. });
  26633. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26634. if (!canvas) {
  26635. return;
  26636. }
  26637. canvas.removeEventListener("keydown", _this._onKeyDown);
  26638. canvas.removeEventListener("keyup", _this._onKeyUp);
  26639. });
  26640. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26641. var canvas = this._engine.getRenderingCanvas();
  26642. if (!canvas) {
  26643. return;
  26644. }
  26645. if (attachMove) {
  26646. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26647. // Wheel
  26648. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26649. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26650. }
  26651. if (attachDown) {
  26652. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26653. }
  26654. if (attachUp) {
  26655. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26656. }
  26657. canvas.tabIndex = 1;
  26658. };
  26659. /** Detaches all event handlers*/
  26660. Scene.prototype.detachControl = function () {
  26661. var engine = this.getEngine();
  26662. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26663. var canvas = engine.getRenderingCanvas();
  26664. if (!canvas) {
  26665. return;
  26666. }
  26667. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26668. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26669. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26670. if (this._onCanvasBlurObserver) {
  26671. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26672. }
  26673. if (this._onCanvasFocusObserver) {
  26674. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26675. }
  26676. // Wheel
  26677. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26678. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26679. // Keyboard
  26680. canvas.removeEventListener("keydown", this._onKeyDown);
  26681. canvas.removeEventListener("keyup", this._onKeyUp);
  26682. // Observables
  26683. this.onKeyboardObservable.clear();
  26684. this.onPreKeyboardObservable.clear();
  26685. this.onPointerObservable.clear();
  26686. this.onPrePointerObservable.clear();
  26687. };
  26688. /**
  26689. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26690. * Delay loaded resources are not taking in account
  26691. * @return true if all required resources are ready
  26692. */
  26693. Scene.prototype.isReady = function () {
  26694. if (this._isDisposed) {
  26695. return false;
  26696. }
  26697. if (this._pendingData.length > 0) {
  26698. return false;
  26699. }
  26700. var index;
  26701. var engine = this.getEngine();
  26702. // Geometries
  26703. for (index = 0; index < this.geometries.length; index++) {
  26704. var geometry = this.geometries[index];
  26705. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26706. return false;
  26707. }
  26708. }
  26709. // Meshes
  26710. for (index = 0; index < this.meshes.length; index++) {
  26711. var mesh = this.meshes[index];
  26712. if (!mesh.isEnabled()) {
  26713. continue;
  26714. }
  26715. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26716. continue;
  26717. }
  26718. if (!mesh.isReady(true)) {
  26719. return false;
  26720. }
  26721. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26722. // Is Ready For Mesh
  26723. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26724. var step = _a[_i];
  26725. if (!step.action(mesh, hardwareInstancedRendering)) {
  26726. return false;
  26727. }
  26728. }
  26729. }
  26730. // Post-processes
  26731. if (this.activeCameras && this.activeCameras.length > 0) {
  26732. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26733. var camera = _c[_b];
  26734. if (!camera.isReady(true)) {
  26735. return false;
  26736. }
  26737. }
  26738. }
  26739. else if (this.activeCamera) {
  26740. if (!this.activeCamera.isReady(true)) {
  26741. return false;
  26742. }
  26743. }
  26744. // Particles
  26745. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26746. var particleSystem = _e[_d];
  26747. if (!particleSystem.isReady()) {
  26748. return false;
  26749. }
  26750. }
  26751. return true;
  26752. };
  26753. /** Resets all cached information relative to material (including effect and visibility) */
  26754. Scene.prototype.resetCachedMaterial = function () {
  26755. this._cachedMaterial = null;
  26756. this._cachedEffect = null;
  26757. this._cachedVisibility = null;
  26758. };
  26759. /**
  26760. * Registers a function to be called before every frame render
  26761. * @param func defines the function to register
  26762. */
  26763. Scene.prototype.registerBeforeRender = function (func) {
  26764. this.onBeforeRenderObservable.add(func);
  26765. };
  26766. /**
  26767. * Unregisters a function called before every frame render
  26768. * @param func defines the function to unregister
  26769. */
  26770. Scene.prototype.unregisterBeforeRender = function (func) {
  26771. this.onBeforeRenderObservable.removeCallback(func);
  26772. };
  26773. /**
  26774. * Registers a function to be called after every frame render
  26775. * @param func defines the function to register
  26776. */
  26777. Scene.prototype.registerAfterRender = function (func) {
  26778. this.onAfterRenderObservable.add(func);
  26779. };
  26780. /**
  26781. * Unregisters a function called after every frame render
  26782. * @param func defines the function to unregister
  26783. */
  26784. Scene.prototype.unregisterAfterRender = function (func) {
  26785. this.onAfterRenderObservable.removeCallback(func);
  26786. };
  26787. Scene.prototype._executeOnceBeforeRender = function (func) {
  26788. var _this = this;
  26789. var execFunc = function () {
  26790. func();
  26791. setTimeout(function () {
  26792. _this.unregisterBeforeRender(execFunc);
  26793. });
  26794. };
  26795. this.registerBeforeRender(execFunc);
  26796. };
  26797. /**
  26798. * The provided function will run before render once and will be disposed afterwards.
  26799. * A timeout delay can be provided so that the function will be executed in N ms.
  26800. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26801. * @param func The function to be executed.
  26802. * @param timeout optional delay in ms
  26803. */
  26804. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26805. var _this = this;
  26806. if (timeout !== undefined) {
  26807. setTimeout(function () {
  26808. _this._executeOnceBeforeRender(func);
  26809. }, timeout);
  26810. }
  26811. else {
  26812. this._executeOnceBeforeRender(func);
  26813. }
  26814. };
  26815. /** @hidden */
  26816. Scene.prototype._addPendingData = function (data) {
  26817. this._pendingData.push(data);
  26818. };
  26819. /** @hidden */
  26820. Scene.prototype._removePendingData = function (data) {
  26821. var wasLoading = this.isLoading;
  26822. var index = this._pendingData.indexOf(data);
  26823. if (index !== -1) {
  26824. this._pendingData.splice(index, 1);
  26825. }
  26826. if (wasLoading && !this.isLoading) {
  26827. this.onDataLoadedObservable.notifyObservers(this);
  26828. }
  26829. };
  26830. /**
  26831. * Returns the number of items waiting to be loaded
  26832. * @returns the number of items waiting to be loaded
  26833. */
  26834. Scene.prototype.getWaitingItemsCount = function () {
  26835. return this._pendingData.length;
  26836. };
  26837. Object.defineProperty(Scene.prototype, "isLoading", {
  26838. /**
  26839. * Returns a boolean indicating if the scene is still loading data
  26840. */
  26841. get: function () {
  26842. return this._pendingData.length > 0;
  26843. },
  26844. enumerable: true,
  26845. configurable: true
  26846. });
  26847. /**
  26848. * Registers a function to be executed when the scene is ready
  26849. * @param {Function} func - the function to be executed
  26850. */
  26851. Scene.prototype.executeWhenReady = function (func) {
  26852. var _this = this;
  26853. this.onReadyObservable.add(func);
  26854. if (this._executeWhenReadyTimeoutId !== -1) {
  26855. return;
  26856. }
  26857. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26858. _this._checkIsReady();
  26859. }, 150);
  26860. };
  26861. /**
  26862. * Returns a promise that resolves when the scene is ready
  26863. * @returns A promise that resolves when the scene is ready
  26864. */
  26865. Scene.prototype.whenReadyAsync = function () {
  26866. var _this = this;
  26867. return new Promise(function (resolve) {
  26868. _this.executeWhenReady(function () {
  26869. resolve();
  26870. });
  26871. });
  26872. };
  26873. /** @hidden */
  26874. Scene.prototype._checkIsReady = function () {
  26875. var _this = this;
  26876. this._registerTransientComponents();
  26877. if (this.isReady()) {
  26878. this.onReadyObservable.notifyObservers(this);
  26879. this.onReadyObservable.clear();
  26880. this._executeWhenReadyTimeoutId = -1;
  26881. return;
  26882. }
  26883. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26884. _this._checkIsReady();
  26885. }, 150);
  26886. };
  26887. // Animations
  26888. /**
  26889. * Will start the animation sequence of a given target
  26890. * @param target defines the target
  26891. * @param from defines from which frame should animation start
  26892. * @param to defines until which frame should animation run.
  26893. * @param weight defines the weight to apply to the animation (1.0 by default)
  26894. * @param loop defines if the animation loops
  26895. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26896. * @param onAnimationEnd defines the function to be executed when the animation ends
  26897. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26898. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26899. * @returns the animatable object created for this animation
  26900. */
  26901. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26902. if (weight === void 0) { weight = 1.0; }
  26903. if (speedRatio === void 0) { speedRatio = 1.0; }
  26904. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26905. returnedAnimatable.weight = weight;
  26906. return returnedAnimatable;
  26907. };
  26908. /**
  26909. * Will start the animation sequence of a given target
  26910. * @param target defines the target
  26911. * @param from defines from which frame should animation start
  26912. * @param to defines until which frame should animation run.
  26913. * @param loop defines if the animation loops
  26914. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26915. * @param onAnimationEnd defines the function to be executed when the animation ends
  26916. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26917. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26918. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26919. * @returns the animatable object created for this animation
  26920. */
  26921. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26922. if (speedRatio === void 0) { speedRatio = 1.0; }
  26923. if (stopCurrent === void 0) { stopCurrent = true; }
  26924. if (from > to && speedRatio > 0) {
  26925. speedRatio *= -1;
  26926. }
  26927. if (stopCurrent) {
  26928. this.stopAnimation(target, undefined, targetMask);
  26929. }
  26930. if (!animatable) {
  26931. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26932. }
  26933. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26934. // Local animations
  26935. if (target.animations && shouldRunTargetAnimations) {
  26936. animatable.appendAnimations(target, target.animations);
  26937. }
  26938. // Children animations
  26939. if (target.getAnimatables) {
  26940. var animatables = target.getAnimatables();
  26941. for (var index = 0; index < animatables.length; index++) {
  26942. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26943. }
  26944. }
  26945. animatable.reset();
  26946. return animatable;
  26947. };
  26948. /**
  26949. * Begin a new animation on a given node
  26950. * @param target defines the target where the animation will take place
  26951. * @param animations defines the list of animations to start
  26952. * @param from defines the initial value
  26953. * @param to defines the final value
  26954. * @param loop defines if you want animation to loop (off by default)
  26955. * @param speedRatio defines the speed ratio to apply to all animations
  26956. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26957. * @returns the list of created animatables
  26958. */
  26959. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26960. if (speedRatio === undefined) {
  26961. speedRatio = 1.0;
  26962. }
  26963. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26964. return animatable;
  26965. };
  26966. /**
  26967. * Begin a new animation on a given node and its hierarchy
  26968. * @param target defines the root node where the animation will take place
  26969. * @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.
  26970. * @param animations defines the list of animations to start
  26971. * @param from defines the initial value
  26972. * @param to defines the final value
  26973. * @param loop defines if you want animation to loop (off by default)
  26974. * @param speedRatio defines the speed ratio to apply to all animations
  26975. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26976. * @returns the list of animatables created for all nodes
  26977. */
  26978. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26979. var children = target.getDescendants(directDescendantsOnly);
  26980. var result = [];
  26981. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26982. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26983. var child = children_1[_i];
  26984. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26985. }
  26986. return result;
  26987. };
  26988. /**
  26989. * Gets the animatable associated with a specific target
  26990. * @param target defines the target of the animatable
  26991. * @returns the required animatable if found
  26992. */
  26993. Scene.prototype.getAnimatableByTarget = function (target) {
  26994. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26995. if (this._activeAnimatables[index].target === target) {
  26996. return this._activeAnimatables[index];
  26997. }
  26998. }
  26999. return null;
  27000. };
  27001. /**
  27002. * Gets all animatables associated with a given target
  27003. * @param target defines the target to look animatables for
  27004. * @returns an array of Animatables
  27005. */
  27006. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27007. var result = [];
  27008. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27009. if (this._activeAnimatables[index].target === target) {
  27010. result.push(this._activeAnimatables[index]);
  27011. }
  27012. }
  27013. return result;
  27014. };
  27015. Object.defineProperty(Scene.prototype, "animatables", {
  27016. /**
  27017. * Gets all animatable attached to the scene
  27018. */
  27019. get: function () {
  27020. return this._activeAnimatables;
  27021. },
  27022. enumerable: true,
  27023. configurable: true
  27024. });
  27025. /**
  27026. * Will stop the animation of the given target
  27027. * @param target - the target
  27028. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27029. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  27030. */
  27031. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27032. var animatables = this.getAllAnimatablesByTarget(target);
  27033. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27034. var animatable = animatables_1[_i];
  27035. animatable.stop(animationName, targetMask);
  27036. }
  27037. };
  27038. /**
  27039. * Stops and removes all animations that have been applied to the scene
  27040. */
  27041. Scene.prototype.stopAllAnimations = function () {
  27042. if (this._activeAnimatables) {
  27043. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27044. this._activeAnimatables[i].stop();
  27045. }
  27046. this._activeAnimatables = [];
  27047. }
  27048. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27049. var group = _a[_i];
  27050. group.stop();
  27051. }
  27052. };
  27053. Scene.prototype._animate = function () {
  27054. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27055. return;
  27056. }
  27057. // Getting time
  27058. var now = BABYLON.Tools.Now;
  27059. if (!this._animationTimeLast) {
  27060. if (this._pendingData.length > 0) {
  27061. return;
  27062. }
  27063. this._animationTimeLast = now;
  27064. }
  27065. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27066. this._animationTime += deltaTime;
  27067. this._animationTimeLast = now;
  27068. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27069. this._activeAnimatables[index]._animate(this._animationTime);
  27070. }
  27071. // Late animation bindings
  27072. this._processLateAnimationBindings();
  27073. };
  27074. /** @hidden */
  27075. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27076. var target = runtimeAnimation.target;
  27077. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27078. if (!target._lateAnimationHolders) {
  27079. target._lateAnimationHolders = {};
  27080. }
  27081. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27082. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27083. totalWeight: 0,
  27084. animations: [],
  27085. originalValue: originalValue
  27086. };
  27087. }
  27088. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27089. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27090. };
  27091. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27092. var normalizer = 1.0;
  27093. var finalPosition = BABYLON.Tmp.Vector3[0];
  27094. var finalScaling = BABYLON.Tmp.Vector3[1];
  27095. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27096. var startIndex = 0;
  27097. var originalAnimation = holder.animations[0];
  27098. var originalValue = holder.originalValue;
  27099. var scale = 1;
  27100. if (holder.totalWeight < 1.0) {
  27101. // We need to mix the original value in
  27102. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27103. scale = 1.0 - holder.totalWeight;
  27104. }
  27105. else {
  27106. startIndex = 1;
  27107. // We need to normalize the weights
  27108. normalizer = holder.totalWeight;
  27109. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27110. scale = originalAnimation.weight / normalizer;
  27111. if (scale == 1) {
  27112. return originalAnimation.currentValue;
  27113. }
  27114. }
  27115. finalScaling.scaleInPlace(scale);
  27116. finalPosition.scaleInPlace(scale);
  27117. finalQuaternion.scaleInPlace(scale);
  27118. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27119. var runtimeAnimation = holder.animations[animIndex];
  27120. var scale = runtimeAnimation.weight / normalizer;
  27121. var currentPosition = BABYLON.Tmp.Vector3[2];
  27122. var currentScaling = BABYLON.Tmp.Vector3[3];
  27123. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27124. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27125. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27126. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27127. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27128. }
  27129. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27130. return originalAnimation._workValue;
  27131. };
  27132. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27133. var originalAnimation = holder.animations[0];
  27134. var originalValue = holder.originalValue;
  27135. if (holder.animations.length === 1) {
  27136. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27137. return refQuaternion;
  27138. }
  27139. var normalizer = 1.0;
  27140. var quaternions;
  27141. var weights;
  27142. if (holder.totalWeight < 1.0) {
  27143. var scale = 1.0 - holder.totalWeight;
  27144. quaternions = [];
  27145. weights = [];
  27146. quaternions.push(originalValue);
  27147. weights.push(scale);
  27148. }
  27149. else {
  27150. if (holder.animations.length === 2) { // Slerp as soon as we can
  27151. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27152. return refQuaternion;
  27153. }
  27154. quaternions = [];
  27155. weights = [];
  27156. normalizer = holder.totalWeight;
  27157. }
  27158. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27159. var runtimeAnimation = holder.animations[animIndex];
  27160. quaternions.push(runtimeAnimation.currentValue);
  27161. weights.push(runtimeAnimation.weight / normalizer);
  27162. }
  27163. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27164. var cumulativeAmount = 0;
  27165. var cumulativeQuaternion = null;
  27166. for (var index = 0; index < quaternions.length;) {
  27167. if (!cumulativeQuaternion) {
  27168. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27169. cumulativeQuaternion = refQuaternion;
  27170. cumulativeAmount = weights[index] + weights[index + 1];
  27171. index += 2;
  27172. continue;
  27173. }
  27174. cumulativeAmount += weights[index];
  27175. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27176. index++;
  27177. }
  27178. return cumulativeQuaternion;
  27179. };
  27180. Scene.prototype._processLateAnimationBindings = function () {
  27181. if (!this._registeredForLateAnimationBindings.length) {
  27182. return;
  27183. }
  27184. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27185. var target = this._registeredForLateAnimationBindings.data[index];
  27186. for (var path in target._lateAnimationHolders) {
  27187. var holder = target._lateAnimationHolders[path];
  27188. var originalAnimation = holder.animations[0];
  27189. var originalValue = holder.originalValue;
  27190. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27191. var finalValue = target[path];
  27192. if (matrixDecomposeMode) {
  27193. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27194. }
  27195. else {
  27196. var quaternionMode = originalValue.w !== undefined;
  27197. if (quaternionMode) {
  27198. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27199. }
  27200. else {
  27201. var startIndex = 0;
  27202. var normalizer = 1.0;
  27203. if (holder.totalWeight < 1.0) {
  27204. // We need to mix the original value in
  27205. if (originalValue.scale) {
  27206. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27207. }
  27208. else {
  27209. finalValue = originalValue * (1.0 - holder.totalWeight);
  27210. }
  27211. }
  27212. else {
  27213. // We need to normalize the weights
  27214. normalizer = holder.totalWeight;
  27215. var scale_1 = originalAnimation.weight / normalizer;
  27216. if (scale_1 !== 1) {
  27217. if (originalAnimation.currentValue.scale) {
  27218. finalValue = originalAnimation.currentValue.scale(scale_1);
  27219. }
  27220. else {
  27221. finalValue = originalAnimation.currentValue * scale_1;
  27222. }
  27223. }
  27224. else {
  27225. finalValue = originalAnimation.currentValue;
  27226. }
  27227. startIndex = 1;
  27228. }
  27229. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27230. var runtimeAnimation = holder.animations[animIndex];
  27231. var scale = runtimeAnimation.weight / normalizer;
  27232. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27233. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27234. }
  27235. else {
  27236. finalValue += runtimeAnimation.currentValue * scale;
  27237. }
  27238. }
  27239. }
  27240. }
  27241. target[path] = finalValue;
  27242. }
  27243. target._lateAnimationHolders = {};
  27244. }
  27245. this._registeredForLateAnimationBindings.reset();
  27246. };
  27247. // Matrix
  27248. /** @hidden */
  27249. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27250. this._useAlternateCameraConfiguration = active;
  27251. };
  27252. /**
  27253. * Gets the current view matrix
  27254. * @returns a Matrix
  27255. */
  27256. Scene.prototype.getViewMatrix = function () {
  27257. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27258. };
  27259. /**
  27260. * Gets the current projection matrix
  27261. * @returns a Matrix
  27262. */
  27263. Scene.prototype.getProjectionMatrix = function () {
  27264. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27265. };
  27266. /**
  27267. * Gets the current transform matrix
  27268. * @returns a Matrix made of View * Projection
  27269. */
  27270. Scene.prototype.getTransformMatrix = function () {
  27271. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27272. };
  27273. /**
  27274. * Sets the current transform matrix
  27275. * @param view defines the View matrix to use
  27276. * @param projection defines the Projection matrix to use
  27277. */
  27278. Scene.prototype.setTransformMatrix = function (view, projection) {
  27279. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27280. return;
  27281. }
  27282. this._viewUpdateFlag = view.updateFlag;
  27283. this._projectionUpdateFlag = projection.updateFlag;
  27284. this._viewMatrix = view;
  27285. this._projectionMatrix = projection;
  27286. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27287. // Update frustum
  27288. if (!this._frustumPlanes) {
  27289. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27290. }
  27291. else {
  27292. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27293. }
  27294. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27295. var otherCamera = this.activeCamera._alternateCamera;
  27296. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27297. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27298. }
  27299. if (this._sceneUbo.useUbo) {
  27300. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27301. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27302. this._sceneUbo.update();
  27303. }
  27304. };
  27305. /** @hidden */
  27306. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27307. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27308. return;
  27309. }
  27310. this._alternateViewUpdateFlag = view.updateFlag;
  27311. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27312. this._alternateViewMatrix = view;
  27313. this._alternateProjectionMatrix = projection;
  27314. if (!this._alternateTransformMatrix) {
  27315. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27316. }
  27317. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27318. if (!this._alternateSceneUbo) {
  27319. this._createAlternateUbo();
  27320. }
  27321. if (this._alternateSceneUbo.useUbo) {
  27322. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27323. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27324. this._alternateSceneUbo.update();
  27325. }
  27326. };
  27327. /**
  27328. * Gets the uniform buffer used to store scene data
  27329. * @returns a UniformBuffer
  27330. */
  27331. Scene.prototype.getSceneUniformBuffer = function () {
  27332. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27333. };
  27334. /**
  27335. * Gets an unique (relatively to the current scene) Id
  27336. * @returns an unique number for the scene
  27337. */
  27338. Scene.prototype.getUniqueId = function () {
  27339. var result = Scene._uniqueIdCounter;
  27340. Scene._uniqueIdCounter++;
  27341. return result;
  27342. };
  27343. /**
  27344. * Add a mesh to the list of scene's meshes
  27345. * @param newMesh defines the mesh to add
  27346. * @param recursive if all child meshes should also be added to the scene
  27347. */
  27348. Scene.prototype.addMesh = function (newMesh, recursive) {
  27349. var _this = this;
  27350. if (recursive === void 0) { recursive = false; }
  27351. this.meshes.push(newMesh);
  27352. //notify the collision coordinator
  27353. if (this.collisionCoordinator) {
  27354. this.collisionCoordinator.onMeshAdded(newMesh);
  27355. }
  27356. newMesh._resyncLightSources();
  27357. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27358. if (recursive) {
  27359. newMesh.getChildMeshes().forEach(function (m) {
  27360. _this.addMesh(m);
  27361. });
  27362. }
  27363. };
  27364. /**
  27365. * Remove a mesh for the list of scene's meshes
  27366. * @param toRemove defines the mesh to remove
  27367. * @param recursive if all child meshes should also be removed from the scene
  27368. * @returns the index where the mesh was in the mesh list
  27369. */
  27370. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27371. var _this = this;
  27372. if (recursive === void 0) { recursive = false; }
  27373. var index = this.meshes.indexOf(toRemove);
  27374. if (index !== -1) {
  27375. // Remove from the scene if mesh found
  27376. this.meshes.splice(index, 1);
  27377. }
  27378. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27379. if (recursive) {
  27380. toRemove.getChildMeshes().forEach(function (m) {
  27381. _this.removeMesh(m);
  27382. });
  27383. }
  27384. return index;
  27385. };
  27386. /**
  27387. * Add a transform node to the list of scene's transform nodes
  27388. * @param newTransformNode defines the transform node to add
  27389. */
  27390. Scene.prototype.addTransformNode = function (newTransformNode) {
  27391. this.transformNodes.push(newTransformNode);
  27392. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27393. };
  27394. /**
  27395. * Remove a transform node for the list of scene's transform nodes
  27396. * @param toRemove defines the transform node to remove
  27397. * @returns the index where the transform node was in the transform node list
  27398. */
  27399. Scene.prototype.removeTransformNode = function (toRemove) {
  27400. var index = this.transformNodes.indexOf(toRemove);
  27401. if (index !== -1) {
  27402. // Remove from the scene if found
  27403. this.transformNodes.splice(index, 1);
  27404. }
  27405. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27406. return index;
  27407. };
  27408. /**
  27409. * Remove a skeleton for the list of scene's skeletons
  27410. * @param toRemove defines the skeleton to remove
  27411. * @returns the index where the skeleton was in the skeleton list
  27412. */
  27413. Scene.prototype.removeSkeleton = function (toRemove) {
  27414. var index = this.skeletons.indexOf(toRemove);
  27415. if (index !== -1) {
  27416. // Remove from the scene if found
  27417. this.skeletons.splice(index, 1);
  27418. }
  27419. return index;
  27420. };
  27421. /**
  27422. * Remove a morph target for the list of scene's morph targets
  27423. * @param toRemove defines the morph target to remove
  27424. * @returns the index where the morph target was in the morph target list
  27425. */
  27426. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27427. var index = this.morphTargetManagers.indexOf(toRemove);
  27428. if (index !== -1) {
  27429. // Remove from the scene if found
  27430. this.morphTargetManagers.splice(index, 1);
  27431. }
  27432. return index;
  27433. };
  27434. /**
  27435. * Remove a light for the list of scene's lights
  27436. * @param toRemove defines the light to remove
  27437. * @returns the index where the light was in the light list
  27438. */
  27439. Scene.prototype.removeLight = function (toRemove) {
  27440. var index = this.lights.indexOf(toRemove);
  27441. if (index !== -1) {
  27442. // Remove from meshes
  27443. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27444. var mesh = _a[_i];
  27445. mesh._removeLightSource(toRemove);
  27446. }
  27447. // Remove from the scene if mesh found
  27448. this.lights.splice(index, 1);
  27449. this.sortLightsByPriority();
  27450. }
  27451. this.onLightRemovedObservable.notifyObservers(toRemove);
  27452. return index;
  27453. };
  27454. /**
  27455. * Remove a camera for the list of scene's cameras
  27456. * @param toRemove defines the camera to remove
  27457. * @returns the index where the camera was in the camera list
  27458. */
  27459. Scene.prototype.removeCamera = function (toRemove) {
  27460. var index = this.cameras.indexOf(toRemove);
  27461. if (index !== -1) {
  27462. // Remove from the scene if mesh found
  27463. this.cameras.splice(index, 1);
  27464. }
  27465. // Remove from activeCameras
  27466. var index2 = this.activeCameras.indexOf(toRemove);
  27467. if (index2 !== -1) {
  27468. // Remove from the scene if mesh found
  27469. this.activeCameras.splice(index2, 1);
  27470. }
  27471. // Reset the activeCamera
  27472. if (this.activeCamera === toRemove) {
  27473. if (this.cameras.length > 0) {
  27474. this.activeCamera = this.cameras[0];
  27475. }
  27476. else {
  27477. this.activeCamera = null;
  27478. }
  27479. }
  27480. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27481. return index;
  27482. };
  27483. /**
  27484. * Remove a particle system for the list of scene's particle systems
  27485. * @param toRemove defines the particle system to remove
  27486. * @returns the index where the particle system was in the particle system list
  27487. */
  27488. Scene.prototype.removeParticleSystem = function (toRemove) {
  27489. var index = this.particleSystems.indexOf(toRemove);
  27490. if (index !== -1) {
  27491. this.particleSystems.splice(index, 1);
  27492. }
  27493. return index;
  27494. };
  27495. /**
  27496. * Remove a animation for the list of scene's animations
  27497. * @param toRemove defines the animation to remove
  27498. * @returns the index where the animation was in the animation list
  27499. */
  27500. Scene.prototype.removeAnimation = function (toRemove) {
  27501. var index = this.animations.indexOf(toRemove);
  27502. if (index !== -1) {
  27503. this.animations.splice(index, 1);
  27504. }
  27505. return index;
  27506. };
  27507. /**
  27508. * Removes the given animation group from this scene.
  27509. * @param toRemove The animation group to remove
  27510. * @returns The index of the removed animation group
  27511. */
  27512. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27513. var index = this.animationGroups.indexOf(toRemove);
  27514. if (index !== -1) {
  27515. this.animationGroups.splice(index, 1);
  27516. }
  27517. return index;
  27518. };
  27519. /**
  27520. * Removes the given multi-material from this scene.
  27521. * @param toRemove The multi-material to remove
  27522. * @returns The index of the removed multi-material
  27523. */
  27524. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27525. var index = this.multiMaterials.indexOf(toRemove);
  27526. if (index !== -1) {
  27527. this.multiMaterials.splice(index, 1);
  27528. }
  27529. return index;
  27530. };
  27531. /**
  27532. * Removes the given material from this scene.
  27533. * @param toRemove The material to remove
  27534. * @returns The index of the removed material
  27535. */
  27536. Scene.prototype.removeMaterial = function (toRemove) {
  27537. var index = this.materials.indexOf(toRemove);
  27538. if (index !== -1) {
  27539. this.materials.splice(index, 1);
  27540. }
  27541. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27542. return index;
  27543. };
  27544. /**
  27545. * Removes the given action manager from this scene.
  27546. * @param toRemove The action manager to remove
  27547. * @returns The index of the removed action manager
  27548. */
  27549. Scene.prototype.removeActionManager = function (toRemove) {
  27550. var index = this.actionManagers.indexOf(toRemove);
  27551. if (index !== -1) {
  27552. this.actionManagers.splice(index, 1);
  27553. }
  27554. return index;
  27555. };
  27556. /**
  27557. * Removes the given texture from this scene.
  27558. * @param toRemove The texture to remove
  27559. * @returns The index of the removed texture
  27560. */
  27561. Scene.prototype.removeTexture = function (toRemove) {
  27562. var index = this.textures.indexOf(toRemove);
  27563. if (index !== -1) {
  27564. this.textures.splice(index, 1);
  27565. }
  27566. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27567. return index;
  27568. };
  27569. /**
  27570. * Adds the given light to this scene
  27571. * @param newLight The light to add
  27572. */
  27573. Scene.prototype.addLight = function (newLight) {
  27574. this.lights.push(newLight);
  27575. this.sortLightsByPriority();
  27576. // Add light to all meshes (To support if the light is removed and then readded)
  27577. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27578. var mesh = _a[_i];
  27579. if (mesh._lightSources.indexOf(newLight) === -1) {
  27580. mesh._lightSources.push(newLight);
  27581. mesh._resyncLightSources();
  27582. }
  27583. }
  27584. this.onNewLightAddedObservable.notifyObservers(newLight);
  27585. };
  27586. /**
  27587. * Sorts the list list based on light priorities
  27588. */
  27589. Scene.prototype.sortLightsByPriority = function () {
  27590. if (this.requireLightSorting) {
  27591. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27592. }
  27593. };
  27594. /**
  27595. * Adds the given camera to this scene
  27596. * @param newCamera The camera to add
  27597. */
  27598. Scene.prototype.addCamera = function (newCamera) {
  27599. this.cameras.push(newCamera);
  27600. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27601. };
  27602. /**
  27603. * Adds the given skeleton to this scene
  27604. * @param newSkeleton The skeleton to add
  27605. */
  27606. Scene.prototype.addSkeleton = function (newSkeleton) {
  27607. this.skeletons.push(newSkeleton);
  27608. };
  27609. /**
  27610. * Adds the given particle system to this scene
  27611. * @param newParticleSystem The particle system to add
  27612. */
  27613. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27614. this.particleSystems.push(newParticleSystem);
  27615. };
  27616. /**
  27617. * Adds the given animation to this scene
  27618. * @param newAnimation The animation to add
  27619. */
  27620. Scene.prototype.addAnimation = function (newAnimation) {
  27621. this.animations.push(newAnimation);
  27622. };
  27623. /**
  27624. * Adds the given animation group to this scene.
  27625. * @param newAnimationGroup The animation group to add
  27626. */
  27627. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27628. this.animationGroups.push(newAnimationGroup);
  27629. };
  27630. /**
  27631. * Adds the given multi-material to this scene
  27632. * @param newMultiMaterial The multi-material to add
  27633. */
  27634. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27635. this.multiMaterials.push(newMultiMaterial);
  27636. };
  27637. /**
  27638. * Adds the given material to this scene
  27639. * @param newMaterial The material to add
  27640. */
  27641. Scene.prototype.addMaterial = function (newMaterial) {
  27642. this.materials.push(newMaterial);
  27643. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27644. };
  27645. /**
  27646. * Adds the given morph target to this scene
  27647. * @param newMorphTargetManager The morph target to add
  27648. */
  27649. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27650. this.morphTargetManagers.push(newMorphTargetManager);
  27651. };
  27652. /**
  27653. * Adds the given geometry to this scene
  27654. * @param newGeometry The geometry to add
  27655. */
  27656. Scene.prototype.addGeometry = function (newGeometry) {
  27657. this.geometries.push(newGeometry);
  27658. };
  27659. /**
  27660. * Adds the given action manager to this scene
  27661. * @param newActionManager The action manager to add
  27662. */
  27663. Scene.prototype.addActionManager = function (newActionManager) {
  27664. this.actionManagers.push(newActionManager);
  27665. };
  27666. /**
  27667. * Adds the given texture to this scene.
  27668. * @param newTexture The texture to add
  27669. */
  27670. Scene.prototype.addTexture = function (newTexture) {
  27671. this.textures.push(newTexture);
  27672. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27673. };
  27674. /**
  27675. * Switch active camera
  27676. * @param newCamera defines the new active camera
  27677. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27678. */
  27679. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27680. if (attachControl === void 0) { attachControl = true; }
  27681. var canvas = this._engine.getRenderingCanvas();
  27682. if (!canvas) {
  27683. return;
  27684. }
  27685. if (this.activeCamera) {
  27686. this.activeCamera.detachControl(canvas);
  27687. }
  27688. this.activeCamera = newCamera;
  27689. if (attachControl) {
  27690. newCamera.attachControl(canvas);
  27691. }
  27692. };
  27693. /**
  27694. * sets the active camera of the scene using its ID
  27695. * @param id defines the camera's ID
  27696. * @return the new active camera or null if none found.
  27697. */
  27698. Scene.prototype.setActiveCameraByID = function (id) {
  27699. var camera = this.getCameraByID(id);
  27700. if (camera) {
  27701. this.activeCamera = camera;
  27702. return camera;
  27703. }
  27704. return null;
  27705. };
  27706. /**
  27707. * sets the active camera of the scene using its name
  27708. * @param name defines the camera's name
  27709. * @returns the new active camera or null if none found.
  27710. */
  27711. Scene.prototype.setActiveCameraByName = function (name) {
  27712. var camera = this.getCameraByName(name);
  27713. if (camera) {
  27714. this.activeCamera = camera;
  27715. return camera;
  27716. }
  27717. return null;
  27718. };
  27719. /**
  27720. * get an animation group using its name
  27721. * @param name defines the material's name
  27722. * @return the animation group or null if none found.
  27723. */
  27724. Scene.prototype.getAnimationGroupByName = function (name) {
  27725. for (var index = 0; index < this.animationGroups.length; index++) {
  27726. if (this.animationGroups[index].name === name) {
  27727. return this.animationGroups[index];
  27728. }
  27729. }
  27730. return null;
  27731. };
  27732. /**
  27733. * get a material using its id
  27734. * @param id defines the material's ID
  27735. * @return the material or null if none found.
  27736. */
  27737. Scene.prototype.getMaterialByID = function (id) {
  27738. for (var index = 0; index < this.materials.length; index++) {
  27739. if (this.materials[index].id === id) {
  27740. return this.materials[index];
  27741. }
  27742. }
  27743. return null;
  27744. };
  27745. /**
  27746. * Gets a material using its name
  27747. * @param name defines the material's name
  27748. * @return the material or null if none found.
  27749. */
  27750. Scene.prototype.getMaterialByName = function (name) {
  27751. for (var index = 0; index < this.materials.length; index++) {
  27752. if (this.materials[index].name === name) {
  27753. return this.materials[index];
  27754. }
  27755. }
  27756. return null;
  27757. };
  27758. /**
  27759. * Gets a camera using its id
  27760. * @param id defines the id to look for
  27761. * @returns the camera or null if not found
  27762. */
  27763. Scene.prototype.getCameraByID = function (id) {
  27764. for (var index = 0; index < this.cameras.length; index++) {
  27765. if (this.cameras[index].id === id) {
  27766. return this.cameras[index];
  27767. }
  27768. }
  27769. return null;
  27770. };
  27771. /**
  27772. * Gets a camera using its unique id
  27773. * @param uniqueId defines the unique id to look for
  27774. * @returns the camera or null if not found
  27775. */
  27776. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27777. for (var index = 0; index < this.cameras.length; index++) {
  27778. if (this.cameras[index].uniqueId === uniqueId) {
  27779. return this.cameras[index];
  27780. }
  27781. }
  27782. return null;
  27783. };
  27784. /**
  27785. * Gets a camera using its name
  27786. * @param name defines the camera's name
  27787. * @return the camera or null if none found.
  27788. */
  27789. Scene.prototype.getCameraByName = function (name) {
  27790. for (var index = 0; index < this.cameras.length; index++) {
  27791. if (this.cameras[index].name === name) {
  27792. return this.cameras[index];
  27793. }
  27794. }
  27795. return null;
  27796. };
  27797. /**
  27798. * Gets a bone using its id
  27799. * @param id defines the bone's id
  27800. * @return the bone or null if not found
  27801. */
  27802. Scene.prototype.getBoneByID = function (id) {
  27803. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27804. var skeleton = this.skeletons[skeletonIndex];
  27805. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27806. if (skeleton.bones[boneIndex].id === id) {
  27807. return skeleton.bones[boneIndex];
  27808. }
  27809. }
  27810. }
  27811. return null;
  27812. };
  27813. /**
  27814. * Gets a bone using its id
  27815. * @param name defines the bone's name
  27816. * @return the bone or null if not found
  27817. */
  27818. Scene.prototype.getBoneByName = function (name) {
  27819. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27820. var skeleton = this.skeletons[skeletonIndex];
  27821. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27822. if (skeleton.bones[boneIndex].name === name) {
  27823. return skeleton.bones[boneIndex];
  27824. }
  27825. }
  27826. }
  27827. return null;
  27828. };
  27829. /**
  27830. * Gets a light node using its name
  27831. * @param name defines the the light's name
  27832. * @return the light or null if none found.
  27833. */
  27834. Scene.prototype.getLightByName = function (name) {
  27835. for (var index = 0; index < this.lights.length; index++) {
  27836. if (this.lights[index].name === name) {
  27837. return this.lights[index];
  27838. }
  27839. }
  27840. return null;
  27841. };
  27842. /**
  27843. * Gets a light node using its id
  27844. * @param id defines the light's id
  27845. * @return the light or null if none found.
  27846. */
  27847. Scene.prototype.getLightByID = function (id) {
  27848. for (var index = 0; index < this.lights.length; index++) {
  27849. if (this.lights[index].id === id) {
  27850. return this.lights[index];
  27851. }
  27852. }
  27853. return null;
  27854. };
  27855. /**
  27856. * Gets a light node using its scene-generated unique ID
  27857. * @param uniqueId defines the light's unique id
  27858. * @return the light or null if none found.
  27859. */
  27860. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27861. for (var index = 0; index < this.lights.length; index++) {
  27862. if (this.lights[index].uniqueId === uniqueId) {
  27863. return this.lights[index];
  27864. }
  27865. }
  27866. return null;
  27867. };
  27868. /**
  27869. * Gets a particle system by id
  27870. * @param id defines the particle system id
  27871. * @return the corresponding system or null if none found
  27872. */
  27873. Scene.prototype.getParticleSystemByID = function (id) {
  27874. for (var index = 0; index < this.particleSystems.length; index++) {
  27875. if (this.particleSystems[index].id === id) {
  27876. return this.particleSystems[index];
  27877. }
  27878. }
  27879. return null;
  27880. };
  27881. /**
  27882. * Gets a geometry using its ID
  27883. * @param id defines the geometry's id
  27884. * @return the geometry or null if none found.
  27885. */
  27886. Scene.prototype.getGeometryByID = function (id) {
  27887. for (var index = 0; index < this.geometries.length; index++) {
  27888. if (this.geometries[index].id === id) {
  27889. return this.geometries[index];
  27890. }
  27891. }
  27892. return null;
  27893. };
  27894. /**
  27895. * Add a new geometry to this scene
  27896. * @param geometry defines the geometry to be added to the scene.
  27897. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27898. * @return a boolean defining if the geometry was added or not
  27899. */
  27900. Scene.prototype.pushGeometry = function (geometry, force) {
  27901. if (!force && this.getGeometryByID(geometry.id)) {
  27902. return false;
  27903. }
  27904. this.geometries.push(geometry);
  27905. //notify the collision coordinator
  27906. if (this.collisionCoordinator) {
  27907. this.collisionCoordinator.onGeometryAdded(geometry);
  27908. }
  27909. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27910. return true;
  27911. };
  27912. /**
  27913. * Removes an existing geometry
  27914. * @param geometry defines the geometry to be removed from the scene
  27915. * @return a boolean defining if the geometry was removed or not
  27916. */
  27917. Scene.prototype.removeGeometry = function (geometry) {
  27918. var index = this.geometries.indexOf(geometry);
  27919. if (index > -1) {
  27920. this.geometries.splice(index, 1);
  27921. //notify the collision coordinator
  27922. if (this.collisionCoordinator) {
  27923. this.collisionCoordinator.onGeometryDeleted(geometry);
  27924. }
  27925. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27926. return true;
  27927. }
  27928. return false;
  27929. };
  27930. /**
  27931. * Gets the list of geometries attached to the scene
  27932. * @returns an array of Geometry
  27933. */
  27934. Scene.prototype.getGeometries = function () {
  27935. return this.geometries;
  27936. };
  27937. /**
  27938. * Gets the first added mesh found of a given ID
  27939. * @param id defines the id to search for
  27940. * @return the mesh found or null if not found at all
  27941. */
  27942. Scene.prototype.getMeshByID = function (id) {
  27943. for (var index = 0; index < this.meshes.length; index++) {
  27944. if (this.meshes[index].id === id) {
  27945. return this.meshes[index];
  27946. }
  27947. }
  27948. return null;
  27949. };
  27950. /**
  27951. * Gets a list of meshes using their id
  27952. * @param id defines the id to search for
  27953. * @returns a list of meshes
  27954. */
  27955. Scene.prototype.getMeshesByID = function (id) {
  27956. return this.meshes.filter(function (m) {
  27957. return m.id === id;
  27958. });
  27959. };
  27960. /**
  27961. * Gets the first added transform node found of a given ID
  27962. * @param id defines the id to search for
  27963. * @return the found transform node or null if not found at all.
  27964. */
  27965. Scene.prototype.getTransformNodeByID = function (id) {
  27966. for (var index = 0; index < this.transformNodes.length; index++) {
  27967. if (this.transformNodes[index].id === id) {
  27968. return this.transformNodes[index];
  27969. }
  27970. }
  27971. return null;
  27972. };
  27973. /**
  27974. * Gets a list of transform nodes using their id
  27975. * @param id defines the id to search for
  27976. * @returns a list of transform nodes
  27977. */
  27978. Scene.prototype.getTransformNodesByID = function (id) {
  27979. return this.transformNodes.filter(function (m) {
  27980. return m.id === id;
  27981. });
  27982. };
  27983. /**
  27984. * Gets a mesh with its auto-generated unique id
  27985. * @param uniqueId defines the unique id to search for
  27986. * @return the found mesh or null if not found at all.
  27987. */
  27988. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27989. for (var index = 0; index < this.meshes.length; index++) {
  27990. if (this.meshes[index].uniqueId === uniqueId) {
  27991. return this.meshes[index];
  27992. }
  27993. }
  27994. return null;
  27995. };
  27996. /**
  27997. * Gets a the last added mesh using a given id
  27998. * @param id defines the id to search for
  27999. * @return the found mesh or null if not found at all.
  28000. */
  28001. Scene.prototype.getLastMeshByID = function (id) {
  28002. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28003. if (this.meshes[index].id === id) {
  28004. return this.meshes[index];
  28005. }
  28006. }
  28007. return null;
  28008. };
  28009. /**
  28010. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28011. * @param id defines the id to search for
  28012. * @return the found node or null if not found at all
  28013. */
  28014. Scene.prototype.getLastEntryByID = function (id) {
  28015. var index;
  28016. for (index = this.meshes.length - 1; index >= 0; index--) {
  28017. if (this.meshes[index].id === id) {
  28018. return this.meshes[index];
  28019. }
  28020. }
  28021. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28022. if (this.transformNodes[index].id === id) {
  28023. return this.transformNodes[index];
  28024. }
  28025. }
  28026. for (index = this.cameras.length - 1; index >= 0; index--) {
  28027. if (this.cameras[index].id === id) {
  28028. return this.cameras[index];
  28029. }
  28030. }
  28031. for (index = this.lights.length - 1; index >= 0; index--) {
  28032. if (this.lights[index].id === id) {
  28033. return this.lights[index];
  28034. }
  28035. }
  28036. return null;
  28037. };
  28038. /**
  28039. * Gets a node (Mesh, Camera, Light) using a given id
  28040. * @param id defines the id to search for
  28041. * @return the found node or null if not found at all
  28042. */
  28043. Scene.prototype.getNodeByID = function (id) {
  28044. var mesh = this.getMeshByID(id);
  28045. if (mesh) {
  28046. return mesh;
  28047. }
  28048. var light = this.getLightByID(id);
  28049. if (light) {
  28050. return light;
  28051. }
  28052. var camera = this.getCameraByID(id);
  28053. if (camera) {
  28054. return camera;
  28055. }
  28056. var bone = this.getBoneByID(id);
  28057. return bone;
  28058. };
  28059. /**
  28060. * Gets a node (Mesh, Camera, Light) using a given name
  28061. * @param name defines the name to search for
  28062. * @return the found node or null if not found at all.
  28063. */
  28064. Scene.prototype.getNodeByName = function (name) {
  28065. var mesh = this.getMeshByName(name);
  28066. if (mesh) {
  28067. return mesh;
  28068. }
  28069. var light = this.getLightByName(name);
  28070. if (light) {
  28071. return light;
  28072. }
  28073. var camera = this.getCameraByName(name);
  28074. if (camera) {
  28075. return camera;
  28076. }
  28077. var bone = this.getBoneByName(name);
  28078. return bone;
  28079. };
  28080. /**
  28081. * Gets a mesh using a given name
  28082. * @param name defines the name to search for
  28083. * @return the found mesh or null if not found at all.
  28084. */
  28085. Scene.prototype.getMeshByName = function (name) {
  28086. for (var index = 0; index < this.meshes.length; index++) {
  28087. if (this.meshes[index].name === name) {
  28088. return this.meshes[index];
  28089. }
  28090. }
  28091. return null;
  28092. };
  28093. /**
  28094. * Gets a transform node using a given name
  28095. * @param name defines the name to search for
  28096. * @return the found transform node or null if not found at all.
  28097. */
  28098. Scene.prototype.getTransformNodeByName = function (name) {
  28099. for (var index = 0; index < this.transformNodes.length; index++) {
  28100. if (this.transformNodes[index].name === name) {
  28101. return this.transformNodes[index];
  28102. }
  28103. }
  28104. return null;
  28105. };
  28106. /**
  28107. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28108. * @param id defines the id to search for
  28109. * @return the found skeleton or null if not found at all.
  28110. */
  28111. Scene.prototype.getLastSkeletonByID = function (id) {
  28112. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28113. if (this.skeletons[index].id === id) {
  28114. return this.skeletons[index];
  28115. }
  28116. }
  28117. return null;
  28118. };
  28119. /**
  28120. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28121. * @param id defines the id to search for
  28122. * @return the found skeleton or null if not found at all.
  28123. */
  28124. Scene.prototype.getSkeletonById = function (id) {
  28125. for (var index = 0; index < this.skeletons.length; index++) {
  28126. if (this.skeletons[index].id === id) {
  28127. return this.skeletons[index];
  28128. }
  28129. }
  28130. return null;
  28131. };
  28132. /**
  28133. * Gets a skeleton using a given name
  28134. * @param name defines the name to search for
  28135. * @return the found skeleton or null if not found at all.
  28136. */
  28137. Scene.prototype.getSkeletonByName = function (name) {
  28138. for (var index = 0; index < this.skeletons.length; index++) {
  28139. if (this.skeletons[index].name === name) {
  28140. return this.skeletons[index];
  28141. }
  28142. }
  28143. return null;
  28144. };
  28145. /**
  28146. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28147. * @param id defines the id to search for
  28148. * @return the found morph target manager or null if not found at all.
  28149. */
  28150. Scene.prototype.getMorphTargetManagerById = function (id) {
  28151. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28152. if (this.morphTargetManagers[index].uniqueId === id) {
  28153. return this.morphTargetManagers[index];
  28154. }
  28155. }
  28156. return null;
  28157. };
  28158. /**
  28159. * Gets a boolean indicating if the given mesh is active
  28160. * @param mesh defines the mesh to look for
  28161. * @returns true if the mesh is in the active list
  28162. */
  28163. Scene.prototype.isActiveMesh = function (mesh) {
  28164. return (this._activeMeshes.indexOf(mesh) !== -1);
  28165. };
  28166. Object.defineProperty(Scene.prototype, "uid", {
  28167. /**
  28168. * Return a unique id as a string which can serve as an identifier for the scene
  28169. */
  28170. get: function () {
  28171. if (!this._uid) {
  28172. this._uid = BABYLON.Tools.RandomId();
  28173. }
  28174. return this._uid;
  28175. },
  28176. enumerable: true,
  28177. configurable: true
  28178. });
  28179. /**
  28180. * Add an externaly attached data from its key.
  28181. * This method call will fail and return false, if such key already exists.
  28182. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28183. * @param key the unique key that identifies the data
  28184. * @param data the data object to associate to the key for this Engine instance
  28185. * @return true if no such key were already present and the data was added successfully, false otherwise
  28186. */
  28187. Scene.prototype.addExternalData = function (key, data) {
  28188. if (!this._externalData) {
  28189. this._externalData = new BABYLON.StringDictionary();
  28190. }
  28191. return this._externalData.add(key, data);
  28192. };
  28193. /**
  28194. * Get an externaly attached data from its key
  28195. * @param key the unique key that identifies the data
  28196. * @return the associated data, if present (can be null), or undefined if not present
  28197. */
  28198. Scene.prototype.getExternalData = function (key) {
  28199. if (!this._externalData) {
  28200. return null;
  28201. }
  28202. return this._externalData.get(key);
  28203. };
  28204. /**
  28205. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28206. * @param key the unique key that identifies the data
  28207. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28208. * @return the associated data, can be null if the factory returned null.
  28209. */
  28210. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28211. if (!this._externalData) {
  28212. this._externalData = new BABYLON.StringDictionary();
  28213. }
  28214. return this._externalData.getOrAddWithFactory(key, factory);
  28215. };
  28216. /**
  28217. * Remove an externaly attached data from the Engine instance
  28218. * @param key the unique key that identifies the data
  28219. * @return true if the data was successfully removed, false if it doesn't exist
  28220. */
  28221. Scene.prototype.removeExternalData = function (key) {
  28222. return this._externalData.remove(key);
  28223. };
  28224. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28225. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28226. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28227. var step = _a[_i];
  28228. step.action(mesh, subMesh);
  28229. }
  28230. var material = subMesh.getMaterial();
  28231. if (material !== null && material !== undefined) {
  28232. // Render targets
  28233. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28234. if (this._processedMaterials.indexOf(material) === -1) {
  28235. this._processedMaterials.push(material);
  28236. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28237. }
  28238. }
  28239. // Dispatch
  28240. this._activeIndices.addCount(subMesh.indexCount, false);
  28241. this._renderingManager.dispatch(subMesh, mesh, material);
  28242. }
  28243. }
  28244. };
  28245. /**
  28246. * Clear the processed materials smart array preventing retention point in material dispose.
  28247. */
  28248. Scene.prototype.freeProcessedMaterials = function () {
  28249. this._processedMaterials.dispose();
  28250. };
  28251. /**
  28252. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28253. */
  28254. Scene.prototype.freeActiveMeshes = function () {
  28255. this._activeMeshes.dispose();
  28256. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28257. this.activeCamera._activeMeshes.dispose();
  28258. }
  28259. if (this.activeCameras) {
  28260. for (var i = 0; i < this.activeCameras.length; i++) {
  28261. var activeCamera = this.activeCameras[i];
  28262. if (activeCamera && activeCamera._activeMeshes) {
  28263. activeCamera._activeMeshes.dispose();
  28264. }
  28265. }
  28266. }
  28267. };
  28268. /**
  28269. * Clear the info related to rendering groups preventing retention points during dispose.
  28270. */
  28271. Scene.prototype.freeRenderingGroups = function () {
  28272. if (this._renderingManager) {
  28273. this._renderingManager.freeRenderingGroups();
  28274. }
  28275. if (this.textures) {
  28276. for (var i = 0; i < this.textures.length; i++) {
  28277. var texture = this.textures[i];
  28278. if (texture && texture.renderList) {
  28279. texture.freeRenderingGroups();
  28280. }
  28281. }
  28282. }
  28283. };
  28284. /** @hidden */
  28285. Scene.prototype._isInIntermediateRendering = function () {
  28286. return this._intermediateRendering;
  28287. };
  28288. /**
  28289. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28290. * @returns the current scene
  28291. */
  28292. Scene.prototype.freezeActiveMeshes = function () {
  28293. if (!this.activeCamera) {
  28294. return this;
  28295. }
  28296. if (!this._frustumPlanes) {
  28297. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28298. }
  28299. this._evaluateActiveMeshes();
  28300. this._activeMeshesFrozen = true;
  28301. return this;
  28302. };
  28303. /**
  28304. * Use this function to restart evaluating active meshes on every frame
  28305. * @returns the current scene
  28306. */
  28307. Scene.prototype.unfreezeActiveMeshes = function () {
  28308. this._activeMeshesFrozen = false;
  28309. return this;
  28310. };
  28311. Scene.prototype._evaluateActiveMeshes = function () {
  28312. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28313. return;
  28314. }
  28315. if (!this.activeCamera) {
  28316. return;
  28317. }
  28318. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28319. this.activeCamera._activeMeshes.reset();
  28320. this._activeMeshes.reset();
  28321. this._renderingManager.reset();
  28322. this._processedMaterials.reset();
  28323. this._activeParticleSystems.reset();
  28324. this._activeSkeletons.reset();
  28325. this._softwareSkinnedMeshes.reset();
  28326. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28327. var step = _a[_i];
  28328. step.action();
  28329. }
  28330. // Determine mesh candidates
  28331. var meshes = this.getActiveMeshCandidates();
  28332. // Check each mesh
  28333. var len = meshes.length;
  28334. for (var i = 0; i < len; i++) {
  28335. var mesh = meshes.data[i];
  28336. if (mesh.isBlocked) {
  28337. continue;
  28338. }
  28339. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28340. if (!mesh.isReady() || !mesh.isEnabled()) {
  28341. continue;
  28342. }
  28343. mesh.computeWorldMatrix();
  28344. // Intersections
  28345. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28346. this._meshesForIntersections.pushNoDuplicate(mesh);
  28347. }
  28348. // Switch to current LOD
  28349. var meshLOD = mesh.getLOD(this.activeCamera);
  28350. if (meshLOD === undefined || meshLOD === null) {
  28351. continue;
  28352. }
  28353. mesh._preActivate();
  28354. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28355. this._activeMeshes.push(mesh);
  28356. this.activeCamera._activeMeshes.push(mesh);
  28357. mesh._activate(this._renderId);
  28358. if (meshLOD !== mesh) {
  28359. meshLOD._activate(this._renderId);
  28360. }
  28361. this._activeMesh(mesh, meshLOD);
  28362. }
  28363. }
  28364. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28365. // Particle systems
  28366. if (this.particlesEnabled) {
  28367. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28368. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28369. var particleSystem = this.particleSystems[particleIndex];
  28370. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28371. continue;
  28372. }
  28373. var emitter = particleSystem.emitter;
  28374. if (!emitter.position || emitter.isEnabled()) {
  28375. this._activeParticleSystems.push(particleSystem);
  28376. particleSystem.animate();
  28377. this._renderingManager.dispatchParticles(particleSystem);
  28378. }
  28379. }
  28380. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28381. }
  28382. };
  28383. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28384. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28385. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28386. mesh.skeleton.prepare();
  28387. }
  28388. if (!mesh.computeBonesUsingShaders) {
  28389. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28390. }
  28391. }
  28392. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28393. var step = _a[_i];
  28394. step.action(sourceMesh, mesh);
  28395. }
  28396. if (mesh !== undefined && mesh !== null
  28397. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28398. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28399. var len = subMeshes.length;
  28400. for (var i = 0; i < len; i++) {
  28401. var subMesh = subMeshes.data[i];
  28402. this._evaluateSubMesh(subMesh, mesh);
  28403. }
  28404. }
  28405. };
  28406. /**
  28407. * Update the transform matrix to update from the current active camera
  28408. * @param force defines a boolean used to force the update even if cache is up to date
  28409. */
  28410. Scene.prototype.updateTransformMatrix = function (force) {
  28411. if (!this.activeCamera) {
  28412. return;
  28413. }
  28414. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28415. };
  28416. /**
  28417. * 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)
  28418. * @param alternateCamera defines the camera to use
  28419. */
  28420. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28421. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28422. };
  28423. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28424. if (camera && camera._skipRendering) {
  28425. return;
  28426. }
  28427. var engine = this._engine;
  28428. this.activeCamera = camera;
  28429. if (!this.activeCamera)
  28430. throw new Error("Active camera not set");
  28431. // Viewport
  28432. engine.setViewport(this.activeCamera.viewport);
  28433. // Camera
  28434. this.resetCachedMaterial();
  28435. this._renderId++;
  28436. this.updateTransformMatrix();
  28437. if (camera._alternateCamera) {
  28438. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28439. this._alternateRendering = true;
  28440. }
  28441. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28442. // Meshes
  28443. this._evaluateActiveMeshes();
  28444. // Software skinning
  28445. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28446. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28447. mesh.applySkeleton(mesh.skeleton);
  28448. }
  28449. // Render targets
  28450. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28451. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28452. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28453. }
  28454. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28455. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28456. }
  28457. // Collects render targets from external components.
  28458. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28459. var step = _a[_i];
  28460. step.action(this._renderTargets);
  28461. }
  28462. if (this.renderTargetsEnabled) {
  28463. this._intermediateRendering = true;
  28464. if (this._renderTargets.length > 0) {
  28465. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28466. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28467. var renderTarget = this._renderTargets.data[renderIndex];
  28468. if (renderTarget._shouldRender()) {
  28469. this._renderId++;
  28470. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28471. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28472. }
  28473. }
  28474. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28475. this._renderId++;
  28476. }
  28477. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28478. var step = _c[_b];
  28479. step.action(this.activeCamera);
  28480. }
  28481. this._intermediateRendering = false;
  28482. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28483. }
  28484. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28485. // Prepare Frame
  28486. if (this.postProcessManager) {
  28487. this.postProcessManager._prepareFrame();
  28488. }
  28489. // Before Camera Draw
  28490. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28491. var step = _e[_d];
  28492. step.action(this.activeCamera);
  28493. }
  28494. // Render
  28495. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28496. this._renderingManager.render(null, null, true, true);
  28497. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28498. // After Camera Draw
  28499. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28500. var step = _g[_f];
  28501. step.action(this.activeCamera);
  28502. }
  28503. // Finalize frame
  28504. if (this.postProcessManager) {
  28505. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28506. }
  28507. // Reset some special arrays
  28508. this._renderTargets.reset();
  28509. this._alternateRendering = false;
  28510. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28511. };
  28512. Scene.prototype._processSubCameras = function (camera) {
  28513. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28514. this._renderForCamera(camera);
  28515. return;
  28516. }
  28517. // rig cameras
  28518. for (var index = 0; index < camera._rigCameras.length; index++) {
  28519. this._renderForCamera(camera._rigCameras[index], camera);
  28520. }
  28521. this.activeCamera = camera;
  28522. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28523. };
  28524. Scene.prototype._checkIntersections = function () {
  28525. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28526. var sourceMesh = this._meshesForIntersections.data[index];
  28527. if (!sourceMesh.actionManager) {
  28528. continue;
  28529. }
  28530. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28531. var action = sourceMesh.actionManager.actions[actionIndex];
  28532. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28533. var parameters = action.getTriggerParameter();
  28534. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28535. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28536. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28537. if (areIntersecting && currentIntersectionInProgress === -1) {
  28538. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28539. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28540. sourceMesh._intersectionsInProgress.push(otherMesh);
  28541. }
  28542. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28543. sourceMesh._intersectionsInProgress.push(otherMesh);
  28544. }
  28545. }
  28546. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28547. //They intersected, and now they don't.
  28548. //is this trigger an exit trigger? execute an event.
  28549. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28550. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28551. }
  28552. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28553. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28554. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28555. return otherMesh === parameterMesh;
  28556. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28557. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28558. }
  28559. }
  28560. }
  28561. }
  28562. }
  28563. };
  28564. /** @hidden */
  28565. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28566. // Do nothing. Code will be replaced if physics engine component is referenced
  28567. };
  28568. /**
  28569. * Render the scene
  28570. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28571. */
  28572. Scene.prototype.render = function (updateCameras) {
  28573. if (updateCameras === void 0) { updateCameras = true; }
  28574. if (this.isDisposed) {
  28575. return;
  28576. }
  28577. this._frameId++;
  28578. // Register components that have been associated lately to the scene.
  28579. this._registerTransientComponents();
  28580. this._activeParticles.fetchNewFrame();
  28581. this._totalVertices.fetchNewFrame();
  28582. this._activeIndices.fetchNewFrame();
  28583. this._activeBones.fetchNewFrame();
  28584. this._meshesForIntersections.reset();
  28585. this.resetCachedMaterial();
  28586. this.onBeforeAnimationsObservable.notifyObservers(this);
  28587. // Actions
  28588. if (this.actionManager) {
  28589. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28590. }
  28591. if (this._engine.isDeterministicLockStep()) {
  28592. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28593. var defaultFPS = (60.0 / 1000.0);
  28594. var defaultFrameTime = this.getDeterministicFrameTime();
  28595. var stepsTaken = 0;
  28596. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28597. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28598. internalSteps = Math.min(internalSteps, maxSubSteps);
  28599. do {
  28600. this.onBeforeStepObservable.notifyObservers(this);
  28601. // Animations
  28602. this._animationRatio = defaultFrameTime * defaultFPS;
  28603. this._animate();
  28604. this.onAfterAnimationsObservable.notifyObservers(this);
  28605. // Physics
  28606. this._advancePhysicsEngineStep(defaultFrameTime);
  28607. this.onAfterStepObservable.notifyObservers(this);
  28608. this._currentStepId++;
  28609. stepsTaken++;
  28610. deltaTime -= defaultFrameTime;
  28611. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28612. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28613. }
  28614. else {
  28615. // Animations
  28616. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28617. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28618. this._animate();
  28619. this.onAfterAnimationsObservable.notifyObservers(this);
  28620. // Physics
  28621. this._advancePhysicsEngineStep(deltaTime);
  28622. }
  28623. // Before camera update steps
  28624. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28625. var step = _a[_i];
  28626. step.action();
  28627. }
  28628. // Update Cameras
  28629. if (updateCameras) {
  28630. if (this.activeCameras.length > 0) {
  28631. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28632. var camera = this.activeCameras[cameraIndex];
  28633. camera.update();
  28634. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28635. // rig cameras
  28636. for (var index = 0; index < camera._rigCameras.length; index++) {
  28637. camera._rigCameras[index].update();
  28638. }
  28639. }
  28640. }
  28641. }
  28642. else if (this.activeCamera) {
  28643. this.activeCamera.update();
  28644. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28645. // rig cameras
  28646. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28647. this.activeCamera._rigCameras[index].update();
  28648. }
  28649. }
  28650. }
  28651. }
  28652. // Before render
  28653. this.onBeforeRenderObservable.notifyObservers(this);
  28654. // Customs render targets
  28655. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28656. var engine = this.getEngine();
  28657. var currentActiveCamera = this.activeCamera;
  28658. if (this.renderTargetsEnabled) {
  28659. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28660. this._intermediateRendering = true;
  28661. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28662. var renderTarget = this.customRenderTargets[customIndex];
  28663. if (renderTarget._shouldRender()) {
  28664. this._renderId++;
  28665. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28666. if (!this.activeCamera)
  28667. throw new Error("Active camera not set");
  28668. // Viewport
  28669. engine.setViewport(this.activeCamera.viewport);
  28670. // Camera
  28671. this.updateTransformMatrix();
  28672. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28673. }
  28674. }
  28675. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28676. this._intermediateRendering = false;
  28677. this._renderId++;
  28678. }
  28679. // Restore back buffer
  28680. if (this.customRenderTargets.length > 0) {
  28681. engine.restoreDefaultFramebuffer();
  28682. }
  28683. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28684. this.activeCamera = currentActiveCamera;
  28685. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28686. var step = _c[_b];
  28687. step.action();
  28688. }
  28689. // Clear
  28690. if (this.autoClearDepthAndStencil || this.autoClear) {
  28691. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28692. }
  28693. // Collects render targets from external components.
  28694. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28695. var step = _e[_d];
  28696. step.action(this._renderTargets);
  28697. }
  28698. // Multi-cameras?
  28699. if (this.activeCameras.length > 0) {
  28700. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28701. if (cameraIndex > 0) {
  28702. this._engine.clear(null, false, true, true);
  28703. }
  28704. this._processSubCameras(this.activeCameras[cameraIndex]);
  28705. }
  28706. }
  28707. else {
  28708. if (!this.activeCamera) {
  28709. throw new Error("No camera defined");
  28710. }
  28711. this._processSubCameras(this.activeCamera);
  28712. }
  28713. // Intersection checks
  28714. this._checkIntersections();
  28715. // Executes the after render stage actions.
  28716. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28717. var step = _g[_f];
  28718. step.action();
  28719. }
  28720. // After render
  28721. if (this.afterRender) {
  28722. this.afterRender();
  28723. }
  28724. this.onAfterRenderObservable.notifyObservers(this);
  28725. // Cleaning
  28726. if (this._toBeDisposed.length) {
  28727. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28728. var data = this._toBeDisposed[index];
  28729. if (data) {
  28730. data.dispose();
  28731. }
  28732. }
  28733. this._toBeDisposed = [];
  28734. }
  28735. if (this.dumpNextRenderTargets) {
  28736. this.dumpNextRenderTargets = false;
  28737. }
  28738. this._activeBones.addCount(0, true);
  28739. this._activeIndices.addCount(0, true);
  28740. this._activeParticles.addCount(0, true);
  28741. };
  28742. /**
  28743. * Freeze all materials
  28744. * A frozen material will not be updatable but should be faster to render
  28745. */
  28746. Scene.prototype.freezeMaterials = function () {
  28747. for (var i = 0; i < this.materials.length; i++) {
  28748. this.materials[i].freeze();
  28749. }
  28750. };
  28751. /**
  28752. * Unfreeze all materials
  28753. * A frozen material will not be updatable but should be faster to render
  28754. */
  28755. Scene.prototype.unfreezeMaterials = function () {
  28756. for (var i = 0; i < this.materials.length; i++) {
  28757. this.materials[i].unfreeze();
  28758. }
  28759. };
  28760. /**
  28761. * Releases all held ressources
  28762. */
  28763. Scene.prototype.dispose = function () {
  28764. this.beforeRender = null;
  28765. this.afterRender = null;
  28766. this.skeletons = [];
  28767. this.morphTargetManagers = [];
  28768. this._transientComponents = [];
  28769. this._isReadyForMeshStage.clear();
  28770. this._beforeEvaluateActiveMeshStage.clear();
  28771. this._evaluateSubMeshStage.clear();
  28772. this._activeMeshStage.clear();
  28773. this._cameraDrawRenderTargetStage.clear();
  28774. this._beforeCameraDrawStage.clear();
  28775. this._beforeRenderingGroupDrawStage.clear();
  28776. this._beforeRenderingMeshStage.clear();
  28777. this._afterRenderingMeshStage.clear();
  28778. this._afterRenderingGroupDrawStage.clear();
  28779. this._afterCameraDrawStage.clear();
  28780. this._afterRenderStage.clear();
  28781. this._beforeCameraUpdateStage.clear();
  28782. this._beforeClearStage.clear();
  28783. this._gatherRenderTargetsStage.clear();
  28784. this._gatherActiveCameraRenderTargetsStage.clear();
  28785. this._pointerMoveStage.clear();
  28786. this._pointerDownStage.clear();
  28787. this._pointerUpStage.clear();
  28788. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28789. var component = _a[_i];
  28790. component.dispose();
  28791. }
  28792. this.importedMeshesFiles = new Array();
  28793. this.stopAllAnimations();
  28794. this.resetCachedMaterial();
  28795. // Smart arrays
  28796. if (this.activeCamera) {
  28797. this.activeCamera._activeMeshes.dispose();
  28798. this.activeCamera = null;
  28799. }
  28800. this._activeMeshes.dispose();
  28801. this._renderingManager.dispose();
  28802. this._processedMaterials.dispose();
  28803. this._activeParticleSystems.dispose();
  28804. this._activeSkeletons.dispose();
  28805. this._softwareSkinnedMeshes.dispose();
  28806. this._renderTargets.dispose();
  28807. this._registeredForLateAnimationBindings.dispose();
  28808. this._meshesForIntersections.dispose();
  28809. this._toBeDisposed = [];
  28810. // Abort active requests
  28811. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28812. var request = _c[_b];
  28813. request.abort();
  28814. }
  28815. // Events
  28816. this.onDisposeObservable.notifyObservers(this);
  28817. this.onDisposeObservable.clear();
  28818. this.onBeforeRenderObservable.clear();
  28819. this.onAfterRenderObservable.clear();
  28820. this.onBeforeRenderTargetsRenderObservable.clear();
  28821. this.onAfterRenderTargetsRenderObservable.clear();
  28822. this.onAfterStepObservable.clear();
  28823. this.onBeforeStepObservable.clear();
  28824. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28825. this.onAfterActiveMeshesEvaluationObservable.clear();
  28826. this.onBeforeParticlesRenderingObservable.clear();
  28827. this.onAfterParticlesRenderingObservable.clear();
  28828. this.onBeforeDrawPhaseObservable.clear();
  28829. this.onAfterDrawPhaseObservable.clear();
  28830. this.onBeforeAnimationsObservable.clear();
  28831. this.onAfterAnimationsObservable.clear();
  28832. this.onDataLoadedObservable.clear();
  28833. this.onBeforeRenderingGroupObservable.clear();
  28834. this.onAfterRenderingGroupObservable.clear();
  28835. this.onMeshImportedObservable.clear();
  28836. this.onBeforeCameraRenderObservable.clear();
  28837. this.onAfterCameraRenderObservable.clear();
  28838. this.onReadyObservable.clear();
  28839. this.onNewCameraAddedObservable.clear();
  28840. this.onCameraRemovedObservable.clear();
  28841. this.onNewLightAddedObservable.clear();
  28842. this.onLightRemovedObservable.clear();
  28843. this.onNewGeometryAddedObservable.clear();
  28844. this.onGeometryRemovedObservable.clear();
  28845. this.onNewTransformNodeAddedObservable.clear();
  28846. this.onTransformNodeRemovedObservable.clear();
  28847. this.onNewMeshAddedObservable.clear();
  28848. this.onMeshRemovedObservable.clear();
  28849. this.onNewMaterialAddedObservable.clear();
  28850. this.onMaterialRemovedObservable.clear();
  28851. this.onNewTextureAddedObservable.clear();
  28852. this.onTextureRemovedObservable.clear();
  28853. this.onPrePointerObservable.clear();
  28854. this.onPointerObservable.clear();
  28855. this.onPreKeyboardObservable.clear();
  28856. this.onKeyboardObservable.clear();
  28857. this.detachControl();
  28858. // Detach cameras
  28859. var canvas = this._engine.getRenderingCanvas();
  28860. if (canvas) {
  28861. var index;
  28862. for (index = 0; index < this.cameras.length; index++) {
  28863. this.cameras[index].detachControl(canvas);
  28864. }
  28865. }
  28866. // Release animation groups
  28867. while (this.animationGroups.length) {
  28868. this.animationGroups[0].dispose();
  28869. }
  28870. // Release lights
  28871. while (this.lights.length) {
  28872. this.lights[0].dispose();
  28873. }
  28874. // Release meshes
  28875. while (this.meshes.length) {
  28876. this.meshes[0].dispose(true);
  28877. }
  28878. while (this.transformNodes.length) {
  28879. this.removeTransformNode(this.transformNodes[0]);
  28880. }
  28881. // Release cameras
  28882. while (this.cameras.length) {
  28883. this.cameras[0].dispose();
  28884. }
  28885. // Release materials
  28886. if (this.defaultMaterial) {
  28887. this.defaultMaterial.dispose();
  28888. }
  28889. while (this.multiMaterials.length) {
  28890. this.multiMaterials[0].dispose();
  28891. }
  28892. while (this.materials.length) {
  28893. this.materials[0].dispose();
  28894. }
  28895. // Release particles
  28896. while (this.particleSystems.length) {
  28897. this.particleSystems[0].dispose();
  28898. }
  28899. // Release postProcesses
  28900. while (this.postProcesses.length) {
  28901. this.postProcesses[0].dispose();
  28902. }
  28903. // Release textures
  28904. while (this.textures.length) {
  28905. this.textures[0].dispose();
  28906. }
  28907. // Release UBO
  28908. this._sceneUbo.dispose();
  28909. if (this._alternateSceneUbo) {
  28910. this._alternateSceneUbo.dispose();
  28911. }
  28912. // Post-processes
  28913. this.postProcessManager.dispose();
  28914. // Remove from engine
  28915. index = this._engine.scenes.indexOf(this);
  28916. if (index > -1) {
  28917. this._engine.scenes.splice(index, 1);
  28918. }
  28919. this._engine.wipeCaches(true);
  28920. this._isDisposed = true;
  28921. };
  28922. Object.defineProperty(Scene.prototype, "isDisposed", {
  28923. /**
  28924. * Gets if the scene is already disposed
  28925. */
  28926. get: function () {
  28927. return this._isDisposed;
  28928. },
  28929. enumerable: true,
  28930. configurable: true
  28931. });
  28932. /**
  28933. * Call this function to reduce memory footprint of the scene.
  28934. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28935. */
  28936. Scene.prototype.clearCachedVertexData = function () {
  28937. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28938. var mesh = this.meshes[meshIndex];
  28939. var geometry = mesh.geometry;
  28940. if (geometry) {
  28941. geometry._indices = [];
  28942. for (var vbName in geometry._vertexBuffers) {
  28943. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28944. continue;
  28945. }
  28946. geometry._vertexBuffers[vbName]._buffer._data = null;
  28947. }
  28948. }
  28949. }
  28950. };
  28951. /**
  28952. * This function will remove the local cached buffer data from texture.
  28953. * It will save memory but will prevent the texture from being rebuilt
  28954. */
  28955. Scene.prototype.cleanCachedTextureBuffer = function () {
  28956. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28957. var baseTexture = _a[_i];
  28958. var buffer = baseTexture._buffer;
  28959. if (buffer) {
  28960. baseTexture._buffer = null;
  28961. }
  28962. }
  28963. };
  28964. /**
  28965. * Get the world extend vectors with an optional filter
  28966. *
  28967. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28968. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28969. */
  28970. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28971. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28972. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28973. filterPredicate = filterPredicate || (function () { return true; });
  28974. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28975. mesh.computeWorldMatrix(true);
  28976. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28977. return;
  28978. }
  28979. var boundingInfo = mesh.getBoundingInfo();
  28980. var minBox = boundingInfo.boundingBox.minimumWorld;
  28981. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28982. BABYLON.Tools.CheckExtends(minBox, min, max);
  28983. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28984. });
  28985. return {
  28986. min: min,
  28987. max: max
  28988. };
  28989. };
  28990. // Picking
  28991. /**
  28992. * Creates a ray that can be used to pick in the scene
  28993. * @param x defines the x coordinate of the origin (on-screen)
  28994. * @param y defines the y coordinate of the origin (on-screen)
  28995. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28996. * @param camera defines the camera to use for the picking
  28997. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28998. * @returns a Ray
  28999. */
  29000. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29001. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29002. var result = BABYLON.Ray.Zero();
  29003. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29004. return result;
  29005. };
  29006. /**
  29007. * Creates a ray that can be used to pick in the scene
  29008. * @param x defines the x coordinate of the origin (on-screen)
  29009. * @param y defines the y coordinate of the origin (on-screen)
  29010. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29011. * @param result defines the ray where to store the picking ray
  29012. * @param camera defines the camera to use for the picking
  29013. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29014. * @returns the current scene
  29015. */
  29016. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29017. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29018. var engine = this._engine;
  29019. if (!camera) {
  29020. if (!this.activeCamera)
  29021. throw new Error("Active camera not set");
  29022. camera = this.activeCamera;
  29023. }
  29024. var cameraViewport = camera.viewport;
  29025. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29026. // Moving coordinates to local viewport world
  29027. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29028. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29029. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29030. return this;
  29031. };
  29032. /**
  29033. * Creates a ray that can be used to pick in the scene
  29034. * @param x defines the x coordinate of the origin (on-screen)
  29035. * @param y defines the y coordinate of the origin (on-screen)
  29036. * @param camera defines the camera to use for the picking
  29037. * @returns a Ray
  29038. */
  29039. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29040. var result = BABYLON.Ray.Zero();
  29041. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29042. return result;
  29043. };
  29044. /**
  29045. * Creates a ray that can be used to pick in the scene
  29046. * @param x defines the x coordinate of the origin (on-screen)
  29047. * @param y defines the y coordinate of the origin (on-screen)
  29048. * @param result defines the ray where to store the picking ray
  29049. * @param camera defines the camera to use for the picking
  29050. * @returns the current scene
  29051. */
  29052. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29053. if (!BABYLON.PickingInfo) {
  29054. return this;
  29055. }
  29056. var engine = this._engine;
  29057. if (!camera) {
  29058. if (!this.activeCamera)
  29059. throw new Error("Active camera not set");
  29060. camera = this.activeCamera;
  29061. }
  29062. var cameraViewport = camera.viewport;
  29063. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29064. var identity = BABYLON.Matrix.Identity();
  29065. // Moving coordinates to local viewport world
  29066. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29067. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29068. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29069. return this;
  29070. };
  29071. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29072. if (!BABYLON.PickingInfo) {
  29073. return null;
  29074. }
  29075. var pickingInfo = null;
  29076. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29077. var mesh = this.meshes[meshIndex];
  29078. if (predicate) {
  29079. if (!predicate(mesh)) {
  29080. continue;
  29081. }
  29082. }
  29083. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29084. continue;
  29085. }
  29086. var world = mesh.getWorldMatrix();
  29087. var ray = rayFunction(world);
  29088. var result = mesh.intersects(ray, fastCheck);
  29089. if (!result || !result.hit)
  29090. continue;
  29091. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29092. continue;
  29093. pickingInfo = result;
  29094. if (fastCheck) {
  29095. break;
  29096. }
  29097. }
  29098. return pickingInfo || new BABYLON.PickingInfo();
  29099. };
  29100. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29101. if (!BABYLON.PickingInfo) {
  29102. return null;
  29103. }
  29104. var pickingInfos = new Array();
  29105. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29106. var mesh = this.meshes[meshIndex];
  29107. if (predicate) {
  29108. if (!predicate(mesh)) {
  29109. continue;
  29110. }
  29111. }
  29112. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29113. continue;
  29114. }
  29115. var world = mesh.getWorldMatrix();
  29116. var ray = rayFunction(world);
  29117. var result = mesh.intersects(ray, false);
  29118. if (!result || !result.hit)
  29119. continue;
  29120. pickingInfos.push(result);
  29121. }
  29122. return pickingInfos;
  29123. };
  29124. /** Launch a ray to try to pick a mesh in the scene
  29125. * @param x position on screen
  29126. * @param y position on screen
  29127. * @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
  29128. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29129. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29130. * @returns a PickingInfo
  29131. */
  29132. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29133. var _this = this;
  29134. if (!BABYLON.PickingInfo) {
  29135. return null;
  29136. }
  29137. var result = this._internalPick(function (world) {
  29138. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29139. return _this._tempPickingRay;
  29140. }, predicate, fastCheck);
  29141. if (result) {
  29142. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29143. }
  29144. return result;
  29145. };
  29146. /** Use the given ray to pick a mesh in the scene
  29147. * @param ray The ray to use to pick meshes
  29148. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  29149. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29150. * @returns a PickingInfo
  29151. */
  29152. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29153. var _this = this;
  29154. var result = this._internalPick(function (world) {
  29155. if (!_this._pickWithRayInverseMatrix) {
  29156. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29157. }
  29158. world.invertToRef(_this._pickWithRayInverseMatrix);
  29159. if (!_this._cachedRayForTransform) {
  29160. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29161. }
  29162. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29163. return _this._cachedRayForTransform;
  29164. }, predicate, fastCheck);
  29165. if (result) {
  29166. result.ray = ray;
  29167. }
  29168. return result;
  29169. };
  29170. /**
  29171. * Launch a ray to try to pick a mesh in the scene
  29172. * @param x X position on screen
  29173. * @param y Y position on screen
  29174. * @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
  29175. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29176. * @returns an array of PickingInfo
  29177. */
  29178. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29179. var _this = this;
  29180. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29181. };
  29182. /**
  29183. * Launch a ray to try to pick a mesh in the scene
  29184. * @param ray Ray to use
  29185. * @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
  29186. * @returns an array of PickingInfo
  29187. */
  29188. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29189. var _this = this;
  29190. return this._internalMultiPick(function (world) {
  29191. if (!_this._pickWithRayInverseMatrix) {
  29192. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29193. }
  29194. world.invertToRef(_this._pickWithRayInverseMatrix);
  29195. if (!_this._cachedRayForTransform) {
  29196. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29197. }
  29198. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29199. return _this._cachedRayForTransform;
  29200. }, predicate);
  29201. };
  29202. /**
  29203. * Force the value of meshUnderPointer
  29204. * @param mesh defines the mesh to use
  29205. */
  29206. Scene.prototype.setPointerOverMesh = function (mesh) {
  29207. if (this._pointerOverMesh === mesh) {
  29208. return;
  29209. }
  29210. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29211. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29212. }
  29213. this._pointerOverMesh = mesh;
  29214. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29215. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29216. }
  29217. };
  29218. /**
  29219. * Gets the mesh under the pointer
  29220. * @returns a Mesh or null if no mesh is under the pointer
  29221. */
  29222. Scene.prototype.getPointerOverMesh = function () {
  29223. return this._pointerOverMesh;
  29224. };
  29225. // Misc.
  29226. /** @hidden */
  29227. Scene.prototype._rebuildGeometries = function () {
  29228. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29229. var geometry = _a[_i];
  29230. geometry._rebuild();
  29231. }
  29232. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29233. var mesh = _c[_b];
  29234. mesh._rebuild();
  29235. }
  29236. if (this.postProcessManager) {
  29237. this.postProcessManager._rebuild();
  29238. }
  29239. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29240. var component = _e[_d];
  29241. component.rebuild();
  29242. }
  29243. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29244. var system = _g[_f];
  29245. system.rebuild();
  29246. }
  29247. };
  29248. /** @hidden */
  29249. Scene.prototype._rebuildTextures = function () {
  29250. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29251. var texture = _a[_i];
  29252. texture._rebuild();
  29253. }
  29254. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29255. };
  29256. // Tags
  29257. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29258. if (tagsQuery === undefined) {
  29259. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29260. return list;
  29261. }
  29262. var listByTags = [];
  29263. forEach = forEach || (function (item) { return; });
  29264. for (var i in list) {
  29265. var item = list[i];
  29266. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29267. listByTags.push(item);
  29268. forEach(item);
  29269. }
  29270. }
  29271. return listByTags;
  29272. };
  29273. /**
  29274. * Get a list of meshes by tags
  29275. * @param tagsQuery defines the tags query to use
  29276. * @param forEach defines a predicate used to filter results
  29277. * @returns an array of Mesh
  29278. */
  29279. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29280. return this._getByTags(this.meshes, tagsQuery, forEach);
  29281. };
  29282. /**
  29283. * Get a list of cameras by tags
  29284. * @param tagsQuery defines the tags query to use
  29285. * @param forEach defines a predicate used to filter results
  29286. * @returns an array of Camera
  29287. */
  29288. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29289. return this._getByTags(this.cameras, tagsQuery, forEach);
  29290. };
  29291. /**
  29292. * Get a list of lights by tags
  29293. * @param tagsQuery defines the tags query to use
  29294. * @param forEach defines a predicate used to filter results
  29295. * @returns an array of Light
  29296. */
  29297. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29298. return this._getByTags(this.lights, tagsQuery, forEach);
  29299. };
  29300. /**
  29301. * Get a list of materials by tags
  29302. * @param tagsQuery defines the tags query to use
  29303. * @param forEach defines a predicate used to filter results
  29304. * @returns an array of Material
  29305. */
  29306. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29307. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29308. };
  29309. /**
  29310. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29311. * This allowed control for front to back rendering or reversly depending of the special needs.
  29312. *
  29313. * @param renderingGroupId The rendering group id corresponding to its index
  29314. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29315. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29316. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29317. */
  29318. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29319. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29320. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29321. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29322. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29323. };
  29324. /**
  29325. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29326. *
  29327. * @param renderingGroupId The rendering group id corresponding to its index
  29328. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29329. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29330. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29331. */
  29332. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29333. if (depth === void 0) { depth = true; }
  29334. if (stencil === void 0) { stencil = true; }
  29335. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29336. };
  29337. /**
  29338. * Gets the current auto clear configuration for one rendering group of the rendering
  29339. * manager.
  29340. * @param index the rendering group index to get the information for
  29341. * @returns The auto clear setup for the requested rendering group
  29342. */
  29343. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29344. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29345. };
  29346. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29347. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29348. get: function () {
  29349. return this._blockMaterialDirtyMechanism;
  29350. },
  29351. set: function (value) {
  29352. if (this._blockMaterialDirtyMechanism === value) {
  29353. return;
  29354. }
  29355. this._blockMaterialDirtyMechanism = value;
  29356. if (!value) { // Do a complete update
  29357. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29358. }
  29359. },
  29360. enumerable: true,
  29361. configurable: true
  29362. });
  29363. /**
  29364. * Will flag all materials as dirty to trigger new shader compilation
  29365. * @param flag defines the flag used to specify which material part must be marked as dirty
  29366. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29367. */
  29368. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29369. if (this._blockMaterialDirtyMechanism) {
  29370. return;
  29371. }
  29372. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29373. var material = _a[_i];
  29374. if (predicate && !predicate(material)) {
  29375. continue;
  29376. }
  29377. material.markAsDirty(flag);
  29378. }
  29379. };
  29380. /** @hidden */
  29381. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29382. var _this = this;
  29383. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29384. this._activeRequests.push(request);
  29385. request.onCompleteObservable.add(function (request) {
  29386. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29387. });
  29388. return request;
  29389. };
  29390. /** @hidden */
  29391. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29392. var _this = this;
  29393. return new Promise(function (resolve, reject) {
  29394. _this._loadFile(url, function (data) {
  29395. resolve(data);
  29396. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29397. reject(exception);
  29398. });
  29399. });
  29400. };
  29401. // Statics
  29402. Scene._uniqueIdCounter = 0;
  29403. /** The fog is deactivated */
  29404. Scene.FOGMODE_NONE = 0;
  29405. /** The fog density is following an exponential function */
  29406. Scene.FOGMODE_EXP = 1;
  29407. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29408. Scene.FOGMODE_EXP2 = 2;
  29409. /** The fog density is following a linear function. */
  29410. Scene.FOGMODE_LINEAR = 3;
  29411. /**
  29412. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29413. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29414. */
  29415. Scene.MinDeltaTime = 1.0;
  29416. /**
  29417. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29418. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29419. */
  29420. Scene.MaxDeltaTime = 1000.0;
  29421. /** The distance in pixel that you have to move to prevent some events */
  29422. Scene.DragMovementThreshold = 10; // in pixels
  29423. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29424. Scene.LongPressDelay = 500; // in milliseconds
  29425. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29426. Scene.DoubleClickDelay = 300; // in milliseconds
  29427. /** If you need to check double click without raising a single click at first click, enable this flag */
  29428. Scene.ExclusiveDoubleClickMode = false;
  29429. return Scene;
  29430. }(BABYLON.AbstractScene));
  29431. BABYLON.Scene = Scene;
  29432. })(BABYLON || (BABYLON = {}));
  29433. //# sourceMappingURL=babylon.scene.js.map
  29434. var BABYLON;
  29435. (function (BABYLON) {
  29436. /**
  29437. * Set of assets to keep when moving a scene into an asset container.
  29438. */
  29439. var KeepAssets = /** @class */ (function (_super) {
  29440. __extends(KeepAssets, _super);
  29441. function KeepAssets() {
  29442. return _super !== null && _super.apply(this, arguments) || this;
  29443. }
  29444. return KeepAssets;
  29445. }(BABYLON.AbstractScene));
  29446. BABYLON.KeepAssets = KeepAssets;
  29447. /**
  29448. * Container with a set of assets that can be added or removed from a scene.
  29449. */
  29450. var AssetContainer = /** @class */ (function (_super) {
  29451. __extends(AssetContainer, _super);
  29452. /**
  29453. * Instantiates an AssetContainer.
  29454. * @param scene The scene the AssetContainer belongs to.
  29455. */
  29456. function AssetContainer(scene) {
  29457. var _this = _super.call(this) || this;
  29458. _this.scene = scene;
  29459. return _this;
  29460. }
  29461. /**
  29462. * Adds all the assets from the container to the scene.
  29463. */
  29464. AssetContainer.prototype.addAllToScene = function () {
  29465. var _this = this;
  29466. this.cameras.forEach(function (o) {
  29467. _this.scene.addCamera(o);
  29468. });
  29469. this.lights.forEach(function (o) {
  29470. _this.scene.addLight(o);
  29471. });
  29472. this.meshes.forEach(function (o) {
  29473. _this.scene.addMesh(o);
  29474. });
  29475. this.skeletons.forEach(function (o) {
  29476. _this.scene.addSkeleton(o);
  29477. });
  29478. this.animations.forEach(function (o) {
  29479. _this.scene.addAnimation(o);
  29480. });
  29481. this.animationGroups.forEach(function (o) {
  29482. _this.scene.addAnimationGroup(o);
  29483. });
  29484. this.multiMaterials.forEach(function (o) {
  29485. _this.scene.addMultiMaterial(o);
  29486. });
  29487. this.materials.forEach(function (o) {
  29488. _this.scene.addMaterial(o);
  29489. });
  29490. this.morphTargetManagers.forEach(function (o) {
  29491. _this.scene.addMorphTargetManager(o);
  29492. });
  29493. this.geometries.forEach(function (o) {
  29494. _this.scene.addGeometry(o);
  29495. });
  29496. this.transformNodes.forEach(function (o) {
  29497. _this.scene.addTransformNode(o);
  29498. });
  29499. this.actionManagers.forEach(function (o) {
  29500. _this.scene.addActionManager(o);
  29501. });
  29502. this.textures.forEach(function (o) {
  29503. _this.scene.addTexture(o);
  29504. });
  29505. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29506. var component = _a[_i];
  29507. component.addFromContainer(this.scene);
  29508. }
  29509. };
  29510. /**
  29511. * Removes all the assets in the container from the scene
  29512. */
  29513. AssetContainer.prototype.removeAllFromScene = function () {
  29514. var _this = this;
  29515. this.cameras.forEach(function (o) {
  29516. _this.scene.removeCamera(o);
  29517. });
  29518. this.lights.forEach(function (o) {
  29519. _this.scene.removeLight(o);
  29520. });
  29521. this.meshes.forEach(function (o) {
  29522. _this.scene.removeMesh(o);
  29523. });
  29524. this.skeletons.forEach(function (o) {
  29525. _this.scene.removeSkeleton(o);
  29526. });
  29527. this.animations.forEach(function (o) {
  29528. _this.scene.removeAnimation(o);
  29529. });
  29530. this.animationGroups.forEach(function (o) {
  29531. _this.scene.removeAnimationGroup(o);
  29532. });
  29533. this.multiMaterials.forEach(function (o) {
  29534. _this.scene.removeMultiMaterial(o);
  29535. });
  29536. this.materials.forEach(function (o) {
  29537. _this.scene.removeMaterial(o);
  29538. });
  29539. this.morphTargetManagers.forEach(function (o) {
  29540. _this.scene.removeMorphTargetManager(o);
  29541. });
  29542. this.geometries.forEach(function (o) {
  29543. _this.scene.removeGeometry(o);
  29544. });
  29545. this.transformNodes.forEach(function (o) {
  29546. _this.scene.removeTransformNode(o);
  29547. });
  29548. this.actionManagers.forEach(function (o) {
  29549. _this.scene.removeActionManager(o);
  29550. });
  29551. this.textures.forEach(function (o) {
  29552. _this.scene.removeTexture(o);
  29553. });
  29554. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29555. var component = _a[_i];
  29556. component.removeFromContainer(this.scene);
  29557. }
  29558. };
  29559. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29560. if (!sourceAssets) {
  29561. return;
  29562. }
  29563. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29564. var asset = sourceAssets_1[_i];
  29565. var move = true;
  29566. if (keepAssets) {
  29567. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29568. var keepAsset = keepAssets_1[_a];
  29569. if (asset === keepAsset) {
  29570. move = false;
  29571. break;
  29572. }
  29573. }
  29574. }
  29575. if (move) {
  29576. targetAssets.push(asset);
  29577. }
  29578. }
  29579. };
  29580. /**
  29581. * Removes all the assets contained in the scene and adds them to the container.
  29582. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29583. */
  29584. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29585. if (keepAssets === undefined) {
  29586. keepAssets = new KeepAssets();
  29587. }
  29588. for (var key in this) {
  29589. if (this.hasOwnProperty(key)) {
  29590. this[key] = this[key] || [];
  29591. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29592. }
  29593. }
  29594. this.removeAllFromScene();
  29595. };
  29596. /**
  29597. * 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.
  29598. * @returns the root mesh
  29599. */
  29600. AssetContainer.prototype.createRootMesh = function () {
  29601. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29602. this.meshes.forEach(function (m) {
  29603. if (!m.parent) {
  29604. rootMesh.addChild(m);
  29605. }
  29606. });
  29607. this.meshes.unshift(rootMesh);
  29608. return rootMesh;
  29609. };
  29610. return AssetContainer;
  29611. }(BABYLON.AbstractScene));
  29612. BABYLON.AssetContainer = AssetContainer;
  29613. })(BABYLON || (BABYLON = {}));
  29614. //# sourceMappingURL=babylon.assetContainer.js.map
  29615. var BABYLON;
  29616. (function (BABYLON) {
  29617. /**
  29618. * Class used to store data that will be store in GPU memory
  29619. */
  29620. var Buffer = /** @class */ (function () {
  29621. /**
  29622. * Constructor
  29623. * @param engine the engine
  29624. * @param data the data to use for this buffer
  29625. * @param updatable whether the data is updatable
  29626. * @param stride the stride (optional)
  29627. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29628. * @param instanced whether the buffer is instanced (optional)
  29629. * @param useBytes set to true if the stride in in bytes (optional)
  29630. */
  29631. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29632. if (stride === void 0) { stride = 0; }
  29633. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29634. if (instanced === void 0) { instanced = false; }
  29635. if (useBytes === void 0) { useBytes = false; }
  29636. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29637. this._engine = engine.getScene().getEngine();
  29638. }
  29639. else {
  29640. this._engine = engine;
  29641. }
  29642. this._updatable = updatable;
  29643. this._instanced = instanced;
  29644. this._data = data;
  29645. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29646. if (!postponeInternalCreation) { // by default
  29647. this.create();
  29648. }
  29649. }
  29650. /**
  29651. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29652. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29653. * @param offset defines offset in the buffer (0 by default)
  29654. * @param size defines the size in floats of attributes (position is 3 for instance)
  29655. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29656. * @param instanced defines if the vertex buffer contains indexed data
  29657. * @param useBytes defines if the offset and stride are in bytes
  29658. * @returns the new vertex buffer
  29659. */
  29660. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29661. if (useBytes === void 0) { useBytes = false; }
  29662. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29663. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29664. // a lot of these parameters are ignored as they are overriden by the buffer
  29665. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29666. };
  29667. // Properties
  29668. /**
  29669. * Gets a boolean indicating if the Buffer is updatable?
  29670. * @returns true if the buffer is updatable
  29671. */
  29672. Buffer.prototype.isUpdatable = function () {
  29673. return this._updatable;
  29674. };
  29675. /**
  29676. * Gets current buffer's data
  29677. * @returns a DataArray or null
  29678. */
  29679. Buffer.prototype.getData = function () {
  29680. return this._data;
  29681. };
  29682. /**
  29683. * Gets underlying native buffer
  29684. * @returns underlying native buffer
  29685. */
  29686. Buffer.prototype.getBuffer = function () {
  29687. return this._buffer;
  29688. };
  29689. /**
  29690. * Gets the stride in float32 units (i.e. byte stride / 4).
  29691. * May not be an integer if the byte stride is not divisible by 4.
  29692. * DEPRECATED. Use byteStride instead.
  29693. * @returns the stride in float32 units
  29694. */
  29695. Buffer.prototype.getStrideSize = function () {
  29696. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29697. };
  29698. // Methods
  29699. /**
  29700. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29701. * @param data defines the data to store
  29702. */
  29703. Buffer.prototype.create = function (data) {
  29704. if (data === void 0) { data = null; }
  29705. if (!data && this._buffer) {
  29706. return; // nothing to do
  29707. }
  29708. data = data || this._data;
  29709. if (!data) {
  29710. return;
  29711. }
  29712. if (!this._buffer) { // create buffer
  29713. if (this._updatable) {
  29714. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29715. this._data = data;
  29716. }
  29717. else {
  29718. this._buffer = this._engine.createVertexBuffer(data);
  29719. }
  29720. }
  29721. else if (this._updatable) { // update buffer
  29722. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29723. this._data = data;
  29724. }
  29725. };
  29726. /** @hidden */
  29727. Buffer.prototype._rebuild = function () {
  29728. this._buffer = null;
  29729. this.create(this._data);
  29730. };
  29731. /**
  29732. * Update current buffer data
  29733. * @param data defines the data to store
  29734. */
  29735. Buffer.prototype.update = function (data) {
  29736. this.create(data);
  29737. };
  29738. /**
  29739. * Updates the data directly.
  29740. * @param data the new data
  29741. * @param offset the new offset
  29742. * @param vertexCount the vertex count (optional)
  29743. * @param useBytes set to true if the offset is in bytes
  29744. */
  29745. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29746. if (useBytes === void 0) { useBytes = false; }
  29747. if (!this._buffer) {
  29748. return;
  29749. }
  29750. if (this._updatable) { // update buffer
  29751. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29752. this._data = null;
  29753. }
  29754. };
  29755. /**
  29756. * Release all resources
  29757. */
  29758. Buffer.prototype.dispose = function () {
  29759. if (!this._buffer) {
  29760. return;
  29761. }
  29762. if (this._engine._releaseBuffer(this._buffer)) {
  29763. this._buffer = null;
  29764. }
  29765. };
  29766. return Buffer;
  29767. }());
  29768. BABYLON.Buffer = Buffer;
  29769. })(BABYLON || (BABYLON = {}));
  29770. //# sourceMappingURL=babylon.buffer.js.map
  29771. var BABYLON;
  29772. (function (BABYLON) {
  29773. /**
  29774. * Specialized buffer used to store vertex data
  29775. */
  29776. var VertexBuffer = /** @class */ (function () {
  29777. /**
  29778. * Constructor
  29779. * @param engine the engine
  29780. * @param data the data to use for this vertex buffer
  29781. * @param kind the vertex buffer kind
  29782. * @param updatable whether the data is updatable
  29783. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29784. * @param stride the stride (optional)
  29785. * @param instanced whether the buffer is instanced (optional)
  29786. * @param offset the offset of the data (optional)
  29787. * @param size the number of components (optional)
  29788. * @param type the type of the component (optional)
  29789. * @param normalized whether the data contains normalized data (optional)
  29790. * @param useBytes set to true if stride and offset are in bytes (optional)
  29791. */
  29792. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29793. if (normalized === void 0) { normalized = false; }
  29794. if (useBytes === void 0) { useBytes = false; }
  29795. if (data instanceof BABYLON.Buffer) {
  29796. this._buffer = data;
  29797. this._ownsBuffer = false;
  29798. }
  29799. else {
  29800. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29801. this._ownsBuffer = true;
  29802. }
  29803. this._kind = kind;
  29804. if (type == undefined) {
  29805. var data_1 = this.getData();
  29806. this.type = VertexBuffer.FLOAT;
  29807. if (data_1 instanceof Int8Array)
  29808. this.type = VertexBuffer.BYTE;
  29809. else if (data_1 instanceof Uint8Array)
  29810. this.type = VertexBuffer.UNSIGNED_BYTE;
  29811. else if (data_1 instanceof Int16Array)
  29812. this.type = VertexBuffer.SHORT;
  29813. else if (data_1 instanceof Uint16Array)
  29814. this.type = VertexBuffer.UNSIGNED_SHORT;
  29815. else if (data_1 instanceof Int32Array)
  29816. this.type = VertexBuffer.INT;
  29817. else if (data_1 instanceof Uint32Array)
  29818. this.type = VertexBuffer.UNSIGNED_INT;
  29819. }
  29820. else {
  29821. this.type = type;
  29822. }
  29823. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29824. if (useBytes) {
  29825. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29826. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29827. this.byteOffset = offset || 0;
  29828. }
  29829. else {
  29830. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29831. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29832. this.byteOffset = (offset || 0) * typeByteLength;
  29833. }
  29834. this.normalized = normalized;
  29835. this._instanced = instanced !== undefined ? instanced : false;
  29836. this._instanceDivisor = instanced ? 1 : 0;
  29837. }
  29838. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29839. /**
  29840. * Gets or sets the instance divisor when in instanced mode
  29841. */
  29842. get: function () {
  29843. return this._instanceDivisor;
  29844. },
  29845. set: function (value) {
  29846. this._instanceDivisor = value;
  29847. if (value == 0) {
  29848. this._instanced = false;
  29849. }
  29850. else {
  29851. this._instanced = true;
  29852. }
  29853. },
  29854. enumerable: true,
  29855. configurable: true
  29856. });
  29857. /** @hidden */
  29858. VertexBuffer.prototype._rebuild = function () {
  29859. if (!this._buffer) {
  29860. return;
  29861. }
  29862. this._buffer._rebuild();
  29863. };
  29864. /**
  29865. * Returns the kind of the VertexBuffer (string)
  29866. * @returns a string
  29867. */
  29868. VertexBuffer.prototype.getKind = function () {
  29869. return this._kind;
  29870. };
  29871. // Properties
  29872. /**
  29873. * Gets a boolean indicating if the VertexBuffer is updatable?
  29874. * @returns true if the buffer is updatable
  29875. */
  29876. VertexBuffer.prototype.isUpdatable = function () {
  29877. return this._buffer.isUpdatable();
  29878. };
  29879. /**
  29880. * Gets current buffer's data
  29881. * @returns a DataArray or null
  29882. */
  29883. VertexBuffer.prototype.getData = function () {
  29884. return this._buffer.getData();
  29885. };
  29886. /**
  29887. * Gets underlying native buffer
  29888. * @returns underlying native buffer
  29889. */
  29890. VertexBuffer.prototype.getBuffer = function () {
  29891. return this._buffer.getBuffer();
  29892. };
  29893. /**
  29894. * Gets the stride in float32 units (i.e. byte stride / 4).
  29895. * May not be an integer if the byte stride is not divisible by 4.
  29896. * DEPRECATED. Use byteStride instead.
  29897. * @returns the stride in float32 units
  29898. */
  29899. VertexBuffer.prototype.getStrideSize = function () {
  29900. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29901. };
  29902. /**
  29903. * Returns the offset as a multiple of the type byte length.
  29904. * DEPRECATED. Use byteOffset instead.
  29905. * @returns the offset in bytes
  29906. */
  29907. VertexBuffer.prototype.getOffset = function () {
  29908. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29909. };
  29910. /**
  29911. * Returns the number of components per vertex attribute (integer)
  29912. * @returns the size in float
  29913. */
  29914. VertexBuffer.prototype.getSize = function () {
  29915. return this._size;
  29916. };
  29917. /**
  29918. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  29919. * @returns true if this buffer is instanced
  29920. */
  29921. VertexBuffer.prototype.getIsInstanced = function () {
  29922. return this._instanced;
  29923. };
  29924. /**
  29925. * Returns the instancing divisor, zero for non-instanced (integer).
  29926. * @returns a number
  29927. */
  29928. VertexBuffer.prototype.getInstanceDivisor = function () {
  29929. return this._instanceDivisor;
  29930. };
  29931. // Methods
  29932. /**
  29933. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29934. * @param data defines the data to store
  29935. */
  29936. VertexBuffer.prototype.create = function (data) {
  29937. this._buffer.create(data);
  29938. };
  29939. /**
  29940. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  29941. * This function will create a new buffer if the current one is not updatable
  29942. * @param data defines the data to store
  29943. */
  29944. VertexBuffer.prototype.update = function (data) {
  29945. this._buffer.update(data);
  29946. };
  29947. /**
  29948. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29949. * Returns the directly updated WebGLBuffer.
  29950. * @param data the new data
  29951. * @param offset the new offset
  29952. * @param useBytes set to true if the offset is in bytes
  29953. */
  29954. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29955. if (useBytes === void 0) { useBytes = false; }
  29956. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29957. };
  29958. /**
  29959. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29960. */
  29961. VertexBuffer.prototype.dispose = function () {
  29962. if (this._ownsBuffer) {
  29963. this._buffer.dispose();
  29964. }
  29965. };
  29966. /**
  29967. * Enumerates each value of this vertex buffer as numbers.
  29968. * @param count the number of values to enumerate
  29969. * @param callback the callback function called for each value
  29970. */
  29971. VertexBuffer.prototype.forEach = function (count, callback) {
  29972. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29973. };
  29974. /**
  29975. * Deduces the stride given a kind.
  29976. * @param kind The kind string to deduce
  29977. * @returns The deduced stride
  29978. */
  29979. VertexBuffer.DeduceStride = function (kind) {
  29980. switch (kind) {
  29981. case VertexBuffer.UVKind:
  29982. case VertexBuffer.UV2Kind:
  29983. case VertexBuffer.UV3Kind:
  29984. case VertexBuffer.UV4Kind:
  29985. case VertexBuffer.UV5Kind:
  29986. case VertexBuffer.UV6Kind:
  29987. return 2;
  29988. case VertexBuffer.NormalKind:
  29989. case VertexBuffer.PositionKind:
  29990. return 3;
  29991. case VertexBuffer.ColorKind:
  29992. case VertexBuffer.MatricesIndicesKind:
  29993. case VertexBuffer.MatricesIndicesExtraKind:
  29994. case VertexBuffer.MatricesWeightsKind:
  29995. case VertexBuffer.MatricesWeightsExtraKind:
  29996. case VertexBuffer.TangentKind:
  29997. return 4;
  29998. default:
  29999. throw new Error("Invalid kind '" + kind + "'");
  30000. }
  30001. };
  30002. /**
  30003. * Gets the byte length of the given type.
  30004. * @param type the type
  30005. * @returns the number of bytes
  30006. */
  30007. VertexBuffer.GetTypeByteLength = function (type) {
  30008. switch (type) {
  30009. case VertexBuffer.BYTE:
  30010. case VertexBuffer.UNSIGNED_BYTE:
  30011. return 1;
  30012. case VertexBuffer.SHORT:
  30013. case VertexBuffer.UNSIGNED_SHORT:
  30014. return 2;
  30015. case VertexBuffer.INT:
  30016. case VertexBuffer.FLOAT:
  30017. return 4;
  30018. default:
  30019. throw new Error("Invalid type '" + type + "'");
  30020. }
  30021. };
  30022. /**
  30023. * Enumerates each value of the given parameters as numbers.
  30024. * @param data the data to enumerate
  30025. * @param byteOffset the byte offset of the data
  30026. * @param byteStride the byte stride of the data
  30027. * @param componentCount the number of components per element
  30028. * @param componentType the type of the component
  30029. * @param count the total number of components
  30030. * @param normalized whether the data is normalized
  30031. * @param callback the callback function called for each value
  30032. */
  30033. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30034. if (data instanceof Array) {
  30035. var offset = byteOffset / 4;
  30036. var stride = byteStride / 4;
  30037. for (var index = 0; index < count; index += componentCount) {
  30038. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30039. callback(data[offset + componentIndex], index + componentIndex);
  30040. }
  30041. offset += stride;
  30042. }
  30043. }
  30044. else {
  30045. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30046. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30047. for (var index = 0; index < count; index += componentCount) {
  30048. var componentByteOffset = byteOffset;
  30049. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30050. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30051. callback(value, index + componentIndex);
  30052. componentByteOffset += componentByteLength;
  30053. }
  30054. byteOffset += byteStride;
  30055. }
  30056. }
  30057. };
  30058. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30059. switch (type) {
  30060. case VertexBuffer.BYTE: {
  30061. var value = dataView.getInt8(byteOffset);
  30062. if (normalized) {
  30063. value = Math.max(value / 127, -1);
  30064. }
  30065. return value;
  30066. }
  30067. case VertexBuffer.UNSIGNED_BYTE: {
  30068. var value = dataView.getUint8(byteOffset);
  30069. if (normalized) {
  30070. value = value / 255;
  30071. }
  30072. return value;
  30073. }
  30074. case VertexBuffer.SHORT: {
  30075. var value = dataView.getInt16(byteOffset, true);
  30076. if (normalized) {
  30077. value = Math.max(value / 16383, -1);
  30078. }
  30079. return value;
  30080. }
  30081. case VertexBuffer.UNSIGNED_SHORT: {
  30082. var value = dataView.getUint16(byteOffset, true);
  30083. if (normalized) {
  30084. value = value / 65535;
  30085. }
  30086. return value;
  30087. }
  30088. case VertexBuffer.FLOAT: {
  30089. return dataView.getFloat32(byteOffset, true);
  30090. }
  30091. default: {
  30092. throw new Error("Invalid component type " + type);
  30093. }
  30094. }
  30095. };
  30096. /**
  30097. * The byte type.
  30098. */
  30099. VertexBuffer.BYTE = 5120;
  30100. /**
  30101. * The unsigned byte type.
  30102. */
  30103. VertexBuffer.UNSIGNED_BYTE = 5121;
  30104. /**
  30105. * The short type.
  30106. */
  30107. VertexBuffer.SHORT = 5122;
  30108. /**
  30109. * The unsigned short type.
  30110. */
  30111. VertexBuffer.UNSIGNED_SHORT = 5123;
  30112. /**
  30113. * The integer type.
  30114. */
  30115. VertexBuffer.INT = 5124;
  30116. /**
  30117. * The unsigned integer type.
  30118. */
  30119. VertexBuffer.UNSIGNED_INT = 5125;
  30120. /**
  30121. * The float type.
  30122. */
  30123. VertexBuffer.FLOAT = 5126;
  30124. // Enums
  30125. /**
  30126. * Positions
  30127. */
  30128. VertexBuffer.PositionKind = "position";
  30129. /**
  30130. * Normals
  30131. */
  30132. VertexBuffer.NormalKind = "normal";
  30133. /**
  30134. * Tangents
  30135. */
  30136. VertexBuffer.TangentKind = "tangent";
  30137. /**
  30138. * Texture coordinates
  30139. */
  30140. VertexBuffer.UVKind = "uv";
  30141. /**
  30142. * Texture coordinates 2
  30143. */
  30144. VertexBuffer.UV2Kind = "uv2";
  30145. /**
  30146. * Texture coordinates 3
  30147. */
  30148. VertexBuffer.UV3Kind = "uv3";
  30149. /**
  30150. * Texture coordinates 4
  30151. */
  30152. VertexBuffer.UV4Kind = "uv4";
  30153. /**
  30154. * Texture coordinates 5
  30155. */
  30156. VertexBuffer.UV5Kind = "uv5";
  30157. /**
  30158. * Texture coordinates 6
  30159. */
  30160. VertexBuffer.UV6Kind = "uv6";
  30161. /**
  30162. * Colors
  30163. */
  30164. VertexBuffer.ColorKind = "color";
  30165. /**
  30166. * Matrix indices (for bones)
  30167. */
  30168. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30169. /**
  30170. * Matrix weights (for bones)
  30171. */
  30172. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30173. /**
  30174. * Additional matrix indices (for bones)
  30175. */
  30176. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30177. /**
  30178. * Additional matrix weights (for bones)
  30179. */
  30180. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30181. return VertexBuffer;
  30182. }());
  30183. BABYLON.VertexBuffer = VertexBuffer;
  30184. })(BABYLON || (BABYLON = {}));
  30185. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30186. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30187. var BABYLON;
  30188. (function (BABYLON) {
  30189. /**
  30190. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30191. */
  30192. var DummyInternalTextureTracker = /** @class */ (function () {
  30193. function DummyInternalTextureTracker() {
  30194. /**
  30195. * Gets or set the previous tracker in the list
  30196. */
  30197. this.previous = null;
  30198. /**
  30199. * Gets or set the next tracker in the list
  30200. */
  30201. this.next = null;
  30202. }
  30203. return DummyInternalTextureTracker;
  30204. }());
  30205. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30206. })(BABYLON || (BABYLON = {}));
  30207. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30208. var BABYLON;
  30209. (function (BABYLON) {
  30210. /**
  30211. * Class used to store data associated with WebGL texture data for the engine
  30212. * This class should not be used directly
  30213. */
  30214. var InternalTexture = /** @class */ (function () {
  30215. /**
  30216. * Creates a new InternalTexture
  30217. * @param engine defines the engine to use
  30218. * @param dataSource defines the type of data that will be used
  30219. */
  30220. function InternalTexture(engine, dataSource) {
  30221. /**
  30222. * Observable called when the texture is loaded
  30223. */
  30224. this.onLoadedObservable = new BABYLON.Observable();
  30225. /**
  30226. * Gets or set the previous tracker in the list
  30227. */
  30228. this.previous = null;
  30229. /**
  30230. * Gets or set the next tracker in the list
  30231. */
  30232. this.next = null;
  30233. // Private
  30234. /** @hidden */
  30235. this._initialSlot = -1;
  30236. /** @hidden */
  30237. this._designatedSlot = -1;
  30238. /** @hidden */
  30239. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30240. /** @hidden */
  30241. this._comparisonFunction = 0;
  30242. /** @hidden */
  30243. this._sphericalPolynomial = null;
  30244. /** @hidden */
  30245. this._lodGenerationScale = 0;
  30246. /** @hidden */
  30247. this._lodGenerationOffset = 0;
  30248. /** @hidden */
  30249. this._isRGBD = false;
  30250. /** @hidden */
  30251. this._references = 1;
  30252. this._engine = engine;
  30253. this._dataSource = dataSource;
  30254. this._webGLTexture = engine._createTexture();
  30255. }
  30256. /**
  30257. * Gets the Engine the texture belongs to.
  30258. * @returns The babylon engine
  30259. */
  30260. InternalTexture.prototype.getEngine = function () {
  30261. return this._engine;
  30262. };
  30263. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30264. /**
  30265. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30266. */
  30267. get: function () {
  30268. return this._dataSource;
  30269. },
  30270. enumerable: true,
  30271. configurable: true
  30272. });
  30273. /**
  30274. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30275. */
  30276. InternalTexture.prototype.incrementReferences = function () {
  30277. this._references++;
  30278. };
  30279. /**
  30280. * Change the size of the texture (not the size of the content)
  30281. * @param width defines the new width
  30282. * @param height defines the new height
  30283. * @param depth defines the new depth (1 by default)
  30284. */
  30285. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30286. if (depth === void 0) { depth = 1; }
  30287. this.width = width;
  30288. this.height = height;
  30289. this.depth = depth;
  30290. this.baseWidth = width;
  30291. this.baseHeight = height;
  30292. this.baseDepth = depth;
  30293. this._size = width * height * depth;
  30294. };
  30295. /** @hidden */
  30296. InternalTexture.prototype._rebuild = function () {
  30297. var _this = this;
  30298. var proxy;
  30299. this.isReady = false;
  30300. this._cachedCoordinatesMode = null;
  30301. this._cachedWrapU = null;
  30302. this._cachedWrapV = null;
  30303. this._cachedAnisotropicFilteringLevel = null;
  30304. switch (this._dataSource) {
  30305. case InternalTexture.DATASOURCE_TEMP:
  30306. return;
  30307. case InternalTexture.DATASOURCE_URL:
  30308. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30309. _this.isReady = true;
  30310. }, null, this._buffer, undefined, this.format);
  30311. proxy._swapAndDie(this);
  30312. return;
  30313. case InternalTexture.DATASOURCE_RAW:
  30314. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30315. proxy._swapAndDie(this);
  30316. this.isReady = true;
  30317. return;
  30318. case InternalTexture.DATASOURCE_RAW3D:
  30319. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30320. proxy._swapAndDie(this);
  30321. this.isReady = true;
  30322. return;
  30323. case InternalTexture.DATASOURCE_DYNAMIC:
  30324. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30325. proxy._swapAndDie(this);
  30326. // The engine will make sure to update content so no need to flag it as isReady = true
  30327. return;
  30328. case InternalTexture.DATASOURCE_RENDERTARGET:
  30329. var options = new BABYLON.RenderTargetCreationOptions();
  30330. options.generateDepthBuffer = this._generateDepthBuffer;
  30331. options.generateMipMaps = this.generateMipMaps;
  30332. options.generateStencilBuffer = this._generateStencilBuffer;
  30333. options.samplingMode = this.samplingMode;
  30334. options.type = this.type;
  30335. if (this.isCube) {
  30336. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30337. }
  30338. else {
  30339. var size = {
  30340. width: this.width,
  30341. height: this.height
  30342. };
  30343. proxy = this._engine.createRenderTargetTexture(size, options);
  30344. }
  30345. proxy._swapAndDie(this);
  30346. this.isReady = true;
  30347. return;
  30348. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30349. var depthTextureOptions = {
  30350. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30351. comparisonFunction: this._comparisonFunction,
  30352. generateStencil: this._generateStencilBuffer,
  30353. isCube: this.isCube
  30354. };
  30355. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30356. proxy._swapAndDie(this);
  30357. this.isReady = true;
  30358. return;
  30359. case InternalTexture.DATASOURCE_CUBE:
  30360. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30361. _this.isReady = true;
  30362. }, null, this.format, this._extension);
  30363. proxy._swapAndDie(this);
  30364. return;
  30365. case InternalTexture.DATASOURCE_CUBERAW:
  30366. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30367. proxy._swapAndDie(this);
  30368. this.isReady = true;
  30369. return;
  30370. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30371. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30372. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30373. _this.isReady = true;
  30374. });
  30375. proxy._swapAndDie(this);
  30376. return;
  30377. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30378. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30379. if (proxy) {
  30380. proxy._swapAndDie(_this);
  30381. }
  30382. _this.isReady = true;
  30383. }, null, this.format, this._extension);
  30384. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30385. return;
  30386. }
  30387. };
  30388. /** @hidden */
  30389. InternalTexture.prototype._swapAndDie = function (target) {
  30390. target._webGLTexture = this._webGLTexture;
  30391. if (this._framebuffer) {
  30392. target._framebuffer = this._framebuffer;
  30393. }
  30394. if (this._depthStencilBuffer) {
  30395. target._depthStencilBuffer = this._depthStencilBuffer;
  30396. }
  30397. if (this._lodTextureHigh) {
  30398. if (target._lodTextureHigh) {
  30399. target._lodTextureHigh.dispose();
  30400. }
  30401. target._lodTextureHigh = this._lodTextureHigh;
  30402. }
  30403. if (this._lodTextureMid) {
  30404. if (target._lodTextureMid) {
  30405. target._lodTextureMid.dispose();
  30406. }
  30407. target._lodTextureMid = this._lodTextureMid;
  30408. }
  30409. if (this._lodTextureLow) {
  30410. if (target._lodTextureLow) {
  30411. target._lodTextureLow.dispose();
  30412. }
  30413. target._lodTextureLow = this._lodTextureLow;
  30414. }
  30415. var cache = this._engine.getLoadedTexturesCache();
  30416. var index = cache.indexOf(this);
  30417. if (index !== -1) {
  30418. cache.splice(index, 1);
  30419. }
  30420. };
  30421. /**
  30422. * Dispose the current allocated resources
  30423. */
  30424. InternalTexture.prototype.dispose = function () {
  30425. if (!this._webGLTexture) {
  30426. return;
  30427. }
  30428. this._references--;
  30429. if (this._references === 0) {
  30430. this._engine._releaseTexture(this);
  30431. this._webGLTexture = null;
  30432. this.previous = null;
  30433. this.next = null;
  30434. }
  30435. };
  30436. /**
  30437. * The source of the texture data is unknown
  30438. */
  30439. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30440. /**
  30441. * Texture data comes from an URL
  30442. */
  30443. InternalTexture.DATASOURCE_URL = 1;
  30444. /**
  30445. * Texture data is only used for temporary storage
  30446. */
  30447. InternalTexture.DATASOURCE_TEMP = 2;
  30448. /**
  30449. * Texture data comes from raw data (ArrayBuffer)
  30450. */
  30451. InternalTexture.DATASOURCE_RAW = 3;
  30452. /**
  30453. * Texture content is dynamic (video or dynamic texture)
  30454. */
  30455. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30456. /**
  30457. * Texture content is generated by rendering to it
  30458. */
  30459. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30460. /**
  30461. * Texture content is part of a multi render target process
  30462. */
  30463. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30464. /**
  30465. * Texture data comes from a cube data file
  30466. */
  30467. InternalTexture.DATASOURCE_CUBE = 7;
  30468. /**
  30469. * Texture data comes from a raw cube data
  30470. */
  30471. InternalTexture.DATASOURCE_CUBERAW = 8;
  30472. /**
  30473. * Texture data come from a prefiltered cube data file
  30474. */
  30475. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30476. /**
  30477. * Texture content is raw 3D data
  30478. */
  30479. InternalTexture.DATASOURCE_RAW3D = 10;
  30480. /**
  30481. * Texture content is a depth texture
  30482. */
  30483. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30484. /**
  30485. * Texture data comes from a raw cube data encoded with RGBD
  30486. */
  30487. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30488. return InternalTexture;
  30489. }());
  30490. BABYLON.InternalTexture = InternalTexture;
  30491. })(BABYLON || (BABYLON = {}));
  30492. //# sourceMappingURL=babylon.internalTexture.js.map
  30493. var BABYLON;
  30494. (function (BABYLON) {
  30495. /**
  30496. * Base class of all the textures in babylon.
  30497. * It groups all the common properties the materials, post process, lights... might need
  30498. * in order to make a correct use of the texture.
  30499. */
  30500. var BaseTexture = /** @class */ (function () {
  30501. /**
  30502. * Instantiates a new BaseTexture.
  30503. * Base class of all the textures in babylon.
  30504. * It groups all the common properties the materials, post process, lights... might need
  30505. * in order to make a correct use of the texture.
  30506. * @param scene Define the scene the texture blongs to
  30507. */
  30508. function BaseTexture(scene) {
  30509. this._hasAlpha = false;
  30510. /**
  30511. * Defines if the alpha value should be determined via the rgb values.
  30512. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30513. */
  30514. this.getAlphaFromRGB = false;
  30515. /**
  30516. * Intensity or strength of the texture.
  30517. * It is commonly used by materials to fine tune the intensity of the texture
  30518. */
  30519. this.level = 1;
  30520. /**
  30521. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30522. * This is part of the texture as textures usually maps to one uv set.
  30523. */
  30524. this.coordinatesIndex = 0;
  30525. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30526. /**
  30527. * | Value | Type | Description |
  30528. * | ----- | ------------------ | ----------- |
  30529. * | 0 | CLAMP_ADDRESSMODE | |
  30530. * | 1 | WRAP_ADDRESSMODE | |
  30531. * | 2 | MIRROR_ADDRESSMODE | |
  30532. */
  30533. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30534. /**
  30535. * | Value | Type | Description |
  30536. * | ----- | ------------------ | ----------- |
  30537. * | 0 | CLAMP_ADDRESSMODE | |
  30538. * | 1 | WRAP_ADDRESSMODE | |
  30539. * | 2 | MIRROR_ADDRESSMODE | |
  30540. */
  30541. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30542. /**
  30543. * | Value | Type | Description |
  30544. * | ----- | ------------------ | ----------- |
  30545. * | 0 | CLAMP_ADDRESSMODE | |
  30546. * | 1 | WRAP_ADDRESSMODE | |
  30547. * | 2 | MIRROR_ADDRESSMODE | |
  30548. */
  30549. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30550. /**
  30551. * With compliant hardware and browser (supporting anisotropic filtering)
  30552. * this defines the level of anisotropic filtering in the texture.
  30553. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30554. */
  30555. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30556. /**
  30557. * Define if the texture is a cube texture or if false a 2d texture.
  30558. */
  30559. this.isCube = false;
  30560. /**
  30561. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30562. */
  30563. this.is3D = false;
  30564. /**
  30565. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30566. * HDR texture are usually stored in linear space.
  30567. * This only impacts the PBR and Background materials
  30568. */
  30569. this.gammaSpace = true;
  30570. /**
  30571. * Is Z inverted in the texture (useful in a cube texture).
  30572. */
  30573. this.invertZ = false;
  30574. /**
  30575. * @hidden
  30576. */
  30577. this.lodLevelInAlpha = false;
  30578. /**
  30579. * Define if the texture is a render target.
  30580. */
  30581. this.isRenderTarget = false;
  30582. /**
  30583. * Define the list of animation attached to the texture.
  30584. */
  30585. this.animations = new Array();
  30586. /**
  30587. * An event triggered when the texture is disposed.
  30588. */
  30589. this.onDisposeObservable = new BABYLON.Observable();
  30590. /**
  30591. * Define the current state of the loading sequence when in delayed load mode.
  30592. */
  30593. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30594. this._cachedSize = BABYLON.Size.Zero();
  30595. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30596. if (this._scene) {
  30597. this._scene.textures.push(this);
  30598. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30599. }
  30600. this._uid = null;
  30601. }
  30602. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30603. get: function () {
  30604. return this._hasAlpha;
  30605. },
  30606. /**
  30607. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30608. */
  30609. set: function (value) {
  30610. if (this._hasAlpha === value) {
  30611. return;
  30612. }
  30613. this._hasAlpha = value;
  30614. if (this._scene) {
  30615. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30616. }
  30617. },
  30618. enumerable: true,
  30619. configurable: true
  30620. });
  30621. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30622. get: function () {
  30623. return this._coordinatesMode;
  30624. },
  30625. /**
  30626. * How a texture is mapped.
  30627. *
  30628. * | Value | Type | Description |
  30629. * | ----- | ----------------------------------- | ----------- |
  30630. * | 0 | EXPLICIT_MODE | |
  30631. * | 1 | SPHERICAL_MODE | |
  30632. * | 2 | PLANAR_MODE | |
  30633. * | 3 | CUBIC_MODE | |
  30634. * | 4 | PROJECTION_MODE | |
  30635. * | 5 | SKYBOX_MODE | |
  30636. * | 6 | INVCUBIC_MODE | |
  30637. * | 7 | EQUIRECTANGULAR_MODE | |
  30638. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30639. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30640. */
  30641. set: function (value) {
  30642. if (this._coordinatesMode === value) {
  30643. return;
  30644. }
  30645. this._coordinatesMode = value;
  30646. if (this._scene) {
  30647. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30648. }
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30654. /**
  30655. * Gets whether or not the texture contains RGBD data.
  30656. */
  30657. get: function () {
  30658. return this._texture != null && this._texture._isRGBD;
  30659. },
  30660. enumerable: true,
  30661. configurable: true
  30662. });
  30663. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30664. /**
  30665. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30666. */
  30667. get: function () {
  30668. if (this._texture)
  30669. return this._texture._lodGenerationOffset;
  30670. return 0.0;
  30671. },
  30672. set: function (value) {
  30673. if (this._texture)
  30674. this._texture._lodGenerationOffset = value;
  30675. },
  30676. enumerable: true,
  30677. configurable: true
  30678. });
  30679. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30680. /**
  30681. * With prefiltered texture, defined the scale used during the prefiltering steps.
  30682. */
  30683. get: function () {
  30684. if (this._texture)
  30685. return this._texture._lodGenerationScale;
  30686. return 0.0;
  30687. },
  30688. set: function (value) {
  30689. if (this._texture)
  30690. this._texture._lodGenerationScale = value;
  30691. },
  30692. enumerable: true,
  30693. configurable: true
  30694. });
  30695. Object.defineProperty(BaseTexture.prototype, "uid", {
  30696. /**
  30697. * Define the unique id of the texture in the scene.
  30698. */
  30699. get: function () {
  30700. if (!this._uid) {
  30701. this._uid = BABYLON.Tools.RandomId();
  30702. }
  30703. return this._uid;
  30704. },
  30705. enumerable: true,
  30706. configurable: true
  30707. });
  30708. /**
  30709. * Return a string representation of the texture.
  30710. * @returns the texture as a string
  30711. */
  30712. BaseTexture.prototype.toString = function () {
  30713. return this.name;
  30714. };
  30715. /**
  30716. * Get the class name of the texture.
  30717. * @returns "BaseTexture"
  30718. */
  30719. BaseTexture.prototype.getClassName = function () {
  30720. return "BaseTexture";
  30721. };
  30722. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30723. /**
  30724. * Callback triggered when the texture has been disposed.
  30725. * Kept for back compatibility, you can use the onDisposeObservable instead.
  30726. */
  30727. set: function (callback) {
  30728. if (this._onDisposeObserver) {
  30729. this.onDisposeObservable.remove(this._onDisposeObserver);
  30730. }
  30731. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30732. },
  30733. enumerable: true,
  30734. configurable: true
  30735. });
  30736. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30737. /**
  30738. * Define if the texture is preventinga material to render or not.
  30739. * If not and the texture is not ready, the engine will use a default black texture instead.
  30740. */
  30741. get: function () {
  30742. return true;
  30743. },
  30744. enumerable: true,
  30745. configurable: true
  30746. });
  30747. /**
  30748. * Get the scene the texture belongs to.
  30749. * @returns the scene or null if undefined
  30750. */
  30751. BaseTexture.prototype.getScene = function () {
  30752. return this._scene;
  30753. };
  30754. /**
  30755. * Get the texture transform matrix used to offset tile the texture for istance.
  30756. * @returns the transformation matrix
  30757. */
  30758. BaseTexture.prototype.getTextureMatrix = function () {
  30759. return BABYLON.Matrix.IdentityReadOnly;
  30760. };
  30761. /**
  30762. * Get the texture reflection matrix used to rotate/transform the reflection.
  30763. * @returns the reflection matrix
  30764. */
  30765. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30766. return BABYLON.Matrix.IdentityReadOnly;
  30767. };
  30768. /**
  30769. * Get the underlying lower level texture from Babylon.
  30770. * @returns the insternal texture
  30771. */
  30772. BaseTexture.prototype.getInternalTexture = function () {
  30773. return this._texture;
  30774. };
  30775. /**
  30776. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  30777. * @returns true if ready or not blocking
  30778. */
  30779. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30780. return !this.isBlocking || this.isReady();
  30781. };
  30782. /**
  30783. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  30784. * @returns true if fully ready
  30785. */
  30786. BaseTexture.prototype.isReady = function () {
  30787. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30788. this.delayLoad();
  30789. return false;
  30790. }
  30791. if (this._texture) {
  30792. return this._texture.isReady;
  30793. }
  30794. return false;
  30795. };
  30796. /**
  30797. * Get the size of the texture.
  30798. * @returns the texture size.
  30799. */
  30800. BaseTexture.prototype.getSize = function () {
  30801. if (this._texture) {
  30802. if (this._texture.width) {
  30803. this._cachedSize.width = this._texture.width;
  30804. this._cachedSize.height = this._texture.height;
  30805. return this._cachedSize;
  30806. }
  30807. if (this._texture._size) {
  30808. this._cachedSize.width = this._texture._size;
  30809. this._cachedSize.height = this._texture._size;
  30810. return this._cachedSize;
  30811. }
  30812. }
  30813. return this._cachedSize;
  30814. };
  30815. /**
  30816. * Get the base size of the texture.
  30817. * It can be different from the size if the texture has been resized for POT for instance
  30818. * @returns the base size
  30819. */
  30820. BaseTexture.prototype.getBaseSize = function () {
  30821. if (!this.isReady() || !this._texture)
  30822. return BABYLON.Size.Zero();
  30823. if (this._texture._size) {
  30824. return new BABYLON.Size(this._texture._size, this._texture._size);
  30825. }
  30826. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30827. };
  30828. /**
  30829. * Scales the texture if is `canRescale()`
  30830. * @param ratio the resize factor we want to use to rescale
  30831. */
  30832. BaseTexture.prototype.scale = function (ratio) {
  30833. };
  30834. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30835. /**
  30836. * Get if the texture can rescale.
  30837. */
  30838. get: function () {
  30839. return false;
  30840. },
  30841. enumerable: true,
  30842. configurable: true
  30843. });
  30844. /** @hidden */
  30845. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30846. if (!this._scene) {
  30847. return null;
  30848. }
  30849. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30850. for (var index = 0; index < texturesCache.length; index++) {
  30851. var texturesCacheEntry = texturesCache[index];
  30852. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30853. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30854. texturesCacheEntry.incrementReferences();
  30855. return texturesCacheEntry;
  30856. }
  30857. }
  30858. }
  30859. return null;
  30860. };
  30861. /** @hidden */
  30862. BaseTexture.prototype._rebuild = function () {
  30863. };
  30864. /**
  30865. * Triggers the load sequence in delayed load mode.
  30866. */
  30867. BaseTexture.prototype.delayLoad = function () {
  30868. };
  30869. /**
  30870. * Clones the texture.
  30871. * @returns the cloned texture
  30872. */
  30873. BaseTexture.prototype.clone = function () {
  30874. return null;
  30875. };
  30876. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30877. /**
  30878. * Get the texture underlying type (INT, FLOAT...)
  30879. */
  30880. get: function () {
  30881. if (!this._texture) {
  30882. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30883. }
  30884. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30885. },
  30886. enumerable: true,
  30887. configurable: true
  30888. });
  30889. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30890. /**
  30891. * Get the texture underlying format (RGB, RGBA...)
  30892. */
  30893. get: function () {
  30894. if (!this._texture) {
  30895. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30896. }
  30897. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30898. },
  30899. enumerable: true,
  30900. configurable: true
  30901. });
  30902. /**
  30903. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30904. * This will returns an RGBA array buffer containing either in values (0-255) or
  30905. * float values (0-1) depending of the underlying buffer type.
  30906. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30907. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30908. * @param buffer defines a user defined buffer to fill with data (can be null)
  30909. * @returns The Array buffer containing the pixels data.
  30910. */
  30911. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30912. if (faceIndex === void 0) { faceIndex = 0; }
  30913. if (level === void 0) { level = 0; }
  30914. if (buffer === void 0) { buffer = null; }
  30915. if (!this._texture) {
  30916. return null;
  30917. }
  30918. var size = this.getSize();
  30919. var width = size.width;
  30920. var height = size.height;
  30921. var scene = this.getScene();
  30922. if (!scene) {
  30923. return null;
  30924. }
  30925. var engine = scene.getEngine();
  30926. if (level != 0) {
  30927. width = width / Math.pow(2, level);
  30928. height = height / Math.pow(2, level);
  30929. width = Math.round(width);
  30930. height = Math.round(height);
  30931. }
  30932. if (this._texture.isCube) {
  30933. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30934. }
  30935. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30936. };
  30937. /**
  30938. * Release and destroy the underlying lower level texture aka internalTexture.
  30939. */
  30940. BaseTexture.prototype.releaseInternalTexture = function () {
  30941. if (this._texture) {
  30942. this._texture.dispose();
  30943. this._texture = null;
  30944. }
  30945. };
  30946. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30947. /**
  30948. * Get the polynomial representation of the texture data.
  30949. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  30950. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  30951. */
  30952. get: function () {
  30953. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30954. return null;
  30955. }
  30956. if (!this._texture._sphericalPolynomial) {
  30957. this._texture._sphericalPolynomial =
  30958. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30959. }
  30960. return this._texture._sphericalPolynomial;
  30961. },
  30962. set: function (value) {
  30963. if (this._texture) {
  30964. this._texture._sphericalPolynomial = value;
  30965. }
  30966. },
  30967. enumerable: true,
  30968. configurable: true
  30969. });
  30970. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30971. /** @hidden */
  30972. get: function () {
  30973. if (this._texture) {
  30974. return this._texture._lodTextureHigh;
  30975. }
  30976. return null;
  30977. },
  30978. enumerable: true,
  30979. configurable: true
  30980. });
  30981. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30982. /** @hidden */
  30983. get: function () {
  30984. if (this._texture) {
  30985. return this._texture._lodTextureMid;
  30986. }
  30987. return null;
  30988. },
  30989. enumerable: true,
  30990. configurable: true
  30991. });
  30992. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30993. /** @hidden */
  30994. get: function () {
  30995. if (this._texture) {
  30996. return this._texture._lodTextureLow;
  30997. }
  30998. return null;
  30999. },
  31000. enumerable: true,
  31001. configurable: true
  31002. });
  31003. /**
  31004. * Dispose the texture and release its associated resources.
  31005. */
  31006. BaseTexture.prototype.dispose = function () {
  31007. if (!this._scene) {
  31008. return;
  31009. }
  31010. // Animations
  31011. this._scene.stopAnimation(this);
  31012. // Remove from scene
  31013. this._scene._removePendingData(this);
  31014. var index = this._scene.textures.indexOf(this);
  31015. if (index >= 0) {
  31016. this._scene.textures.splice(index, 1);
  31017. }
  31018. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31019. if (this._texture === undefined) {
  31020. return;
  31021. }
  31022. // Release
  31023. this.releaseInternalTexture();
  31024. // Callback
  31025. this.onDisposeObservable.notifyObservers(this);
  31026. this.onDisposeObservable.clear();
  31027. };
  31028. /**
  31029. * Serialize the texture into a JSON representation that can be parsed later on.
  31030. * @returns the JSON representation of the texture
  31031. */
  31032. BaseTexture.prototype.serialize = function () {
  31033. if (!this.name) {
  31034. return null;
  31035. }
  31036. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31037. // Animations
  31038. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31039. return serializationObject;
  31040. };
  31041. /**
  31042. * Helper function to be called back once a list of texture contains only ready textures.
  31043. * @param textures Define the list of textures to wait for
  31044. * @param callback Define the callback triggered once the entire list will be ready
  31045. */
  31046. BaseTexture.WhenAllReady = function (textures, callback) {
  31047. var numRemaining = textures.length;
  31048. if (numRemaining === 0) {
  31049. callback();
  31050. return;
  31051. }
  31052. var _loop_1 = function () {
  31053. texture = textures[i];
  31054. if (texture.isReady()) {
  31055. if (--numRemaining === 0) {
  31056. callback();
  31057. }
  31058. }
  31059. else {
  31060. onLoadObservable = texture.onLoadObservable;
  31061. var onLoadCallback_1 = function () {
  31062. onLoadObservable.removeCallback(onLoadCallback_1);
  31063. if (--numRemaining === 0) {
  31064. callback();
  31065. }
  31066. };
  31067. onLoadObservable.add(onLoadCallback_1);
  31068. }
  31069. };
  31070. var texture, onLoadObservable;
  31071. for (var i = 0; i < textures.length; i++) {
  31072. _loop_1();
  31073. }
  31074. };
  31075. /**
  31076. * Default anisotropic filtering level for the application.
  31077. * It is set to 4 as a good tradeoff between perf and quality.
  31078. */
  31079. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31080. __decorate([
  31081. BABYLON.serialize()
  31082. ], BaseTexture.prototype, "name", void 0);
  31083. __decorate([
  31084. BABYLON.serialize("hasAlpha")
  31085. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31086. __decorate([
  31087. BABYLON.serialize()
  31088. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31089. __decorate([
  31090. BABYLON.serialize()
  31091. ], BaseTexture.prototype, "level", void 0);
  31092. __decorate([
  31093. BABYLON.serialize()
  31094. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31095. __decorate([
  31096. BABYLON.serialize("coordinatesMode")
  31097. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31098. __decorate([
  31099. BABYLON.serialize()
  31100. ], BaseTexture.prototype, "wrapU", void 0);
  31101. __decorate([
  31102. BABYLON.serialize()
  31103. ], BaseTexture.prototype, "wrapV", void 0);
  31104. __decorate([
  31105. BABYLON.serialize()
  31106. ], BaseTexture.prototype, "wrapR", void 0);
  31107. __decorate([
  31108. BABYLON.serialize()
  31109. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31110. __decorate([
  31111. BABYLON.serialize()
  31112. ], BaseTexture.prototype, "isCube", void 0);
  31113. __decorate([
  31114. BABYLON.serialize()
  31115. ], BaseTexture.prototype, "is3D", void 0);
  31116. __decorate([
  31117. BABYLON.serialize()
  31118. ], BaseTexture.prototype, "gammaSpace", void 0);
  31119. __decorate([
  31120. BABYLON.serialize()
  31121. ], BaseTexture.prototype, "invertZ", void 0);
  31122. __decorate([
  31123. BABYLON.serialize()
  31124. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31125. __decorate([
  31126. BABYLON.serialize()
  31127. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31128. __decorate([
  31129. BABYLON.serialize()
  31130. ], BaseTexture.prototype, "lodGenerationScale", null);
  31131. __decorate([
  31132. BABYLON.serialize()
  31133. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31134. return BaseTexture;
  31135. }());
  31136. BABYLON.BaseTexture = BaseTexture;
  31137. })(BABYLON || (BABYLON = {}));
  31138. //# sourceMappingURL=babylon.baseTexture.js.map
  31139. var BABYLON;
  31140. (function (BABYLON) {
  31141. var Texture = /** @class */ (function (_super) {
  31142. __extends(Texture, _super);
  31143. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31144. if (noMipmap === void 0) { noMipmap = false; }
  31145. if (invertY === void 0) { invertY = true; }
  31146. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31147. if (onLoad === void 0) { onLoad = null; }
  31148. if (onError === void 0) { onError = null; }
  31149. if (buffer === void 0) { buffer = null; }
  31150. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31151. var _this = _super.call(this, scene) || this;
  31152. _this.uOffset = 0;
  31153. _this.vOffset = 0;
  31154. _this.uScale = 1.0;
  31155. _this.vScale = 1.0;
  31156. _this.uAng = 0;
  31157. _this.vAng = 0;
  31158. _this.wAng = 0;
  31159. /**
  31160. * Defines the center of rotation (U)
  31161. */
  31162. _this.uRotationCenter = 0.5;
  31163. /**
  31164. * Defines the center of rotation (V)
  31165. */
  31166. _this.vRotationCenter = 0.5;
  31167. /**
  31168. * Defines the center of rotation (W)
  31169. */
  31170. _this.wRotationCenter = 0.5;
  31171. _this._isBlocking = true;
  31172. _this.name = url || "";
  31173. _this.url = url;
  31174. _this._noMipmap = noMipmap;
  31175. _this._invertY = invertY;
  31176. _this._samplingMode = samplingMode;
  31177. _this._buffer = buffer;
  31178. _this._deleteBuffer = deleteBuffer;
  31179. if (format) {
  31180. _this._format = format;
  31181. }
  31182. scene = _this.getScene();
  31183. if (!scene) {
  31184. return _this;
  31185. }
  31186. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31187. var load = function () {
  31188. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31189. _this.onLoadObservable.notifyObservers(_this);
  31190. }
  31191. if (onLoad) {
  31192. onLoad();
  31193. }
  31194. if (!_this.isBlocking && scene) {
  31195. scene.resetCachedMaterial();
  31196. }
  31197. };
  31198. if (!_this.url) {
  31199. _this._delayedOnLoad = load;
  31200. _this._delayedOnError = onError;
  31201. return _this;
  31202. }
  31203. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31204. if (!_this._texture) {
  31205. if (!scene.useDelayedTextureLoading) {
  31206. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31207. if (deleteBuffer) {
  31208. delete _this._buffer;
  31209. }
  31210. }
  31211. else {
  31212. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31213. _this._delayedOnLoad = load;
  31214. _this._delayedOnError = onError;
  31215. }
  31216. }
  31217. else {
  31218. if (_this._texture.isReady) {
  31219. BABYLON.Tools.SetImmediate(function () { return load(); });
  31220. }
  31221. else {
  31222. _this._texture.onLoadedObservable.add(load);
  31223. }
  31224. }
  31225. return _this;
  31226. }
  31227. Object.defineProperty(Texture.prototype, "noMipmap", {
  31228. get: function () {
  31229. return this._noMipmap;
  31230. },
  31231. enumerable: true,
  31232. configurable: true
  31233. });
  31234. Object.defineProperty(Texture.prototype, "isBlocking", {
  31235. get: function () {
  31236. return this._isBlocking;
  31237. },
  31238. set: function (value) {
  31239. this._isBlocking = value;
  31240. },
  31241. enumerable: true,
  31242. configurable: true
  31243. });
  31244. Object.defineProperty(Texture.prototype, "samplingMode", {
  31245. get: function () {
  31246. return this._samplingMode;
  31247. },
  31248. enumerable: true,
  31249. configurable: true
  31250. });
  31251. /**
  31252. * Update the url (and optional buffer) of this texture if url was null during construction.
  31253. * @param url the url of the texture
  31254. * @param buffer the buffer of the texture (defaults to null)
  31255. */
  31256. Texture.prototype.updateURL = function (url, buffer) {
  31257. if (buffer === void 0) { buffer = null; }
  31258. if (this.url) {
  31259. throw new Error("URL is already set");
  31260. }
  31261. this.url = url;
  31262. this._buffer = buffer;
  31263. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31264. this.delayLoad();
  31265. };
  31266. Texture.prototype.delayLoad = function () {
  31267. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31268. return;
  31269. }
  31270. var scene = this.getScene();
  31271. if (!scene) {
  31272. return;
  31273. }
  31274. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31275. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31276. if (!this._texture) {
  31277. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31278. if (this._deleteBuffer) {
  31279. delete this._buffer;
  31280. }
  31281. }
  31282. else {
  31283. if (this._delayedOnLoad) {
  31284. if (this._texture.isReady) {
  31285. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31286. }
  31287. else {
  31288. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31289. }
  31290. }
  31291. }
  31292. this._delayedOnLoad = null;
  31293. this._delayedOnError = null;
  31294. };
  31295. /**
  31296. * Default is Trilinear mode.
  31297. *
  31298. * | Value | Type | Description |
  31299. * | ----- | ------------------ | ----------- |
  31300. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31301. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31302. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31303. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31304. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31305. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31306. * | 7 | NEAREST_LINEAR | |
  31307. * | 8 | NEAREST_NEAREST | |
  31308. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31309. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31310. * | 11 | LINEAR_LINEAR | |
  31311. * | 12 | LINEAR_NEAREST | |
  31312. *
  31313. * > _mag_: magnification filter (close to the viewer)
  31314. * > _min_: minification filter (far from the viewer)
  31315. * > _mip_: filter used between mip map levels
  31316. *
  31317. */
  31318. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31319. if (!this._texture) {
  31320. return;
  31321. }
  31322. var scene = this.getScene();
  31323. if (!scene) {
  31324. return;
  31325. }
  31326. this._samplingMode = samplingMode;
  31327. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31328. };
  31329. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31330. x *= this.uScale;
  31331. y *= this.vScale;
  31332. x -= this.uRotationCenter * this.uScale;
  31333. y -= this.vRotationCenter * this.vScale;
  31334. z -= this.wRotationCenter;
  31335. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31336. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31337. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31338. t.z += this.wRotationCenter;
  31339. };
  31340. Texture.prototype.getTextureMatrix = function () {
  31341. var _this = this;
  31342. if (this.uOffset === this._cachedUOffset &&
  31343. this.vOffset === this._cachedVOffset &&
  31344. this.uScale === this._cachedUScale &&
  31345. this.vScale === this._cachedVScale &&
  31346. this.uAng === this._cachedUAng &&
  31347. this.vAng === this._cachedVAng &&
  31348. this.wAng === this._cachedWAng) {
  31349. return this._cachedTextureMatrix;
  31350. }
  31351. this._cachedUOffset = this.uOffset;
  31352. this._cachedVOffset = this.vOffset;
  31353. this._cachedUScale = this.uScale;
  31354. this._cachedVScale = this.vScale;
  31355. this._cachedUAng = this.uAng;
  31356. this._cachedVAng = this.vAng;
  31357. this._cachedWAng = this.wAng;
  31358. if (!this._cachedTextureMatrix) {
  31359. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31360. this._rowGenerationMatrix = new BABYLON.Matrix();
  31361. this._t0 = BABYLON.Vector3.Zero();
  31362. this._t1 = BABYLON.Vector3.Zero();
  31363. this._t2 = BABYLON.Vector3.Zero();
  31364. }
  31365. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31366. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31367. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31368. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31369. this._t1.subtractInPlace(this._t0);
  31370. this._t2.subtractInPlace(this._t0);
  31371. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31372. this._cachedTextureMatrix.m[0] = this._t1.x;
  31373. this._cachedTextureMatrix.m[1] = this._t1.y;
  31374. this._cachedTextureMatrix.m[2] = this._t1.z;
  31375. this._cachedTextureMatrix.m[4] = this._t2.x;
  31376. this._cachedTextureMatrix.m[5] = this._t2.y;
  31377. this._cachedTextureMatrix.m[6] = this._t2.z;
  31378. this._cachedTextureMatrix.m[8] = this._t0.x;
  31379. this._cachedTextureMatrix.m[9] = this._t0.y;
  31380. this._cachedTextureMatrix.m[10] = this._t0.z;
  31381. var scene = this.getScene();
  31382. if (!scene) {
  31383. return this._cachedTextureMatrix;
  31384. }
  31385. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31386. return mat.hasTexture(_this);
  31387. });
  31388. return this._cachedTextureMatrix;
  31389. };
  31390. Texture.prototype.getReflectionTextureMatrix = function () {
  31391. var _this = this;
  31392. var scene = this.getScene();
  31393. if (!scene) {
  31394. return this._cachedTextureMatrix;
  31395. }
  31396. if (this.uOffset === this._cachedUOffset &&
  31397. this.vOffset === this._cachedVOffset &&
  31398. this.uScale === this._cachedUScale &&
  31399. this.vScale === this._cachedVScale &&
  31400. this.coordinatesMode === this._cachedCoordinatesMode) {
  31401. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31402. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31403. return this._cachedTextureMatrix;
  31404. }
  31405. }
  31406. else {
  31407. return this._cachedTextureMatrix;
  31408. }
  31409. }
  31410. if (!this._cachedTextureMatrix) {
  31411. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31412. }
  31413. if (!this._projectionModeMatrix) {
  31414. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31415. }
  31416. this._cachedUOffset = this.uOffset;
  31417. this._cachedVOffset = this.vOffset;
  31418. this._cachedUScale = this.uScale;
  31419. this._cachedVScale = this.vScale;
  31420. this._cachedCoordinatesMode = this.coordinatesMode;
  31421. switch (this.coordinatesMode) {
  31422. case Texture.PLANAR_MODE:
  31423. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31424. this._cachedTextureMatrix[0] = this.uScale;
  31425. this._cachedTextureMatrix[5] = this.vScale;
  31426. this._cachedTextureMatrix[12] = this.uOffset;
  31427. this._cachedTextureMatrix[13] = this.vOffset;
  31428. break;
  31429. case Texture.PROJECTION_MODE:
  31430. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31431. this._projectionModeMatrix.m[0] = 0.5;
  31432. this._projectionModeMatrix.m[5] = -0.5;
  31433. this._projectionModeMatrix.m[10] = 0.0;
  31434. this._projectionModeMatrix.m[12] = 0.5;
  31435. this._projectionModeMatrix.m[13] = 0.5;
  31436. this._projectionModeMatrix.m[14] = 1.0;
  31437. this._projectionModeMatrix.m[15] = 1.0;
  31438. var projectionMatrix = scene.getProjectionMatrix();
  31439. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31440. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31441. break;
  31442. default:
  31443. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31444. break;
  31445. }
  31446. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31447. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31448. });
  31449. return this._cachedTextureMatrix;
  31450. };
  31451. Texture.prototype.clone = function () {
  31452. var _this = this;
  31453. return BABYLON.SerializationHelper.Clone(function () {
  31454. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31455. }, this);
  31456. };
  31457. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31458. get: function () {
  31459. if (!this._onLoadObservable) {
  31460. this._onLoadObservable = new BABYLON.Observable();
  31461. }
  31462. return this._onLoadObservable;
  31463. },
  31464. enumerable: true,
  31465. configurable: true
  31466. });
  31467. Texture.prototype.serialize = function () {
  31468. var serializationObject = _super.prototype.serialize.call(this);
  31469. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31470. serializationObject.base64String = this._buffer;
  31471. serializationObject.name = serializationObject.name.replace("data:", "");
  31472. }
  31473. serializationObject.invertY = this._invertY;
  31474. serializationObject.samplingMode = this.samplingMode;
  31475. return serializationObject;
  31476. };
  31477. Texture.prototype.getClassName = function () {
  31478. return "Texture";
  31479. };
  31480. Texture.prototype.dispose = function () {
  31481. _super.prototype.dispose.call(this);
  31482. if (this._onLoadObservable) {
  31483. this._onLoadObservable.clear();
  31484. this._onLoadObservable = null;
  31485. }
  31486. this._delayedOnLoad = null;
  31487. this._delayedOnError = null;
  31488. };
  31489. // Statics
  31490. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31491. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31492. if (onLoad === void 0) { onLoad = null; }
  31493. if (onError === void 0) { onError = null; }
  31494. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31495. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31496. };
  31497. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31498. if (parsedTexture.customType) {
  31499. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31500. // Update Sampling Mode
  31501. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31502. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31503. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31504. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31505. }
  31506. }
  31507. return parsedCustomTexture;
  31508. }
  31509. if (parsedTexture.isCube) {
  31510. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31511. }
  31512. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31513. return null;
  31514. }
  31515. var texture = BABYLON.SerializationHelper.Parse(function () {
  31516. var generateMipMaps = true;
  31517. if (parsedTexture.noMipmap) {
  31518. generateMipMaps = false;
  31519. }
  31520. if (parsedTexture.mirrorPlane) {
  31521. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31522. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31523. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31524. return mirrorTexture;
  31525. }
  31526. else if (parsedTexture.isRenderTarget) {
  31527. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31528. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31529. return renderTargetTexture;
  31530. }
  31531. else {
  31532. var texture;
  31533. if (parsedTexture.base64String) {
  31534. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31535. }
  31536. else {
  31537. var url = rootUrl + parsedTexture.name;
  31538. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31539. url = parsedTexture.url;
  31540. }
  31541. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31542. }
  31543. return texture;
  31544. }
  31545. }, parsedTexture, scene);
  31546. // Update Sampling Mode
  31547. if (parsedTexture.samplingMode) {
  31548. var sampling = parsedTexture.samplingMode;
  31549. if (texture._samplingMode !== sampling) {
  31550. texture.updateSamplingMode(sampling);
  31551. }
  31552. }
  31553. // Animations
  31554. if (parsedTexture.animations) {
  31555. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31556. var parsedAnimation = parsedTexture.animations[animationIndex];
  31557. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31558. }
  31559. }
  31560. return texture;
  31561. };
  31562. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31563. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31564. if (noMipmap === void 0) { noMipmap = false; }
  31565. if (invertY === void 0) { invertY = true; }
  31566. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31567. if (onLoad === void 0) { onLoad = null; }
  31568. if (onError === void 0) { onError = null; }
  31569. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31570. if (name.substr(0, 5) !== "data:") {
  31571. name = "data:" + name;
  31572. }
  31573. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31574. };
  31575. // Constants
  31576. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31577. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31578. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31579. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31580. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31581. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31582. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31583. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31584. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31585. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31586. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31587. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31588. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31589. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31590. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31591. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31592. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31593. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31594. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31595. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31596. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31597. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31598. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31599. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31600. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31601. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31602. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31603. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31604. /**
  31605. * 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
  31606. */
  31607. Texture.UseSerializedUrlIfAny = false;
  31608. __decorate([
  31609. BABYLON.serialize()
  31610. ], Texture.prototype, "url", void 0);
  31611. __decorate([
  31612. BABYLON.serialize()
  31613. ], Texture.prototype, "uOffset", void 0);
  31614. __decorate([
  31615. BABYLON.serialize()
  31616. ], Texture.prototype, "vOffset", void 0);
  31617. __decorate([
  31618. BABYLON.serialize()
  31619. ], Texture.prototype, "uScale", void 0);
  31620. __decorate([
  31621. BABYLON.serialize()
  31622. ], Texture.prototype, "vScale", void 0);
  31623. __decorate([
  31624. BABYLON.serialize()
  31625. ], Texture.prototype, "uAng", void 0);
  31626. __decorate([
  31627. BABYLON.serialize()
  31628. ], Texture.prototype, "vAng", void 0);
  31629. __decorate([
  31630. BABYLON.serialize()
  31631. ], Texture.prototype, "wAng", void 0);
  31632. __decorate([
  31633. BABYLON.serialize()
  31634. ], Texture.prototype, "uRotationCenter", void 0);
  31635. __decorate([
  31636. BABYLON.serialize()
  31637. ], Texture.prototype, "vRotationCenter", void 0);
  31638. __decorate([
  31639. BABYLON.serialize()
  31640. ], Texture.prototype, "wRotationCenter", void 0);
  31641. __decorate([
  31642. BABYLON.serialize()
  31643. ], Texture.prototype, "isBlocking", null);
  31644. return Texture;
  31645. }(BABYLON.BaseTexture));
  31646. BABYLON.Texture = Texture;
  31647. })(BABYLON || (BABYLON = {}));
  31648. //# sourceMappingURL=babylon.texture.js.map
  31649. var BABYLON;
  31650. (function (BABYLON) {
  31651. /**
  31652. * @hidden
  31653. **/
  31654. var _CreationDataStorage = /** @class */ (function () {
  31655. function _CreationDataStorage() {
  31656. }
  31657. return _CreationDataStorage;
  31658. }());
  31659. BABYLON._CreationDataStorage = _CreationDataStorage;
  31660. /**
  31661. * @hidden
  31662. **/
  31663. var _InstanceDataStorage = /** @class */ (function () {
  31664. function _InstanceDataStorage() {
  31665. this.visibleInstances = {};
  31666. this.renderIdForInstances = new Array();
  31667. this.batchCache = new _InstancesBatch();
  31668. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31669. }
  31670. return _InstanceDataStorage;
  31671. }());
  31672. /**
  31673. * @hidden
  31674. **/
  31675. var _InstancesBatch = /** @class */ (function () {
  31676. function _InstancesBatch() {
  31677. this.mustReturn = false;
  31678. this.visibleInstances = new Array();
  31679. this.renderSelf = new Array();
  31680. }
  31681. return _InstancesBatch;
  31682. }());
  31683. BABYLON._InstancesBatch = _InstancesBatch;
  31684. /**
  31685. * Class used to represent renderable models
  31686. */
  31687. var Mesh = /** @class */ (function (_super) {
  31688. __extends(Mesh, _super);
  31689. /**
  31690. * @constructor
  31691. * @param name The value used by scene.getMeshByName() to do a lookup.
  31692. * @param scene The scene to add this mesh to.
  31693. * @param parent The parent of this mesh, if it has one
  31694. * @param source An optional Mesh from which geometry is shared, cloned.
  31695. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31696. * When false, achieved by calling a clone(), also passing False.
  31697. * This will make creation of children, recursive.
  31698. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31699. */
  31700. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31701. if (scene === void 0) { scene = null; }
  31702. if (parent === void 0) { parent = null; }
  31703. if (source === void 0) { source = null; }
  31704. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31705. var _this = _super.call(this, name, scene) || this;
  31706. // Members
  31707. /**
  31708. * Gets the delay loading state of the mesh (when delay loading is turned on)
  31709. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  31710. */
  31711. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31712. /**
  31713. * Gets the list of instances created from this mesh
  31714. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  31715. */
  31716. _this.instances = new Array();
  31717. _this._LODLevels = new Array();
  31718. /** @hidden */
  31719. _this._instanceDataStorage = new _InstanceDataStorage();
  31720. // Use by builder only to know what orientation were the mesh build in.
  31721. /** @hidden */
  31722. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31723. /**
  31724. * Use this property to change the original side orientation defined at construction time
  31725. */
  31726. _this.overrideMaterialSideOrientation = null;
  31727. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31728. // Will be used to save a source mesh reference, If any
  31729. _this._source = null;
  31730. scene = _this.getScene();
  31731. if (source) {
  31732. // Geometry
  31733. if (source._geometry) {
  31734. source._geometry.applyToMesh(_this);
  31735. }
  31736. // Deep copy
  31737. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31738. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31739. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31740. ], ["_poseMatrix"]);
  31741. // Source mesh
  31742. _this._source = source;
  31743. // Construction Params
  31744. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31745. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31746. _this._creationDataStorage = source._creationDataStorage;
  31747. // Animation ranges
  31748. if (_this._source._ranges) {
  31749. var ranges = _this._source._ranges;
  31750. for (var name in ranges) {
  31751. if (!ranges.hasOwnProperty(name)) {
  31752. continue;
  31753. }
  31754. if (!ranges[name]) {
  31755. continue;
  31756. }
  31757. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31758. }
  31759. }
  31760. // Metadata
  31761. if (source.metadata && source.metadata.clone) {
  31762. _this.metadata = source.metadata.clone();
  31763. }
  31764. else {
  31765. _this.metadata = source.metadata;
  31766. }
  31767. // Tags
  31768. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31769. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31770. }
  31771. // Parent
  31772. _this.parent = source.parent;
  31773. // Pivot
  31774. _this.setPivotMatrix(source.getPivotMatrix());
  31775. _this.id = name + "." + source.id;
  31776. // Material
  31777. _this.material = source.material;
  31778. var index;
  31779. if (!doNotCloneChildren) {
  31780. // Children
  31781. var directDescendants = source.getDescendants(true);
  31782. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31783. var child = directDescendants[index_1];
  31784. if (child.clone) {
  31785. child.clone(name + "." + child.name, _this);
  31786. }
  31787. }
  31788. }
  31789. // Physics clone
  31790. var physicsEngine = _this.getScene().getPhysicsEngine();
  31791. if (clonePhysicsImpostor && physicsEngine) {
  31792. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31793. if (impostor) {
  31794. _this.physicsImpostor = impostor.clone(_this);
  31795. }
  31796. }
  31797. // Particles
  31798. for (index = 0; index < scene.particleSystems.length; index++) {
  31799. var system = scene.particleSystems[index];
  31800. if (system.emitter === source) {
  31801. system.clone(system.name, _this);
  31802. }
  31803. }
  31804. _this.refreshBoundingInfo();
  31805. _this.computeWorldMatrix(true);
  31806. }
  31807. // Parent
  31808. if (parent !== null) {
  31809. _this.parent = parent;
  31810. }
  31811. return _this;
  31812. }
  31813. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31814. /**
  31815. * An event triggered before rendering the mesh
  31816. */
  31817. get: function () {
  31818. if (!this._onBeforeRenderObservable) {
  31819. this._onBeforeRenderObservable = new BABYLON.Observable();
  31820. }
  31821. return this._onBeforeRenderObservable;
  31822. },
  31823. enumerable: true,
  31824. configurable: true
  31825. });
  31826. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31827. /**
  31828. * An event triggered after rendering the mesh
  31829. */
  31830. get: function () {
  31831. if (!this._onAfterRenderObservable) {
  31832. this._onAfterRenderObservable = new BABYLON.Observable();
  31833. }
  31834. return this._onAfterRenderObservable;
  31835. },
  31836. enumerable: true,
  31837. configurable: true
  31838. });
  31839. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31840. /**
  31841. * An event triggered before drawing the mesh
  31842. */
  31843. get: function () {
  31844. if (!this._onBeforeDrawObservable) {
  31845. this._onBeforeDrawObservable = new BABYLON.Observable();
  31846. }
  31847. return this._onBeforeDrawObservable;
  31848. },
  31849. enumerable: true,
  31850. configurable: true
  31851. });
  31852. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31853. /**
  31854. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31855. */
  31856. set: function (callback) {
  31857. if (this._onBeforeDrawObserver) {
  31858. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31859. }
  31860. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31861. },
  31862. enumerable: true,
  31863. configurable: true
  31864. });
  31865. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31866. /**
  31867. * Gets or sets the morph target manager
  31868. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31869. */
  31870. get: function () {
  31871. return this._morphTargetManager;
  31872. },
  31873. set: function (value) {
  31874. if (this._morphTargetManager === value) {
  31875. return;
  31876. }
  31877. this._morphTargetManager = value;
  31878. this._syncGeometryWithMorphTargetManager();
  31879. },
  31880. enumerable: true,
  31881. configurable: true
  31882. });
  31883. Object.defineProperty(Mesh.prototype, "source", {
  31884. /**
  31885. * Gets the source mesh (the one used to clone this one from)
  31886. */
  31887. get: function () {
  31888. return this._source;
  31889. },
  31890. enumerable: true,
  31891. configurable: true
  31892. });
  31893. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31894. /**
  31895. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31896. */
  31897. get: function () {
  31898. return this._unIndexed;
  31899. },
  31900. set: function (value) {
  31901. if (this._unIndexed !== value) {
  31902. this._unIndexed = value;
  31903. this._markSubMeshesAsAttributesDirty();
  31904. }
  31905. },
  31906. enumerable: true,
  31907. configurable: true
  31908. });
  31909. // Methods
  31910. /**
  31911. * Gets the class name
  31912. * @returns the string "Mesh".
  31913. */
  31914. Mesh.prototype.getClassName = function () {
  31915. return "Mesh";
  31916. };
  31917. /**
  31918. * Returns a description of this mesh
  31919. * @param fullDetails define if full details about this mesh must be used
  31920. * @returns a descriptive string representing this mesh
  31921. */
  31922. Mesh.prototype.toString = function (fullDetails) {
  31923. var ret = _super.prototype.toString.call(this, fullDetails);
  31924. ret += ", n vertices: " + this.getTotalVertices();
  31925. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31926. if (this.animations) {
  31927. for (var i = 0; i < this.animations.length; i++) {
  31928. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31929. }
  31930. }
  31931. if (fullDetails) {
  31932. if (this._geometry) {
  31933. var ib = this.getIndices();
  31934. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31935. if (vb && ib) {
  31936. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31937. }
  31938. }
  31939. else {
  31940. ret += ", flat shading: UNKNOWN";
  31941. }
  31942. }
  31943. return ret;
  31944. };
  31945. /** @hidden */
  31946. Mesh.prototype._unBindEffect = function () {
  31947. _super.prototype._unBindEffect.call(this);
  31948. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31949. var instance = _a[_i];
  31950. instance._unBindEffect();
  31951. }
  31952. };
  31953. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31954. /**
  31955. * Gets a boolean indicating if this mesh has LOD
  31956. */
  31957. get: function () {
  31958. return this._LODLevels.length > 0;
  31959. },
  31960. enumerable: true,
  31961. configurable: true
  31962. });
  31963. /**
  31964. * Gets the list of MeshLODLevel associated with the current mesh
  31965. * @returns an array of MeshLODLevel
  31966. */
  31967. Mesh.prototype.getLODLevels = function () {
  31968. return this._LODLevels;
  31969. };
  31970. Mesh.prototype._sortLODLevels = function () {
  31971. this._LODLevels.sort(function (a, b) {
  31972. if (a.distance < b.distance) {
  31973. return 1;
  31974. }
  31975. if (a.distance > b.distance) {
  31976. return -1;
  31977. }
  31978. return 0;
  31979. });
  31980. };
  31981. /**
  31982. * Add a mesh as LOD level triggered at the given distance.
  31983. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31984. * @param distance The distance from the center of the object to show this level
  31985. * @param mesh The mesh to be added as LOD level (can be null)
  31986. * @return This mesh (for chaining)
  31987. */
  31988. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31989. if (mesh && mesh._masterMesh) {
  31990. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31991. return this;
  31992. }
  31993. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31994. this._LODLevels.push(level);
  31995. if (mesh) {
  31996. mesh._masterMesh = this;
  31997. }
  31998. this._sortLODLevels();
  31999. return this;
  32000. };
  32001. /**
  32002. * Returns the LOD level mesh at the passed distance or null if not found.
  32003. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32004. * @param distance The distance from the center of the object to show this level
  32005. * @returns a Mesh or `null`
  32006. */
  32007. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32008. for (var index = 0; index < this._LODLevels.length; index++) {
  32009. var level = this._LODLevels[index];
  32010. if (level.distance === distance) {
  32011. return level.mesh;
  32012. }
  32013. }
  32014. return null;
  32015. };
  32016. /**
  32017. * Remove a mesh from the LOD array
  32018. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32019. * @param mesh defines the mesh to be removed
  32020. * @return This mesh (for chaining)
  32021. */
  32022. Mesh.prototype.removeLODLevel = function (mesh) {
  32023. for (var index = 0; index < this._LODLevels.length; index++) {
  32024. if (this._LODLevels[index].mesh === mesh) {
  32025. this._LODLevels.splice(index, 1);
  32026. if (mesh) {
  32027. mesh._masterMesh = null;
  32028. }
  32029. }
  32030. }
  32031. this._sortLODLevels();
  32032. return this;
  32033. };
  32034. /**
  32035. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32036. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32037. * @param camera defines the camera to use to compute distance
  32038. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32039. * @return This mesh (for chaining)
  32040. */
  32041. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32042. if (!this._LODLevels || this._LODLevels.length === 0) {
  32043. return this;
  32044. }
  32045. var bSphere;
  32046. if (boundingSphere) {
  32047. bSphere = boundingSphere;
  32048. }
  32049. else {
  32050. var boundingInfo = this.getBoundingInfo();
  32051. bSphere = boundingInfo.boundingSphere;
  32052. }
  32053. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32054. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32055. if (this.onLODLevelSelection) {
  32056. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32057. }
  32058. return this;
  32059. }
  32060. for (var index = 0; index < this._LODLevels.length; index++) {
  32061. var level = this._LODLevels[index];
  32062. if (level.distance < distanceToCamera) {
  32063. if (level.mesh) {
  32064. level.mesh._preActivate();
  32065. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32066. }
  32067. if (this.onLODLevelSelection) {
  32068. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32069. }
  32070. return level.mesh;
  32071. }
  32072. }
  32073. if (this.onLODLevelSelection) {
  32074. this.onLODLevelSelection(distanceToCamera, this, this);
  32075. }
  32076. return this;
  32077. };
  32078. Object.defineProperty(Mesh.prototype, "geometry", {
  32079. /**
  32080. * Gets the mesh internal Geometry object
  32081. */
  32082. get: function () {
  32083. return this._geometry;
  32084. },
  32085. enumerable: true,
  32086. configurable: true
  32087. });
  32088. /**
  32089. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32090. * @returns the total number of vertices
  32091. */
  32092. Mesh.prototype.getTotalVertices = function () {
  32093. if (this._geometry === null || this._geometry === undefined) {
  32094. return 0;
  32095. }
  32096. return this._geometry.getTotalVertices();
  32097. };
  32098. /**
  32099. * Returns the content of an associated vertex buffer
  32100. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32101. * - BABYLON.VertexBuffer.PositionKind
  32102. * - BABYLON.VertexBuffer.UVKind
  32103. * - BABYLON.VertexBuffer.UV2Kind
  32104. * - BABYLON.VertexBuffer.UV3Kind
  32105. * - BABYLON.VertexBuffer.UV4Kind
  32106. * - BABYLON.VertexBuffer.UV5Kind
  32107. * - BABYLON.VertexBuffer.UV6Kind
  32108. * - BABYLON.VertexBuffer.ColorKind
  32109. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32110. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32111. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32112. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32113. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  32114. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32115. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32116. */
  32117. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32118. if (!this._geometry) {
  32119. return null;
  32120. }
  32121. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32122. };
  32123. /**
  32124. * Returns the mesh VertexBuffer object from the requested `kind`
  32125. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32126. * - BABYLON.VertexBuffer.PositionKind
  32127. * - BABYLON.VertexBuffer.UVKind
  32128. * - BABYLON.VertexBuffer.UV2Kind
  32129. * - BABYLON.VertexBuffer.UV3Kind
  32130. * - BABYLON.VertexBuffer.UV4Kind
  32131. * - BABYLON.VertexBuffer.UV5Kind
  32132. * - BABYLON.VertexBuffer.UV6Kind
  32133. * - BABYLON.VertexBuffer.ColorKind
  32134. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32135. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32136. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32137. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32138. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32139. */
  32140. Mesh.prototype.getVertexBuffer = function (kind) {
  32141. if (!this._geometry) {
  32142. return null;
  32143. }
  32144. return this._geometry.getVertexBuffer(kind);
  32145. };
  32146. /**
  32147. * Tests if a specific vertex buffer is associated with this mesh
  32148. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32149. * - BABYLON.VertexBuffer.PositionKind
  32150. * - BABYLON.VertexBuffer.UVKind
  32151. * - BABYLON.VertexBuffer.UV2Kind
  32152. * - BABYLON.VertexBuffer.UV3Kind
  32153. * - BABYLON.VertexBuffer.UV4Kind
  32154. * - BABYLON.VertexBuffer.UV5Kind
  32155. * - BABYLON.VertexBuffer.UV6Kind
  32156. * - BABYLON.VertexBuffer.ColorKind
  32157. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32158. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32159. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32160. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32161. * @returns a boolean
  32162. */
  32163. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32164. if (!this._geometry) {
  32165. if (this._delayInfo) {
  32166. return this._delayInfo.indexOf(kind) !== -1;
  32167. }
  32168. return false;
  32169. }
  32170. return this._geometry.isVerticesDataPresent(kind);
  32171. };
  32172. /**
  32173. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32174. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32175. * - BABYLON.VertexBuffer.PositionKind
  32176. * - BABYLON.VertexBuffer.UVKind
  32177. * - BABYLON.VertexBuffer.UV2Kind
  32178. * - BABYLON.VertexBuffer.UV3Kind
  32179. * - BABYLON.VertexBuffer.UV4Kind
  32180. * - BABYLON.VertexBuffer.UV5Kind
  32181. * - BABYLON.VertexBuffer.UV6Kind
  32182. * - BABYLON.VertexBuffer.ColorKind
  32183. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32184. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32185. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32186. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32187. * @returns a boolean
  32188. */
  32189. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32190. if (!this._geometry) {
  32191. if (this._delayInfo) {
  32192. return this._delayInfo.indexOf(kind) !== -1;
  32193. }
  32194. return false;
  32195. }
  32196. return this._geometry.isVertexBufferUpdatable(kind);
  32197. };
  32198. /**
  32199. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32200. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32201. * - BABYLON.VertexBuffer.PositionKind
  32202. * - BABYLON.VertexBuffer.UVKind
  32203. * - BABYLON.VertexBuffer.UV2Kind
  32204. * - BABYLON.VertexBuffer.UV3Kind
  32205. * - BABYLON.VertexBuffer.UV4Kind
  32206. * - BABYLON.VertexBuffer.UV5Kind
  32207. * - BABYLON.VertexBuffer.UV6Kind
  32208. * - BABYLON.VertexBuffer.ColorKind
  32209. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32210. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32211. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32212. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32213. * @returns an array of strings
  32214. */
  32215. Mesh.prototype.getVerticesDataKinds = function () {
  32216. if (!this._geometry) {
  32217. var result = new Array();
  32218. if (this._delayInfo) {
  32219. this._delayInfo.forEach(function (kind, index, array) {
  32220. result.push(kind);
  32221. });
  32222. }
  32223. return result;
  32224. }
  32225. return this._geometry.getVerticesDataKinds();
  32226. };
  32227. /**
  32228. * Returns a positive integer : the total number of indices in this mesh geometry.
  32229. * @returns the numner of indices or zero if the mesh has no geometry.
  32230. */
  32231. Mesh.prototype.getTotalIndices = function () {
  32232. if (!this._geometry) {
  32233. return 0;
  32234. }
  32235. return this._geometry.getTotalIndices();
  32236. };
  32237. /**
  32238. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32239. * @param copyWhenShared If 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.
  32240. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32241. * @returns the indices array or an empty array if the mesh has no geometry
  32242. */
  32243. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32244. if (!this._geometry) {
  32245. return [];
  32246. }
  32247. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32248. };
  32249. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32250. get: function () {
  32251. return this._masterMesh !== null && this._masterMesh !== undefined;
  32252. },
  32253. enumerable: true,
  32254. configurable: true
  32255. });
  32256. /**
  32257. * Determine if the current mesh is ready to be rendered
  32258. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32259. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32260. * @returns true if all associated assets are ready (material, textures, shaders)
  32261. */
  32262. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32263. if (completeCheck === void 0) { completeCheck = false; }
  32264. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32265. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32266. return false;
  32267. }
  32268. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32269. return false;
  32270. }
  32271. if (!this.subMeshes || this.subMeshes.length === 0) {
  32272. return true;
  32273. }
  32274. if (!completeCheck) {
  32275. return true;
  32276. }
  32277. var engine = this.getEngine();
  32278. var scene = this.getScene();
  32279. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32280. this.computeWorldMatrix();
  32281. var mat = this.material || scene.defaultMaterial;
  32282. if (mat) {
  32283. if (mat.storeEffectOnSubMeshes) {
  32284. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32285. var subMesh = _a[_i];
  32286. var effectiveMaterial = subMesh.getMaterial();
  32287. if (effectiveMaterial) {
  32288. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32289. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32290. return false;
  32291. }
  32292. }
  32293. else {
  32294. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32295. return false;
  32296. }
  32297. }
  32298. }
  32299. }
  32300. }
  32301. else {
  32302. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32303. return false;
  32304. }
  32305. }
  32306. }
  32307. // Shadows
  32308. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32309. var light = _c[_b];
  32310. var generator = light.getShadowGenerator();
  32311. if (generator) {
  32312. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32313. var subMesh = _e[_d];
  32314. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32315. return false;
  32316. }
  32317. }
  32318. }
  32319. }
  32320. // LOD
  32321. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32322. var lod = _g[_f];
  32323. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32324. return false;
  32325. }
  32326. }
  32327. return true;
  32328. };
  32329. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32330. /**
  32331. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  32332. */
  32333. get: function () {
  32334. return this._areNormalsFrozen;
  32335. },
  32336. enumerable: true,
  32337. configurable: true
  32338. });
  32339. /**
  32340. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  32341. * @returns the current mesh
  32342. */
  32343. Mesh.prototype.freezeNormals = function () {
  32344. this._areNormalsFrozen = true;
  32345. return this;
  32346. };
  32347. /**
  32348. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  32349. * @returns the current mesh
  32350. */
  32351. Mesh.prototype.unfreezeNormals = function () {
  32352. this._areNormalsFrozen = false;
  32353. return this;
  32354. };
  32355. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32356. /**
  32357. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32358. */
  32359. set: function (count) {
  32360. this._instanceDataStorage.overridenInstanceCount = count;
  32361. },
  32362. enumerable: true,
  32363. configurable: true
  32364. });
  32365. // Methods
  32366. /** @hidden */
  32367. Mesh.prototype._preActivate = function () {
  32368. var sceneRenderId = this.getScene().getRenderId();
  32369. if (this._preActivateId === sceneRenderId) {
  32370. return this;
  32371. }
  32372. this._preActivateId = sceneRenderId;
  32373. this._instanceDataStorage.visibleInstances = null;
  32374. return this;
  32375. };
  32376. /** @hidden */
  32377. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32378. if (this._instanceDataStorage.visibleInstances) {
  32379. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32380. }
  32381. return this;
  32382. };
  32383. /** @hidden */
  32384. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32385. if (!this._instanceDataStorage.visibleInstances) {
  32386. this._instanceDataStorage.visibleInstances = {};
  32387. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32388. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32389. }
  32390. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32391. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32392. }
  32393. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32394. return this;
  32395. };
  32396. /**
  32397. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32398. * This means the mesh underlying bounding box and sphere are recomputed.
  32399. * @returns the current mesh
  32400. */
  32401. Mesh.prototype.refreshBoundingInfo = function () {
  32402. return this._refreshBoundingInfo(false);
  32403. };
  32404. /** @hidden */
  32405. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32406. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32407. return this;
  32408. }
  32409. var data = this._getPositionData(applySkeleton);
  32410. if (data) {
  32411. var bias = this.geometry ? this.geometry.boundingBias : null;
  32412. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32413. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32414. }
  32415. if (this.subMeshes) {
  32416. for (var index = 0; index < this.subMeshes.length; index++) {
  32417. this.subMeshes[index].refreshBoundingInfo();
  32418. }
  32419. }
  32420. this._updateBoundingInfo();
  32421. return this;
  32422. };
  32423. Mesh.prototype._getPositionData = function (applySkeleton) {
  32424. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32425. if (data && applySkeleton && this.skeleton) {
  32426. data = BABYLON.Tools.Slice(data);
  32427. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32428. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32429. if (matricesWeightsData && matricesIndicesData) {
  32430. var needExtras = this.numBoneInfluencers > 4;
  32431. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32432. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32433. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32434. var tempVector = BABYLON.Tmp.Vector3[0];
  32435. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32436. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32437. var matWeightIdx = 0;
  32438. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32439. finalMatrix.reset();
  32440. var inf;
  32441. var weight;
  32442. for (inf = 0; inf < 4; inf++) {
  32443. weight = matricesWeightsData[matWeightIdx + inf];
  32444. if (weight > 0) {
  32445. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32446. finalMatrix.addToSelf(tempMatrix);
  32447. }
  32448. }
  32449. if (needExtras) {
  32450. for (inf = 0; inf < 4; inf++) {
  32451. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32452. if (weight > 0) {
  32453. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32454. finalMatrix.addToSelf(tempMatrix);
  32455. }
  32456. }
  32457. }
  32458. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32459. tempVector.toArray(data, index);
  32460. }
  32461. }
  32462. }
  32463. return data;
  32464. };
  32465. /** @hidden */
  32466. Mesh.prototype._createGlobalSubMesh = function (force) {
  32467. var totalVertices = this.getTotalVertices();
  32468. if (!totalVertices || !this.getIndices()) {
  32469. return null;
  32470. }
  32471. // Check if we need to recreate the submeshes
  32472. if (this.subMeshes && this.subMeshes.length > 0) {
  32473. var ib = this.getIndices();
  32474. if (!ib) {
  32475. return null;
  32476. }
  32477. var totalIndices = ib.length;
  32478. var needToRecreate = false;
  32479. if (force) {
  32480. needToRecreate = true;
  32481. }
  32482. else {
  32483. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32484. var submesh = _a[_i];
  32485. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32486. needToRecreate = true;
  32487. break;
  32488. }
  32489. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32490. needToRecreate = true;
  32491. break;
  32492. }
  32493. }
  32494. }
  32495. if (!needToRecreate) {
  32496. return this.subMeshes[0];
  32497. }
  32498. }
  32499. this.releaseSubMeshes();
  32500. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32501. };
  32502. /**
  32503. * This function will subdivide the mesh into multiple submeshes
  32504. * @param count defines the expected number of submeshes
  32505. */
  32506. Mesh.prototype.subdivide = function (count) {
  32507. if (count < 1) {
  32508. return;
  32509. }
  32510. var totalIndices = this.getTotalIndices();
  32511. var subdivisionSize = (totalIndices / count) | 0;
  32512. var offset = 0;
  32513. // Ensure that subdivisionSize is a multiple of 3
  32514. while (subdivisionSize % 3 !== 0) {
  32515. subdivisionSize++;
  32516. }
  32517. this.releaseSubMeshes();
  32518. for (var index = 0; index < count; index++) {
  32519. if (offset >= totalIndices) {
  32520. break;
  32521. }
  32522. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32523. offset += subdivisionSize;
  32524. }
  32525. this.synchronizeInstances();
  32526. };
  32527. /**
  32528. * Copy a FloatArray into a specific associated vertex buffer
  32529. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32530. * - BABYLON.VertexBuffer.PositionKind
  32531. * - BABYLON.VertexBuffer.UVKind
  32532. * - BABYLON.VertexBuffer.UV2Kind
  32533. * - BABYLON.VertexBuffer.UV3Kind
  32534. * - BABYLON.VertexBuffer.UV4Kind
  32535. * - BABYLON.VertexBuffer.UV5Kind
  32536. * - BABYLON.VertexBuffer.UV6Kind
  32537. * - BABYLON.VertexBuffer.ColorKind
  32538. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32539. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32540. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32541. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32542. * @param data defines the data source
  32543. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32544. * @param stride defines the data stride size (can be null)
  32545. * @returns the current mesh
  32546. */
  32547. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32548. if (updatable === void 0) { updatable = false; }
  32549. if (!this._geometry) {
  32550. var vertexData = new BABYLON.VertexData();
  32551. vertexData.set(data, kind);
  32552. var scene = this.getScene();
  32553. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32554. }
  32555. else {
  32556. this._geometry.setVerticesData(kind, data, updatable, stride);
  32557. }
  32558. return this;
  32559. };
  32560. /**
  32561. * Flags an associated vertex buffer as updatable
  32562. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32563. * - BABYLON.VertexBuffer.PositionKind
  32564. * - BABYLON.VertexBuffer.UVKind
  32565. * - BABYLON.VertexBuffer.UV2Kind
  32566. * - BABYLON.VertexBuffer.UV3Kind
  32567. * - BABYLON.VertexBuffer.UV4Kind
  32568. * - BABYLON.VertexBuffer.UV5Kind
  32569. * - BABYLON.VertexBuffer.UV6Kind
  32570. * - BABYLON.VertexBuffer.ColorKind
  32571. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32572. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32573. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32574. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32575. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32576. */
  32577. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32578. if (updatable === void 0) { updatable = true; }
  32579. var vb = this.getVertexBuffer(kind);
  32580. if (!vb || vb.isUpdatable() === updatable) {
  32581. return;
  32582. }
  32583. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32584. };
  32585. /**
  32586. * Sets the mesh global Vertex Buffer
  32587. * @param buffer defines the buffer to use
  32588. * @returns the current mesh
  32589. */
  32590. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32591. if (!this._geometry) {
  32592. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32593. }
  32594. this._geometry.setVerticesBuffer(buffer);
  32595. return this;
  32596. };
  32597. /**
  32598. * Update a specific associated vertex buffer
  32599. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32600. * - BABYLON.VertexBuffer.PositionKind
  32601. * - BABYLON.VertexBuffer.UVKind
  32602. * - BABYLON.VertexBuffer.UV2Kind
  32603. * - BABYLON.VertexBuffer.UV3Kind
  32604. * - BABYLON.VertexBuffer.UV4Kind
  32605. * - BABYLON.VertexBuffer.UV5Kind
  32606. * - BABYLON.VertexBuffer.UV6Kind
  32607. * - BABYLON.VertexBuffer.ColorKind
  32608. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32609. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32610. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32611. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32612. * @param data defines the data source
  32613. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32614. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  32615. * @returns the current mesh
  32616. */
  32617. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32618. if (!this._geometry) {
  32619. return this;
  32620. }
  32621. if (!makeItUnique) {
  32622. this._geometry.updateVerticesData(kind, data, updateExtends);
  32623. }
  32624. else {
  32625. this.makeGeometryUnique();
  32626. this.updateVerticesData(kind, data, updateExtends, false);
  32627. }
  32628. return this;
  32629. };
  32630. /**
  32631. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32632. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32633. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32634. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32635. * @returns the current mesh
  32636. */
  32637. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32638. if (computeNormals === void 0) { computeNormals = true; }
  32639. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32640. if (!positions) {
  32641. return this;
  32642. }
  32643. positionFunction(positions);
  32644. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32645. if (computeNormals) {
  32646. var indices = this.getIndices();
  32647. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32648. if (!normals) {
  32649. return this;
  32650. }
  32651. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32652. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32653. }
  32654. return this;
  32655. };
  32656. /**
  32657. * Creates a un-shared specific occurence of the geometry for the mesh.
  32658. * @returns the current mesh
  32659. */
  32660. Mesh.prototype.makeGeometryUnique = function () {
  32661. if (!this._geometry) {
  32662. return this;
  32663. }
  32664. var oldGeometry = this._geometry;
  32665. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32666. oldGeometry.releaseForMesh(this, true);
  32667. geometry.applyToMesh(this);
  32668. return this;
  32669. };
  32670. /**
  32671. * Set the index buffer of this mesh
  32672. * @param indices defines the source data
  32673. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  32674. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  32675. * @returns the current mesh
  32676. */
  32677. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32678. if (totalVertices === void 0) { totalVertices = null; }
  32679. if (updatable === void 0) { updatable = false; }
  32680. if (!this._geometry) {
  32681. var vertexData = new BABYLON.VertexData();
  32682. vertexData.indices = indices;
  32683. var scene = this.getScene();
  32684. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32685. }
  32686. else {
  32687. this._geometry.setIndices(indices, totalVertices, updatable);
  32688. }
  32689. return this;
  32690. };
  32691. /**
  32692. * Update the current index buffer
  32693. * @param indices defines the source data
  32694. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  32695. * @returns the current mesh
  32696. */
  32697. Mesh.prototype.updateIndices = function (indices, offset) {
  32698. if (!this._geometry) {
  32699. return this;
  32700. }
  32701. this._geometry.updateIndices(indices, offset);
  32702. return this;
  32703. };
  32704. /**
  32705. * Invert the geometry to move from a right handed system to a left handed one.
  32706. * @returns the current mesh
  32707. */
  32708. Mesh.prototype.toLeftHanded = function () {
  32709. if (!this._geometry) {
  32710. return this;
  32711. }
  32712. this._geometry.toLeftHanded();
  32713. return this;
  32714. };
  32715. /** @hidden */
  32716. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32717. if (!this._geometry) {
  32718. return this;
  32719. }
  32720. var engine = this.getScene().getEngine();
  32721. // Wireframe
  32722. var indexToBind;
  32723. if (this._unIndexed) {
  32724. indexToBind = null;
  32725. }
  32726. else {
  32727. switch (fillMode) {
  32728. case BABYLON.Material.PointFillMode:
  32729. indexToBind = null;
  32730. break;
  32731. case BABYLON.Material.WireFrameFillMode:
  32732. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  32733. break;
  32734. default:
  32735. case BABYLON.Material.TriangleFillMode:
  32736. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32737. break;
  32738. }
  32739. }
  32740. // VBOs
  32741. this._geometry._bind(effect, indexToBind);
  32742. return this;
  32743. };
  32744. /** @hidden */
  32745. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32746. if (alternate === void 0) { alternate = false; }
  32747. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32748. return this;
  32749. }
  32750. if (this._onBeforeDrawObservable) {
  32751. this._onBeforeDrawObservable.notifyObservers(this);
  32752. }
  32753. var scene = this.getScene();
  32754. var engine = scene.getEngine();
  32755. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32756. // or triangles as points
  32757. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32758. }
  32759. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32760. // Triangles as wireframe
  32761. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  32762. }
  32763. else {
  32764. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32765. }
  32766. if (scene._isAlternateRenderingEnabled && !alternate) {
  32767. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32768. if (!effect || !scene.activeCamera) {
  32769. return this;
  32770. }
  32771. scene._switchToAlternateCameraConfiguration(true);
  32772. this._effectiveMaterial.bindView(effect);
  32773. this._effectiveMaterial.bindViewProjection(effect);
  32774. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32775. this._draw(subMesh, fillMode, instancesCount, true);
  32776. engine.setViewport(scene.activeCamera.viewport);
  32777. scene._switchToAlternateCameraConfiguration(false);
  32778. this._effectiveMaterial.bindView(effect);
  32779. this._effectiveMaterial.bindViewProjection(effect);
  32780. }
  32781. return this;
  32782. };
  32783. /**
  32784. * Registers for this mesh a javascript function called just before the rendering process
  32785. * @param func defines the function to call before rendering this mesh
  32786. * @returns the current mesh
  32787. */
  32788. Mesh.prototype.registerBeforeRender = function (func) {
  32789. this.onBeforeRenderObservable.add(func);
  32790. return this;
  32791. };
  32792. /**
  32793. * Disposes a previously registered javascript function called before the rendering
  32794. * @param func defines the function to remove
  32795. * @returns the current mesh
  32796. */
  32797. Mesh.prototype.unregisterBeforeRender = function (func) {
  32798. this.onBeforeRenderObservable.removeCallback(func);
  32799. return this;
  32800. };
  32801. /**
  32802. * Registers for this mesh a javascript function called just after the rendering is complete
  32803. * @param func defines the function to call after rendering this mesh
  32804. * @returns the current mesh
  32805. */
  32806. Mesh.prototype.registerAfterRender = function (func) {
  32807. this.onAfterRenderObservable.add(func);
  32808. return this;
  32809. };
  32810. /**
  32811. * Disposes a previously registered javascript function called after the rendering.
  32812. * @param func defines the function to remove
  32813. * @returns the current mesh
  32814. */
  32815. Mesh.prototype.unregisterAfterRender = function (func) {
  32816. this.onAfterRenderObservable.removeCallback(func);
  32817. return this;
  32818. };
  32819. /** @hidden */
  32820. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32821. var scene = this.getScene();
  32822. var batchCache = this._instanceDataStorage.batchCache;
  32823. batchCache.mustReturn = false;
  32824. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32825. batchCache.visibleInstances[subMeshId] = null;
  32826. if (this._instanceDataStorage.visibleInstances) {
  32827. var visibleInstances = this._instanceDataStorage.visibleInstances;
  32828. var currentRenderId = scene.getRenderId();
  32829. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  32830. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  32831. var selfRenderId = this._renderId;
  32832. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32833. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  32834. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32835. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  32836. }
  32837. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  32838. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32839. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  32840. batchCache.mustReturn = true;
  32841. return batchCache;
  32842. }
  32843. if (currentRenderId !== selfRenderId) {
  32844. batchCache.renderSelf[subMeshId] = false;
  32845. }
  32846. }
  32847. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  32848. }
  32849. return batchCache;
  32850. };
  32851. /** @hidden */
  32852. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32853. var visibleInstances = batch.visibleInstances[subMesh._id];
  32854. if (!visibleInstances) {
  32855. return this;
  32856. }
  32857. var matricesCount = visibleInstances.length + 1;
  32858. var bufferSize = matricesCount * 16 * 4;
  32859. var instanceStorage = this._instanceDataStorage;
  32860. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  32861. var instancesBuffer = instanceStorage.instancesBuffer;
  32862. while (instanceStorage.instancesBufferSize < bufferSize) {
  32863. instanceStorage.instancesBufferSize *= 2;
  32864. }
  32865. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32866. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  32867. }
  32868. var offset = 0;
  32869. var instancesCount = 0;
  32870. var world = this.getWorldMatrix();
  32871. if (batch.renderSelf[subMesh._id]) {
  32872. world.copyToArray(instanceStorage.instancesData, offset);
  32873. offset += 16;
  32874. instancesCount++;
  32875. }
  32876. if (visibleInstances) {
  32877. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32878. var instance = visibleInstances[instanceIndex];
  32879. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  32880. offset += 16;
  32881. instancesCount++;
  32882. }
  32883. }
  32884. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32885. if (instancesBuffer) {
  32886. instancesBuffer.dispose();
  32887. }
  32888. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  32889. instanceStorage.instancesBuffer = instancesBuffer;
  32890. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32891. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32892. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32893. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32894. }
  32895. else {
  32896. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  32897. }
  32898. this._bind(subMesh, effect, fillMode);
  32899. this._draw(subMesh, fillMode, instancesCount);
  32900. engine.unbindInstanceAttributes();
  32901. return this;
  32902. };
  32903. /** @hidden */
  32904. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32905. var scene = this.getScene();
  32906. var engine = scene.getEngine();
  32907. if (hardwareInstancedRendering) {
  32908. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32909. }
  32910. else {
  32911. if (batch.renderSelf[subMesh._id]) {
  32912. // Draw
  32913. if (onBeforeDraw) {
  32914. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32915. }
  32916. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  32917. }
  32918. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32919. if (visibleInstancesForSubMesh) {
  32920. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32921. var instance = visibleInstancesForSubMesh[instanceIndex];
  32922. // World
  32923. var world = instance.getWorldMatrix();
  32924. if (onBeforeDraw) {
  32925. onBeforeDraw(true, world, effectiveMaterial);
  32926. }
  32927. // Draw
  32928. this._draw(subMesh, fillMode);
  32929. }
  32930. }
  32931. }
  32932. return this;
  32933. };
  32934. /**
  32935. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32936. * @param subMesh defines the subMesh to render
  32937. * @param enableAlphaMode defines if alpha mode can be changed
  32938. * @returns the current mesh
  32939. */
  32940. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32941. if (this._checkOcclusionQuery()) {
  32942. return this;
  32943. }
  32944. var scene = this.getScene();
  32945. // Managing instances
  32946. var batch = this._getInstancesRenderList(subMesh._id);
  32947. if (batch.mustReturn) {
  32948. return this;
  32949. }
  32950. // Checking geometry state
  32951. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32952. return this;
  32953. }
  32954. if (this._onBeforeRenderObservable) {
  32955. this._onBeforeRenderObservable.notifyObservers(this);
  32956. }
  32957. var engine = scene.getEngine();
  32958. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32959. // Material
  32960. var material = subMesh.getMaterial();
  32961. if (!material) {
  32962. return this;
  32963. }
  32964. this._effectiveMaterial = material;
  32965. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32966. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32967. return this;
  32968. }
  32969. }
  32970. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32971. return this;
  32972. }
  32973. // Alpha mode
  32974. if (enableAlphaMode) {
  32975. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32976. }
  32977. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32978. var step = _a[_i];
  32979. step.action(this, subMesh, batch);
  32980. }
  32981. var effect;
  32982. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32983. effect = subMesh.effect;
  32984. }
  32985. else {
  32986. effect = this._effectiveMaterial.getEffect();
  32987. }
  32988. if (!effect) {
  32989. return this;
  32990. }
  32991. var sideOrientation = this.overrideMaterialSideOrientation;
  32992. if (sideOrientation == null) {
  32993. sideOrientation = this._effectiveMaterial.sideOrientation;
  32994. if (this._getWorldMatrixDeterminant() < 0) {
  32995. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32996. }
  32997. }
  32998. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32999. if (this._effectiveMaterial.forceDepthWrite) {
  33000. engine.setDepthWrite(true);
  33001. }
  33002. // Bind
  33003. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33004. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33005. this._bind(subMesh, effect, fillMode);
  33006. }
  33007. var world = this.getWorldMatrix();
  33008. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33009. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33010. }
  33011. else {
  33012. this._effectiveMaterial.bind(world, this);
  33013. }
  33014. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33015. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33016. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33017. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33018. }
  33019. // Draw
  33020. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33021. // Unbind
  33022. this._effectiveMaterial.unbind();
  33023. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33024. var step = _c[_b];
  33025. step.action(this, subMesh, batch);
  33026. }
  33027. if (this._onAfterRenderObservable) {
  33028. this._onAfterRenderObservable.notifyObservers(this);
  33029. }
  33030. return this;
  33031. };
  33032. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33033. if (isInstance && effectiveMaterial) {
  33034. effectiveMaterial.bindOnlyWorldMatrix(world);
  33035. }
  33036. };
  33037. /**
  33038. * Normalize matrix weights so that all vertices have a total weight set to 1
  33039. */
  33040. Mesh.prototype.cleanMatrixWeights = function () {
  33041. var epsilon = 1e-3;
  33042. var noInfluenceBoneIndex = 0.0;
  33043. if (this.skeleton) {
  33044. noInfluenceBoneIndex = this.skeleton.bones.length;
  33045. }
  33046. else {
  33047. return;
  33048. }
  33049. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33050. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33051. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33052. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33053. var influencers = this.numBoneInfluencers;
  33054. var size = matricesWeights.length;
  33055. for (var i = 0; i < size; i += 4) {
  33056. var weight = 0.0;
  33057. var firstZeroWeight = -1;
  33058. for (var j = 0; j < 4; j++) {
  33059. var w = matricesWeights[i + j];
  33060. weight += w;
  33061. if (w < epsilon && firstZeroWeight < 0) {
  33062. firstZeroWeight = j;
  33063. }
  33064. }
  33065. if (matricesWeightsExtra) {
  33066. for (var j = 0; j < 4; j++) {
  33067. var w = matricesWeightsExtra[i + j];
  33068. weight += w;
  33069. if (w < epsilon && firstZeroWeight < 0) {
  33070. firstZeroWeight = j + 4;
  33071. }
  33072. }
  33073. }
  33074. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33075. firstZeroWeight = influencers - 1;
  33076. }
  33077. if (weight > epsilon) {
  33078. var mweight = 1.0 / weight;
  33079. for (var j = 0; j < 4; j++) {
  33080. matricesWeights[i + j] *= mweight;
  33081. }
  33082. if (matricesWeightsExtra) {
  33083. for (var j = 0; j < 4; j++) {
  33084. matricesWeightsExtra[i + j] *= mweight;
  33085. }
  33086. }
  33087. }
  33088. else {
  33089. if (firstZeroWeight >= 4) {
  33090. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33091. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33092. }
  33093. else {
  33094. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33095. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33096. }
  33097. }
  33098. }
  33099. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33100. if (matricesIndicesExtra) {
  33101. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33102. }
  33103. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33104. if (matricesWeightsExtra) {
  33105. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  33106. }
  33107. };
  33108. /** @hidden */
  33109. Mesh.prototype._checkDelayState = function () {
  33110. var scene = this.getScene();
  33111. if (this._geometry) {
  33112. this._geometry.load(scene);
  33113. }
  33114. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33115. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33116. this._queueLoad(scene);
  33117. }
  33118. return this;
  33119. };
  33120. Mesh.prototype._queueLoad = function (scene) {
  33121. var _this = this;
  33122. scene._addPendingData(this);
  33123. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33124. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33125. if (data instanceof ArrayBuffer) {
  33126. _this._delayLoadingFunction(data, _this);
  33127. }
  33128. else {
  33129. _this._delayLoadingFunction(JSON.parse(data), _this);
  33130. }
  33131. _this.instances.forEach(function (instance) {
  33132. instance._syncSubMeshes();
  33133. });
  33134. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33135. scene._removePendingData(_this);
  33136. }, function () { }, scene.database, getBinaryData);
  33137. return this;
  33138. };
  33139. /**
  33140. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33141. * A mesh is in the frustum if its bounding box intersects the frustum
  33142. * @param frustumPlanes defines the frustum to test
  33143. * @returns true if the mesh is in the frustum planes
  33144. */
  33145. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33146. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33147. return false;
  33148. }
  33149. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33150. return false;
  33151. }
  33152. this._checkDelayState();
  33153. return true;
  33154. };
  33155. /**
  33156. * Sets the mesh material by the material or multiMaterial `id` property
  33157. * @param id is a string identifying the material or the multiMaterial
  33158. * @returns the current mesh
  33159. */
  33160. Mesh.prototype.setMaterialByID = function (id) {
  33161. var materials = this.getScene().materials;
  33162. var index;
  33163. for (index = materials.length - 1; index > -1; index--) {
  33164. if (materials[index].id === id) {
  33165. this.material = materials[index];
  33166. return this;
  33167. }
  33168. }
  33169. // Multi
  33170. var multiMaterials = this.getScene().multiMaterials;
  33171. for (index = multiMaterials.length - 1; index > -1; index--) {
  33172. if (multiMaterials[index].id === id) {
  33173. this.material = multiMaterials[index];
  33174. return this;
  33175. }
  33176. }
  33177. return this;
  33178. };
  33179. /**
  33180. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33181. * @returns an array of IAnimatable
  33182. */
  33183. Mesh.prototype.getAnimatables = function () {
  33184. var results = new Array();
  33185. if (this.material) {
  33186. results.push(this.material);
  33187. }
  33188. if (this.skeleton) {
  33189. results.push(this.skeleton);
  33190. }
  33191. return results;
  33192. };
  33193. /**
  33194. * Modifies the mesh geometry according to the passed transformation matrix.
  33195. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33196. * The mesh normals are modified using the same transformation.
  33197. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33198. * @param transform defines the transform matrix to use
  33199. * @see http://doc.babylonjs.com/resources/baking_transformations
  33200. * @returns the current mesh
  33201. */
  33202. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33203. // Position
  33204. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33205. return this;
  33206. }
  33207. var submeshes = this.subMeshes.splice(0);
  33208. this._resetPointsArrayCache();
  33209. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33210. var temp = new Array();
  33211. var index;
  33212. for (index = 0; index < data.length; index += 3) {
  33213. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33214. }
  33215. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33216. // Normals
  33217. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33218. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33219. temp = [];
  33220. for (index = 0; index < data.length; index += 3) {
  33221. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33222. }
  33223. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33224. }
  33225. // flip faces?
  33226. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33227. this.flipFaces();
  33228. }
  33229. // Restore submeshes
  33230. this.releaseSubMeshes();
  33231. this.subMeshes = submeshes;
  33232. return this;
  33233. };
  33234. /**
  33235. * Modifies the mesh geometry according to its own current World Matrix.
  33236. * The mesh World Matrix is then reset.
  33237. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33238. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33239. * @see http://doc.babylonjs.com/resources/baking_transformations
  33240. * @returns the current mesh
  33241. */
  33242. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33243. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33244. this.scaling.copyFromFloats(1, 1, 1);
  33245. this.position.copyFromFloats(0, 0, 0);
  33246. this.rotation.copyFromFloats(0, 0, 0);
  33247. //only if quaternion is already set
  33248. if (this.rotationQuaternion) {
  33249. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33250. }
  33251. this._worldMatrix = BABYLON.Matrix.Identity();
  33252. return this;
  33253. };
  33254. Object.defineProperty(Mesh.prototype, "_positions", {
  33255. // Cache
  33256. /** @hidden */
  33257. get: function () {
  33258. if (this._geometry) {
  33259. return this._geometry._positions;
  33260. }
  33261. return null;
  33262. },
  33263. enumerable: true,
  33264. configurable: true
  33265. });
  33266. /** @hidden */
  33267. Mesh.prototype._resetPointsArrayCache = function () {
  33268. if (this._geometry) {
  33269. this._geometry._resetPointsArrayCache();
  33270. }
  33271. return this;
  33272. };
  33273. /** @hidden */
  33274. Mesh.prototype._generatePointsArray = function () {
  33275. if (this._geometry) {
  33276. return this._geometry._generatePointsArray();
  33277. }
  33278. return false;
  33279. };
  33280. /**
  33281. * Returns a new Mesh object generated from the current mesh properties.
  33282. * This method must not get confused with createInstance()
  33283. * @param name is a string, the name given to the new mesh
  33284. * @param newParent can be any Node object (default `null`)
  33285. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33286. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33287. * @returns a new mesh
  33288. */
  33289. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33290. if (name === void 0) { name = ""; }
  33291. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33292. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33293. };
  33294. /**
  33295. * Releases resources associated with this mesh.
  33296. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33297. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33298. */
  33299. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33300. var _this = this;
  33301. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33302. this.morphTargetManager = null;
  33303. if (this._geometry) {
  33304. this._geometry.releaseForMesh(this, true);
  33305. }
  33306. if (this._onBeforeDrawObservable) {
  33307. this._onBeforeDrawObservable.clear();
  33308. }
  33309. if (this._onBeforeRenderObservable) {
  33310. this._onBeforeRenderObservable.clear();
  33311. }
  33312. if (this._onAfterRenderObservable) {
  33313. this._onAfterRenderObservable.clear();
  33314. }
  33315. // Sources
  33316. var meshes = this.getScene().meshes;
  33317. meshes.forEach(function (abstractMesh) {
  33318. var mesh = abstractMesh;
  33319. if (mesh._source && mesh._source === _this) {
  33320. mesh._source = null;
  33321. }
  33322. });
  33323. this._source = null;
  33324. // Instances
  33325. if (this._instanceDataStorage.instancesBuffer) {
  33326. this._instanceDataStorage.instancesBuffer.dispose();
  33327. this._instanceDataStorage.instancesBuffer = null;
  33328. }
  33329. while (this.instances.length) {
  33330. this.instances[0].dispose();
  33331. }
  33332. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33333. };
  33334. /**
  33335. * Modifies the mesh geometry according to a displacement map.
  33336. * 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.
  33337. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33338. * @param url is a string, the URL from the image file is to be downloaded.
  33339. * @param minHeight is the lower limit of the displacement.
  33340. * @param maxHeight is the upper limit of the displacement.
  33341. * @param 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.
  33342. * @param uvOffset is an optional vector2 used to offset UV.
  33343. * @param uvScale is an optional vector2 used to scale UV.
  33344. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  33345. * @returns the Mesh.
  33346. */
  33347. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33348. var _this = this;
  33349. if (forceUpdate === void 0) { forceUpdate = false; }
  33350. var scene = this.getScene();
  33351. var onload = function (img) {
  33352. // Getting height map data
  33353. var canvas = document.createElement("canvas");
  33354. var context = canvas.getContext("2d");
  33355. var heightMapWidth = img.width;
  33356. var heightMapHeight = img.height;
  33357. canvas.width = heightMapWidth;
  33358. canvas.height = heightMapHeight;
  33359. context.drawImage(img, 0, 0);
  33360. // Create VertexData from map data
  33361. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33362. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33363. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33364. //execute success callback, if set
  33365. if (onSuccess) {
  33366. onSuccess(_this);
  33367. }
  33368. };
  33369. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33370. return this;
  33371. };
  33372. /**
  33373. * Modifies the mesh geometry according to a displacementMap buffer.
  33374. * 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.
  33375. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33376. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33377. * @param heightMapWidth is the width of the buffer image.
  33378. * @param heightMapHeight is the height of the buffer image.
  33379. * @param minHeight is the lower limit of the displacement.
  33380. * @param maxHeight is the upper limit of the displacement.
  33381. * @param 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.
  33382. * @param uvOffset is an optional vector2 used to offset UV.
  33383. * @param uvScale is an optional vector2 used to scale UV.
  33384. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  33385. * @returns the Mesh.
  33386. */
  33387. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33388. if (forceUpdate === void 0) { forceUpdate = false; }
  33389. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33390. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33391. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33392. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33393. return this;
  33394. }
  33395. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33396. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33397. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33398. var position = BABYLON.Vector3.Zero();
  33399. var normal = BABYLON.Vector3.Zero();
  33400. var uv = BABYLON.Vector2.Zero();
  33401. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33402. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33403. for (var index = 0; index < positions.length; index += 3) {
  33404. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33405. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33406. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33407. // Compute height
  33408. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33409. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33410. var pos = (u + v * heightMapWidth) * 4;
  33411. var r = buffer[pos] / 255.0;
  33412. var g = buffer[pos + 1] / 255.0;
  33413. var b = buffer[pos + 2] / 255.0;
  33414. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33415. normal.normalize();
  33416. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33417. position = position.add(normal);
  33418. position.toArray(positions, index);
  33419. }
  33420. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33421. if (forceUpdate) {
  33422. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33423. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33424. }
  33425. else {
  33426. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33427. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33428. }
  33429. return this;
  33430. };
  33431. /**
  33432. * Modify the mesh to get a flat shading rendering.
  33433. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33434. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33435. * @returns current mesh
  33436. */
  33437. Mesh.prototype.convertToFlatShadedMesh = function () {
  33438. var kinds = this.getVerticesDataKinds();
  33439. var vbs = {};
  33440. var data = {};
  33441. var newdata = {};
  33442. var updatableNormals = false;
  33443. var kindIndex;
  33444. var kind;
  33445. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33446. kind = kinds[kindIndex];
  33447. var vertexBuffer = this.getVertexBuffer(kind);
  33448. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33449. updatableNormals = vertexBuffer.isUpdatable();
  33450. kinds.splice(kindIndex, 1);
  33451. kindIndex--;
  33452. continue;
  33453. }
  33454. vbs[kind] = vertexBuffer;
  33455. data[kind] = vbs[kind].getData();
  33456. newdata[kind] = [];
  33457. }
  33458. // Save previous submeshes
  33459. var previousSubmeshes = this.subMeshes.slice(0);
  33460. var indices = this.getIndices();
  33461. var totalIndices = this.getTotalIndices();
  33462. // Generating unique vertices per face
  33463. var index;
  33464. for (index = 0; index < totalIndices; index++) {
  33465. var vertexIndex = indices[index];
  33466. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33467. kind = kinds[kindIndex];
  33468. var stride = vbs[kind].getStrideSize();
  33469. for (var offset = 0; offset < stride; offset++) {
  33470. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33471. }
  33472. }
  33473. }
  33474. // Updating faces & normal
  33475. var normals = [];
  33476. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33477. for (index = 0; index < totalIndices; index += 3) {
  33478. indices[index] = index;
  33479. indices[index + 1] = index + 1;
  33480. indices[index + 2] = index + 2;
  33481. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33482. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33483. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33484. var p1p2 = p1.subtract(p2);
  33485. var p3p2 = p3.subtract(p2);
  33486. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33487. // Store same normals for every vertex
  33488. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33489. normals.push(normal.x);
  33490. normals.push(normal.y);
  33491. normals.push(normal.z);
  33492. }
  33493. }
  33494. this.setIndices(indices);
  33495. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33496. // Updating vertex buffers
  33497. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33498. kind = kinds[kindIndex];
  33499. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33500. }
  33501. // Updating submeshes
  33502. this.releaseSubMeshes();
  33503. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33504. var previousOne = previousSubmeshes[submeshIndex];
  33505. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33506. }
  33507. this.synchronizeInstances();
  33508. return this;
  33509. };
  33510. /**
  33511. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33512. * In other words, more vertices, no more indices and a single bigger VBO.
  33513. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33514. * @returns current mesh
  33515. */
  33516. Mesh.prototype.convertToUnIndexedMesh = function () {
  33517. var kinds = this.getVerticesDataKinds();
  33518. var vbs = {};
  33519. var data = {};
  33520. var newdata = {};
  33521. var kindIndex;
  33522. var kind;
  33523. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33524. kind = kinds[kindIndex];
  33525. var vertexBuffer = this.getVertexBuffer(kind);
  33526. vbs[kind] = vertexBuffer;
  33527. data[kind] = vbs[kind].getData();
  33528. newdata[kind] = [];
  33529. }
  33530. // Save previous submeshes
  33531. var previousSubmeshes = this.subMeshes.slice(0);
  33532. var indices = this.getIndices();
  33533. var totalIndices = this.getTotalIndices();
  33534. // Generating unique vertices per face
  33535. var index;
  33536. for (index = 0; index < totalIndices; index++) {
  33537. var vertexIndex = indices[index];
  33538. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33539. kind = kinds[kindIndex];
  33540. var stride = vbs[kind].getStrideSize();
  33541. for (var offset = 0; offset < stride; offset++) {
  33542. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33543. }
  33544. }
  33545. }
  33546. // Updating indices
  33547. for (index = 0; index < totalIndices; index += 3) {
  33548. indices[index] = index;
  33549. indices[index + 1] = index + 1;
  33550. indices[index + 2] = index + 2;
  33551. }
  33552. this.setIndices(indices);
  33553. // Updating vertex buffers
  33554. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33555. kind = kinds[kindIndex];
  33556. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33557. }
  33558. // Updating submeshes
  33559. this.releaseSubMeshes();
  33560. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33561. var previousOne = previousSubmeshes[submeshIndex];
  33562. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33563. }
  33564. this._unIndexed = true;
  33565. this.synchronizeInstances();
  33566. return this;
  33567. };
  33568. /**
  33569. * Inverses facet orientations.
  33570. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33571. * @param flipNormals will also inverts the normals
  33572. * @returns current mesh
  33573. */
  33574. Mesh.prototype.flipFaces = function (flipNormals) {
  33575. if (flipNormals === void 0) { flipNormals = false; }
  33576. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33577. var i;
  33578. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33579. for (i = 0; i < vertex_data.normals.length; i++) {
  33580. vertex_data.normals[i] *= -1;
  33581. }
  33582. }
  33583. if (vertex_data.indices) {
  33584. var temp;
  33585. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33586. // reassign indices
  33587. temp = vertex_data.indices[i + 1];
  33588. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33589. vertex_data.indices[i + 2] = temp;
  33590. }
  33591. }
  33592. vertex_data.applyToMesh(this);
  33593. return this;
  33594. };
  33595. // Instances
  33596. /**
  33597. * Creates a new InstancedMesh object from the mesh model.
  33598. * Warning : this method is not supported for Line mesh and LineSystem
  33599. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33600. * @param name defines the name of the new instance
  33601. * @returns a new InstancedMesh
  33602. */
  33603. Mesh.prototype.createInstance = function (name) {
  33604. return new BABYLON.InstancedMesh(name, this);
  33605. };
  33606. /**
  33607. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33608. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33609. * @returns the current mesh
  33610. */
  33611. Mesh.prototype.synchronizeInstances = function () {
  33612. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33613. var instance = this.instances[instanceIndex];
  33614. instance._syncSubMeshes();
  33615. }
  33616. return this;
  33617. };
  33618. /**
  33619. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33620. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33621. * This should be used together with the simplification to avoid disappearing triangles.
  33622. * @param successCallback an optional success callback to be called after the optimization finished.
  33623. * @returns the current mesh
  33624. */
  33625. Mesh.prototype.optimizeIndices = function (successCallback) {
  33626. var _this = this;
  33627. var indices = this.getIndices();
  33628. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33629. if (!positions || !indices) {
  33630. return this;
  33631. }
  33632. var vectorPositions = new Array();
  33633. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33634. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33635. }
  33636. var dupes = new Array();
  33637. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33638. var realPos = vectorPositions.length - 1 - iteration;
  33639. var testedPosition = vectorPositions[realPos];
  33640. for (var j = 0; j < realPos; ++j) {
  33641. var againstPosition = vectorPositions[j];
  33642. if (testedPosition.equals(againstPosition)) {
  33643. dupes[realPos] = j;
  33644. break;
  33645. }
  33646. }
  33647. }, function () {
  33648. for (var i = 0; i < indices.length; ++i) {
  33649. indices[i] = dupes[indices[i]] || indices[i];
  33650. }
  33651. //indices are now reordered
  33652. var originalSubMeshes = _this.subMeshes.slice(0);
  33653. _this.setIndices(indices);
  33654. _this.subMeshes = originalSubMeshes;
  33655. if (successCallback) {
  33656. successCallback(_this);
  33657. }
  33658. });
  33659. return this;
  33660. };
  33661. /**
  33662. * Serialize current mesh
  33663. * @param serializationObject defines the object which will receive the serialization data
  33664. */
  33665. Mesh.prototype.serialize = function (serializationObject) {
  33666. serializationObject.name = this.name;
  33667. serializationObject.id = this.id;
  33668. serializationObject.type = this.getClassName();
  33669. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33670. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33671. }
  33672. serializationObject.position = this.position.asArray();
  33673. if (this.rotationQuaternion) {
  33674. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33675. }
  33676. else if (this.rotation) {
  33677. serializationObject.rotation = this.rotation.asArray();
  33678. }
  33679. serializationObject.scaling = this.scaling.asArray();
  33680. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33681. serializationObject.isEnabled = this.isEnabled(false);
  33682. serializationObject.isVisible = this.isVisible;
  33683. serializationObject.infiniteDistance = this.infiniteDistance;
  33684. serializationObject.pickable = this.isPickable;
  33685. serializationObject.receiveShadows = this.receiveShadows;
  33686. serializationObject.billboardMode = this.billboardMode;
  33687. serializationObject.visibility = this.visibility;
  33688. serializationObject.checkCollisions = this.checkCollisions;
  33689. serializationObject.isBlocker = this.isBlocker;
  33690. // Parent
  33691. if (this.parent) {
  33692. serializationObject.parentId = this.parent.id;
  33693. }
  33694. // Geometry
  33695. serializationObject.isUnIndexed = this.isUnIndexed;
  33696. var geometry = this._geometry;
  33697. if (geometry) {
  33698. var geometryId = geometry.id;
  33699. serializationObject.geometryId = geometryId;
  33700. // SubMeshes
  33701. serializationObject.subMeshes = [];
  33702. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33703. var subMesh = this.subMeshes[subIndex];
  33704. serializationObject.subMeshes.push({
  33705. materialIndex: subMesh.materialIndex,
  33706. verticesStart: subMesh.verticesStart,
  33707. verticesCount: subMesh.verticesCount,
  33708. indexStart: subMesh.indexStart,
  33709. indexCount: subMesh.indexCount
  33710. });
  33711. }
  33712. }
  33713. // Material
  33714. if (this.material) {
  33715. serializationObject.materialId = this.material.id;
  33716. }
  33717. else {
  33718. this.material = null;
  33719. }
  33720. // Morph targets
  33721. if (this.morphTargetManager) {
  33722. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33723. }
  33724. // Skeleton
  33725. if (this.skeleton) {
  33726. serializationObject.skeletonId = this.skeleton.id;
  33727. }
  33728. // Physics
  33729. //TODO implement correct serialization for physics impostors.
  33730. var impostor = this.getPhysicsImpostor();
  33731. if (impostor) {
  33732. serializationObject.physicsMass = impostor.getParam("mass");
  33733. serializationObject.physicsFriction = impostor.getParam("friction");
  33734. serializationObject.physicsRestitution = impostor.getParam("mass");
  33735. serializationObject.physicsImpostor = impostor.type;
  33736. }
  33737. // Metadata
  33738. if (this.metadata) {
  33739. serializationObject.metadata = this.metadata;
  33740. }
  33741. // Instances
  33742. serializationObject.instances = [];
  33743. for (var index = 0; index < this.instances.length; index++) {
  33744. var instance = this.instances[index];
  33745. if (instance.doNotSerialize) {
  33746. continue;
  33747. }
  33748. var serializationInstance = {
  33749. name: instance.name,
  33750. id: instance.id,
  33751. position: instance.position.asArray(),
  33752. scaling: instance.scaling.asArray()
  33753. };
  33754. if (instance.parent) {
  33755. serializationInstance.parentId = instance.parent.id;
  33756. }
  33757. if (instance.rotationQuaternion) {
  33758. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33759. }
  33760. else if (instance.rotation) {
  33761. serializationInstance.rotation = instance.rotation.asArray();
  33762. }
  33763. serializationObject.instances.push(serializationInstance);
  33764. // Animations
  33765. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33766. serializationInstance.ranges = instance.serializeAnimationRanges();
  33767. }
  33768. //
  33769. // Animations
  33770. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33771. serializationObject.ranges = this.serializeAnimationRanges();
  33772. // Layer mask
  33773. serializationObject.layerMask = this.layerMask;
  33774. // Alpha
  33775. serializationObject.alphaIndex = this.alphaIndex;
  33776. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33777. // Overlay
  33778. serializationObject.overlayAlpha = this.overlayAlpha;
  33779. serializationObject.overlayColor = this.overlayColor.asArray();
  33780. serializationObject.renderOverlay = this.renderOverlay;
  33781. // Fog
  33782. serializationObject.applyFog = this.applyFog;
  33783. // Action Manager
  33784. if (this.actionManager) {
  33785. serializationObject.actions = this.actionManager.serialize(this.name);
  33786. }
  33787. };
  33788. /** @hidden */
  33789. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33790. if (!this.geometry) {
  33791. return;
  33792. }
  33793. this._markSubMeshesAsAttributesDirty();
  33794. var morphTargetManager = this._morphTargetManager;
  33795. if (morphTargetManager && morphTargetManager.vertexCount) {
  33796. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33797. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33798. this.morphTargetManager = null;
  33799. return;
  33800. }
  33801. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33802. var morphTarget = morphTargetManager.getActiveTarget(index);
  33803. var positions = morphTarget.getPositions();
  33804. if (!positions) {
  33805. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33806. return;
  33807. }
  33808. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33809. var normals = morphTarget.getNormals();
  33810. if (normals) {
  33811. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33812. }
  33813. var tangents = morphTarget.getTangents();
  33814. if (tangents) {
  33815. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33816. }
  33817. }
  33818. }
  33819. else {
  33820. var index = 0;
  33821. // Positions
  33822. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33823. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33824. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33825. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33826. }
  33827. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33828. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33829. }
  33830. index++;
  33831. }
  33832. }
  33833. };
  33834. // Statics
  33835. /**
  33836. * Returns a new Mesh object parsed from the source provided.
  33837. * @param parsedMesh is the source
  33838. * @param scene defines the hosting scene
  33839. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33840. * @returns a new Mesh
  33841. */
  33842. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33843. var mesh;
  33844. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33845. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33846. }
  33847. else {
  33848. mesh = new Mesh(parsedMesh.name, scene);
  33849. }
  33850. mesh.id = parsedMesh.id;
  33851. if (BABYLON.Tags) {
  33852. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33853. }
  33854. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33855. if (parsedMesh.metadata !== undefined) {
  33856. mesh.metadata = parsedMesh.metadata;
  33857. }
  33858. if (parsedMesh.rotationQuaternion) {
  33859. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33860. }
  33861. else if (parsedMesh.rotation) {
  33862. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33863. }
  33864. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33865. if (parsedMesh.localMatrix) {
  33866. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33867. }
  33868. else if (parsedMesh.pivotMatrix) {
  33869. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33870. }
  33871. mesh.setEnabled(parsedMesh.isEnabled);
  33872. mesh.isVisible = parsedMesh.isVisible;
  33873. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33874. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33875. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33876. if (parsedMesh.applyFog !== undefined) {
  33877. mesh.applyFog = parsedMesh.applyFog;
  33878. }
  33879. if (parsedMesh.pickable !== undefined) {
  33880. mesh.isPickable = parsedMesh.pickable;
  33881. }
  33882. if (parsedMesh.alphaIndex !== undefined) {
  33883. mesh.alphaIndex = parsedMesh.alphaIndex;
  33884. }
  33885. mesh.receiveShadows = parsedMesh.receiveShadows;
  33886. mesh.billboardMode = parsedMesh.billboardMode;
  33887. if (parsedMesh.visibility !== undefined) {
  33888. mesh.visibility = parsedMesh.visibility;
  33889. }
  33890. mesh.checkCollisions = parsedMesh.checkCollisions;
  33891. if (parsedMesh.isBlocker !== undefined) {
  33892. mesh.isBlocker = parsedMesh.isBlocker;
  33893. }
  33894. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33895. // freezeWorldMatrix
  33896. if (parsedMesh.freezeWorldMatrix) {
  33897. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33898. }
  33899. // Parent
  33900. if (parsedMesh.parentId) {
  33901. mesh._waitingParentId = parsedMesh.parentId;
  33902. }
  33903. // Actions
  33904. if (parsedMesh.actions !== undefined) {
  33905. mesh._waitingActions = parsedMesh.actions;
  33906. }
  33907. // Overlay
  33908. if (parsedMesh.overlayAlpha !== undefined) {
  33909. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33910. }
  33911. if (parsedMesh.overlayColor !== undefined) {
  33912. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33913. }
  33914. if (parsedMesh.renderOverlay !== undefined) {
  33915. mesh.renderOverlay = parsedMesh.renderOverlay;
  33916. }
  33917. // Geometry
  33918. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33919. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33920. if (parsedMesh.delayLoadingFile) {
  33921. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33922. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33923. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33924. if (parsedMesh._binaryInfo) {
  33925. mesh._binaryInfo = parsedMesh._binaryInfo;
  33926. }
  33927. mesh._delayInfo = [];
  33928. if (parsedMesh.hasUVs) {
  33929. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33930. }
  33931. if (parsedMesh.hasUVs2) {
  33932. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33933. }
  33934. if (parsedMesh.hasUVs3) {
  33935. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33936. }
  33937. if (parsedMesh.hasUVs4) {
  33938. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33939. }
  33940. if (parsedMesh.hasUVs5) {
  33941. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33942. }
  33943. if (parsedMesh.hasUVs6) {
  33944. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33945. }
  33946. if (parsedMesh.hasColors) {
  33947. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33948. }
  33949. if (parsedMesh.hasMatricesIndices) {
  33950. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33951. }
  33952. if (parsedMesh.hasMatricesWeights) {
  33953. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33954. }
  33955. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33956. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33957. mesh._checkDelayState();
  33958. }
  33959. }
  33960. else {
  33961. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33962. }
  33963. // Material
  33964. if (parsedMesh.materialId) {
  33965. mesh.setMaterialByID(parsedMesh.materialId);
  33966. }
  33967. else {
  33968. mesh.material = null;
  33969. }
  33970. // Morph targets
  33971. if (parsedMesh.morphTargetManagerId > -1) {
  33972. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33973. }
  33974. // Skeleton
  33975. if (parsedMesh.skeletonId > -1) {
  33976. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33977. if (parsedMesh.numBoneInfluencers) {
  33978. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33979. }
  33980. }
  33981. // Animations
  33982. if (parsedMesh.animations) {
  33983. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33984. var parsedAnimation = parsedMesh.animations[animationIndex];
  33985. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33986. }
  33987. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33988. }
  33989. if (parsedMesh.autoAnimate) {
  33990. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33991. }
  33992. // Layer Mask
  33993. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33994. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33995. }
  33996. else {
  33997. mesh.layerMask = 0x0FFFFFFF;
  33998. }
  33999. // Physics
  34000. if (parsedMesh.physicsImpostor) {
  34001. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34002. mass: parsedMesh.physicsMass,
  34003. friction: parsedMesh.physicsFriction,
  34004. restitution: parsedMesh.physicsRestitution
  34005. }, scene);
  34006. }
  34007. // Instances
  34008. if (parsedMesh.instances) {
  34009. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34010. var parsedInstance = parsedMesh.instances[index];
  34011. var instance = mesh.createInstance(parsedInstance.name);
  34012. if (parsedInstance.id) {
  34013. instance.id = parsedInstance.id;
  34014. }
  34015. if (BABYLON.Tags) {
  34016. if (parsedInstance.tags) {
  34017. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34018. }
  34019. else {
  34020. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34021. }
  34022. }
  34023. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34024. if (parsedInstance.parentId) {
  34025. instance._waitingParentId = parsedInstance.parentId;
  34026. }
  34027. if (parsedInstance.rotationQuaternion) {
  34028. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34029. }
  34030. else if (parsedInstance.rotation) {
  34031. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34032. }
  34033. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34034. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34035. instance.checkCollisions = parsedInstance.checkCollisions;
  34036. }
  34037. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34038. instance.isPickable = parsedInstance.pickable;
  34039. }
  34040. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34041. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34042. }
  34043. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34044. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34045. }
  34046. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34047. instance.alphaIndex = parsedInstance.alphaIndex;
  34048. }
  34049. // Physics
  34050. if (parsedInstance.physicsImpostor) {
  34051. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34052. mass: parsedInstance.physicsMass,
  34053. friction: parsedInstance.physicsFriction,
  34054. restitution: parsedInstance.physicsRestitution
  34055. }, scene);
  34056. }
  34057. // Animation
  34058. if (parsedInstance.animations) {
  34059. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34060. parsedAnimation = parsedInstance.animations[animationIndex];
  34061. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34062. }
  34063. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34064. if (parsedInstance.autoAnimate) {
  34065. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34066. }
  34067. }
  34068. }
  34069. }
  34070. return mesh;
  34071. };
  34072. /**
  34073. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34074. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34075. * @param name defines the name of the mesh to create
  34076. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34077. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34078. * @param closePath creates a seam between the first and the last points of each path of the path array
  34079. * @param offset is taken in account only if the `pathArray` is containing a single path
  34080. * @param scene defines the hosting scene
  34081. * @param updatable defines if the mesh must be flagged as updatable
  34082. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34083. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  34084. * @returns a new Mesh
  34085. */
  34086. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34087. if (closeArray === void 0) { closeArray = false; }
  34088. if (updatable === void 0) { updatable = false; }
  34089. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34090. pathArray: pathArray,
  34091. closeArray: closeArray,
  34092. closePath: closePath,
  34093. offset: offset,
  34094. updatable: updatable,
  34095. sideOrientation: sideOrientation,
  34096. instance: instance
  34097. }, scene);
  34098. };
  34099. /**
  34100. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34101. * @param name defines the name of the mesh to create
  34102. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34103. * @param 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
  34104. * @param scene defines the hosting scene
  34105. * @param updatable defines if the mesh must be flagged as updatable
  34106. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34107. * @returns a new Mesh
  34108. */
  34109. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34110. if (scene === void 0) { scene = null; }
  34111. var options = {
  34112. radius: radius,
  34113. tessellation: tessellation,
  34114. sideOrientation: sideOrientation,
  34115. updatable: updatable
  34116. };
  34117. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34118. };
  34119. /**
  34120. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34121. * @param name defines the name of the mesh to create
  34122. * @param size sets the size (float) of each box side (default 1)
  34123. * @param scene defines the hosting scene
  34124. * @param updatable defines if the mesh must be flagged as updatable
  34125. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34126. * @returns a new Mesh
  34127. */
  34128. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34129. if (scene === void 0) { scene = null; }
  34130. var options = {
  34131. size: size,
  34132. sideOrientation: sideOrientation,
  34133. updatable: updatable
  34134. };
  34135. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34136. };
  34137. /**
  34138. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34139. * @param name defines the name of the mesh to create
  34140. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34141. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34142. * @param scene defines the hosting scene
  34143. * @param updatable defines if the mesh must be flagged as updatable
  34144. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34145. * @returns a new Mesh
  34146. */
  34147. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34148. var options = {
  34149. segments: segments,
  34150. diameterX: diameter,
  34151. diameterY: diameter,
  34152. diameterZ: diameter,
  34153. sideOrientation: sideOrientation,
  34154. updatable: updatable
  34155. };
  34156. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34157. };
  34158. /**
  34159. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34160. * @param name defines the name of the mesh to create
  34161. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34162. * @param diameterTop set the top cap diameter (floats, default 1)
  34163. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34164. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34165. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34166. * @param scene defines the hosting scene
  34167. * @param updatable defines if the mesh must be flagged as updatable
  34168. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34169. * @returns a new Mesh
  34170. */
  34171. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34172. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34173. if (scene !== undefined) {
  34174. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34175. updatable = scene;
  34176. }
  34177. scene = subdivisions;
  34178. subdivisions = 1;
  34179. }
  34180. var options = {
  34181. height: height,
  34182. diameterTop: diameterTop,
  34183. diameterBottom: diameterBottom,
  34184. tessellation: tessellation,
  34185. subdivisions: subdivisions,
  34186. sideOrientation: sideOrientation,
  34187. updatable: updatable
  34188. };
  34189. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34190. };
  34191. // Torus (Code from SharpDX.org)
  34192. /**
  34193. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34194. * @param name defines the name of the mesh to create
  34195. * @param diameter sets the diameter size (float) of the torus (default 1)
  34196. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34197. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34198. * @param scene defines the hosting scene
  34199. * @param updatable defines if the mesh must be flagged as updatable
  34200. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34201. * @returns a new Mesh
  34202. */
  34203. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34204. var options = {
  34205. diameter: diameter,
  34206. thickness: thickness,
  34207. tessellation: tessellation,
  34208. sideOrientation: sideOrientation,
  34209. updatable: updatable
  34210. };
  34211. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34212. };
  34213. /**
  34214. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34215. * @param name defines the name of the mesh to create
  34216. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34217. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34218. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34219. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34220. * @param p the number of windings on X axis (positive integers, default 2)
  34221. * @param q the number of windings on Y axis (positive integers, default 3)
  34222. * @param scene defines the hosting scene
  34223. * @param updatable defines if the mesh must be flagged as updatable
  34224. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34225. * @returns a new Mesh
  34226. */
  34227. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34228. var options = {
  34229. radius: radius,
  34230. tube: tube,
  34231. radialSegments: radialSegments,
  34232. tubularSegments: tubularSegments,
  34233. p: p,
  34234. q: q,
  34235. sideOrientation: sideOrientation,
  34236. updatable: updatable
  34237. };
  34238. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34239. };
  34240. /**
  34241. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34242. * @param name defines the name of the mesh to create
  34243. * @param points is an array successive Vector3
  34244. * @param scene defines the hosting scene
  34245. * @param updatable defines if the mesh must be flagged as updatable
  34246. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  34247. * @returns a new Mesh
  34248. */
  34249. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34250. if (scene === void 0) { scene = null; }
  34251. if (updatable === void 0) { updatable = false; }
  34252. if (instance === void 0) { instance = null; }
  34253. var options = {
  34254. points: points,
  34255. updatable: updatable,
  34256. instance: instance
  34257. };
  34258. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34259. };
  34260. /**
  34261. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34262. * @param name defines the name of the mesh to create
  34263. * @param points is an array successive Vector3
  34264. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34265. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34266. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34267. * @param scene defines the hosting scene
  34268. * @param updatable defines if the mesh must be flagged as updatable
  34269. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  34270. * @returns a new Mesh
  34271. */
  34272. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34273. if (scene === void 0) { scene = null; }
  34274. var options = {
  34275. points: points,
  34276. dashSize: dashSize,
  34277. gapSize: gapSize,
  34278. dashNb: dashNb,
  34279. updatable: updatable,
  34280. instance: instance
  34281. };
  34282. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34283. };
  34284. /**
  34285. * Creates a polygon mesh.
  34286. * Please consider using the same method from the MeshBuilder class instead.
  34287. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34288. * 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.
  34289. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34291. * Remember you can only change the shape positions, not their number when updating a polygon.
  34292. */
  34293. /**
  34294. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34295. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34296. * @param name defines the name of the mesh to create
  34297. * @param 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
  34298. * @param scene defines the hosting scene
  34299. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34300. * @param updatable defines if the mesh must be flagged as updatable
  34301. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34302. * @returns a new Mesh
  34303. */
  34304. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34305. var options = {
  34306. shape: shape,
  34307. holes: holes,
  34308. updatable: updatable,
  34309. sideOrientation: sideOrientation
  34310. };
  34311. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34312. };
  34313. /**
  34314. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34315. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34316. * @param name defines the name of the mesh to create
  34317. * @param 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
  34318. * @param depth defines the height of extrusion
  34319. * @param scene defines the hosting scene
  34320. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34321. * @param updatable defines if the mesh must be flagged as updatable
  34322. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34323. * @returns a new Mesh
  34324. */
  34325. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34326. var options = {
  34327. shape: shape,
  34328. holes: holes,
  34329. depth: depth,
  34330. updatable: updatable,
  34331. sideOrientation: sideOrientation
  34332. };
  34333. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34334. };
  34335. /**
  34336. * Creates an extruded shape mesh.
  34337. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  34338. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34339. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34340. * @param name defines the name of the mesh to create
  34341. * @param 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
  34342. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34343. * @param scale is the value to scale the shape
  34344. * @param rotation 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
  34345. * @param 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
  34346. * @param scene defines the hosting scene
  34347. * @param updatable defines if the mesh must be flagged as updatable
  34348. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34349. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  34350. * @returns a new Mesh
  34351. */
  34352. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34353. if (scene === void 0) { scene = null; }
  34354. var options = {
  34355. shape: shape,
  34356. path: path,
  34357. scale: scale,
  34358. rotation: rotation,
  34359. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34360. sideOrientation: sideOrientation,
  34361. instance: instance,
  34362. updatable: updatable
  34363. };
  34364. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34365. };
  34366. /**
  34367. * Creates an custom extruded shape mesh.
  34368. * The custom extrusion is a parametric shape.
  34369. * It has no predefined shape. Its final shape will depend on the input parameters.
  34370. * Please consider using the same method from the MeshBuilder class instead
  34371. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34372. * @param name defines the name of the mesh to create
  34373. * @param 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
  34374. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34375. * @param scaleFunction is a custom Javascript function called on each path point
  34376. * @param rotationFunction is a custom Javascript function called on each path point
  34377. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34378. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34379. * @param 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
  34380. * @param scene defines the hosting scene
  34381. * @param updatable defines if the mesh must be flagged as updatable
  34382. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34383. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  34384. * @returns a new Mesh
  34385. */
  34386. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34387. var options = {
  34388. shape: shape,
  34389. path: path,
  34390. scaleFunction: scaleFunction,
  34391. rotationFunction: rotationFunction,
  34392. ribbonCloseArray: ribbonCloseArray,
  34393. ribbonClosePath: ribbonClosePath,
  34394. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34395. sideOrientation: sideOrientation,
  34396. instance: instance,
  34397. updatable: updatable
  34398. };
  34399. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34400. };
  34401. /**
  34402. * Creates lathe mesh.
  34403. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34404. * Please consider using the same method from the MeshBuilder class instead
  34405. * @param name defines the name of the mesh to create
  34406. * @param 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
  34407. * @param radius is the radius value of the lathe
  34408. * @param tessellation is the side number of the lathe.
  34409. * @param scene defines the hosting scene
  34410. * @param updatable defines if the mesh must be flagged as updatable
  34411. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34412. * @returns a new Mesh
  34413. */
  34414. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34415. var options = {
  34416. shape: shape,
  34417. radius: radius,
  34418. tessellation: tessellation,
  34419. sideOrientation: sideOrientation,
  34420. updatable: updatable
  34421. };
  34422. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34423. };
  34424. /**
  34425. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34426. * @param name defines the name of the mesh to create
  34427. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34428. * @param scene defines the hosting scene
  34429. * @param updatable defines if the mesh must be flagged as updatable
  34430. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34431. * @returns a new Mesh
  34432. */
  34433. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34434. var options = {
  34435. size: size,
  34436. width: size,
  34437. height: size,
  34438. sideOrientation: sideOrientation,
  34439. updatable: updatable
  34440. };
  34441. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34442. };
  34443. /**
  34444. * Creates a ground mesh.
  34445. * Please consider using the same method from the MeshBuilder class instead
  34446. * @param name defines the name of the mesh to create
  34447. * @param width set the width of the ground
  34448. * @param height set the height of the ground
  34449. * @param subdivisions sets the number of subdivisions per side
  34450. * @param scene defines the hosting scene
  34451. * @param updatable defines if the mesh must be flagged as updatable
  34452. * @returns a new Mesh
  34453. */
  34454. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34455. var options = {
  34456. width: width,
  34457. height: height,
  34458. subdivisions: subdivisions,
  34459. updatable: updatable
  34460. };
  34461. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34462. };
  34463. /**
  34464. * Creates a tiled ground mesh.
  34465. * Please consider using the same method from the MeshBuilder class instead
  34466. * @param name defines the name of the mesh to create
  34467. * @param xmin set the ground minimum X coordinate
  34468. * @param zmin set the ground minimum Y coordinate
  34469. * @param xmax set the ground maximum X coordinate
  34470. * @param zmax set the ground maximum Z coordinate
  34471. * @param subdivisions is an 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
  34472. * @param precision is an 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
  34473. * @param scene defines the hosting scene
  34474. * @param updatable defines if the mesh must be flagged as updatable
  34475. * @returns a new Mesh
  34476. */
  34477. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34478. var options = {
  34479. xmin: xmin,
  34480. zmin: zmin,
  34481. xmax: xmax,
  34482. zmax: zmax,
  34483. subdivisions: subdivisions,
  34484. precision: precision,
  34485. updatable: updatable
  34486. };
  34487. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34488. };
  34489. /**
  34490. * Creates a ground mesh from a height map.
  34491. * Please consider using the same method from the MeshBuilder class instead
  34492. * @see http://doc.babylonjs.com/babylon101/height_map
  34493. * @param name defines the name of the mesh to create
  34494. * @param url sets the URL of the height map image resource
  34495. * @param width set the ground width size
  34496. * @param height set the ground height size
  34497. * @param subdivisions sets the number of subdivision per side
  34498. * @param minHeight is the minimum altitude on the ground
  34499. * @param maxHeight is the maximum altitude on the ground
  34500. * @param scene defines the hosting scene
  34501. * @param updatable defines if the mesh must be flagged as updatable
  34502. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34503. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34504. * @returns a new Mesh
  34505. */
  34506. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34507. var options = {
  34508. width: width,
  34509. height: height,
  34510. subdivisions: subdivisions,
  34511. minHeight: minHeight,
  34512. maxHeight: maxHeight,
  34513. updatable: updatable,
  34514. onReady: onReady,
  34515. alphaFilter: alphaFilter
  34516. };
  34517. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34518. };
  34519. /**
  34520. * Creates a tube mesh.
  34521. * The tube is a parametric shape.
  34522. * It has no predefined shape. Its final shape will depend on the input parameters.
  34523. * Please consider using the same method from the MeshBuilder class instead
  34524. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34525. * @param name defines the name of the mesh to create
  34526. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34527. * @param radius sets the tube radius size
  34528. * @param tessellation is the number of sides on the tubular surface
  34529. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  34530. * @param 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
  34531. * @param scene defines the hosting scene
  34532. * @param updatable defines if the mesh must be flagged as updatable
  34533. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34534. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  34535. * @returns a new Mesh
  34536. */
  34537. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34538. var options = {
  34539. path: path,
  34540. radius: radius,
  34541. tessellation: tessellation,
  34542. radiusFunction: radiusFunction,
  34543. arc: 1,
  34544. cap: cap,
  34545. updatable: updatable,
  34546. sideOrientation: sideOrientation,
  34547. instance: instance
  34548. };
  34549. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34550. };
  34551. /**
  34552. * Creates a polyhedron mesh.
  34553. * Please consider using the same method from the MeshBuilder class instead.
  34554. * * 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
  34555. * * The parameter `size` (positive float, default 1) sets the polygon size
  34556. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34557. * * 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`
  34558. * * 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
  34559. * * 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)`)
  34560. * * 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
  34561. * * 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
  34562. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34563. * * 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
  34564. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34565. * @param name defines the name of the mesh to create
  34566. * @param options defines the options used to create the mesh
  34567. * @param scene defines the hosting scene
  34568. * @returns a new Mesh
  34569. */
  34570. Mesh.CreatePolyhedron = function (name, options, scene) {
  34571. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34572. };
  34573. /**
  34574. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34575. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34576. * * 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`)
  34577. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34578. * * 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
  34579. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34580. * * 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
  34581. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34582. * @param name defines the name of the mesh
  34583. * @param options defines the options used to create the mesh
  34584. * @param scene defines the hosting scene
  34585. * @returns a new Mesh
  34586. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  34587. */
  34588. Mesh.CreateIcoSphere = function (name, options, scene) {
  34589. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34590. };
  34591. /**
  34592. * Creates a decal mesh.
  34593. * Please consider using the same method from the MeshBuilder class instead.
  34594. * A decal is a mesh usually applied as a model onto the surface of another mesh
  34595. * @param name defines the name of the mesh
  34596. * @param sourceMesh defines the mesh receiving the decal
  34597. * @param position sets the position of the decal in world coordinates
  34598. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  34599. * @param size sets the decal scaling
  34600. * @param angle sets the angle to rotate the decal
  34601. * @returns a new Mesh
  34602. */
  34603. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34604. var options = {
  34605. position: position,
  34606. normal: normal,
  34607. size: size,
  34608. angle: angle
  34609. };
  34610. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34611. };
  34612. // Skeletons
  34613. /**
  34614. * Prepare internal position array for software CPU skinning
  34615. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  34616. */
  34617. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34618. if (!this._sourcePositions) {
  34619. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34620. if (!source) {
  34621. return this._sourcePositions;
  34622. }
  34623. this._sourcePositions = new Float32Array(source);
  34624. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34625. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34626. }
  34627. }
  34628. return this._sourcePositions;
  34629. };
  34630. /**
  34631. * Prepare internal normal array for software CPU skinning
  34632. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34633. */
  34634. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34635. if (!this._sourceNormals) {
  34636. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34637. if (!source) {
  34638. return this._sourceNormals;
  34639. }
  34640. this._sourceNormals = new Float32Array(source);
  34641. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34642. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34643. }
  34644. }
  34645. return this._sourceNormals;
  34646. };
  34647. /**
  34648. * Updates the vertex buffer by applying transformation from the bones
  34649. * @param skeleton defines the skeleton to apply to current mesh
  34650. * @returns the current mesh
  34651. */
  34652. Mesh.prototype.applySkeleton = function (skeleton) {
  34653. if (!this.geometry) {
  34654. return this;
  34655. }
  34656. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  34657. return this;
  34658. }
  34659. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  34660. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34661. return this;
  34662. }
  34663. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34664. return this;
  34665. }
  34666. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34667. return this;
  34668. }
  34669. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34670. return this;
  34671. }
  34672. if (!this._sourcePositions) {
  34673. var submeshes = this.subMeshes.slice();
  34674. this.setPositionsForCPUSkinning();
  34675. this.subMeshes = submeshes;
  34676. }
  34677. if (!this._sourceNormals) {
  34678. this.setNormalsForCPUSkinning();
  34679. }
  34680. // positionsData checks for not being Float32Array will only pass at most once
  34681. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34682. if (!positionsData) {
  34683. return this;
  34684. }
  34685. if (!(positionsData instanceof Float32Array)) {
  34686. positionsData = new Float32Array(positionsData);
  34687. }
  34688. // normalsData checks for not being Float32Array will only pass at most once
  34689. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34690. if (!normalsData) {
  34691. return this;
  34692. }
  34693. if (!(normalsData instanceof Float32Array)) {
  34694. normalsData = new Float32Array(normalsData);
  34695. }
  34696. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34697. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34698. if (!matricesWeightsData || !matricesIndicesData) {
  34699. return this;
  34700. }
  34701. var needExtras = this.numBoneInfluencers > 4;
  34702. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34703. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34704. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34705. var tempVector3 = BABYLON.Vector3.Zero();
  34706. var finalMatrix = new BABYLON.Matrix();
  34707. var tempMatrix = new BABYLON.Matrix();
  34708. var matWeightIdx = 0;
  34709. var inf;
  34710. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34711. var weight;
  34712. for (inf = 0; inf < 4; inf++) {
  34713. weight = matricesWeightsData[matWeightIdx + inf];
  34714. if (weight > 0) {
  34715. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34716. finalMatrix.addToSelf(tempMatrix);
  34717. }
  34718. }
  34719. if (needExtras) {
  34720. for (inf = 0; inf < 4; inf++) {
  34721. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34722. if (weight > 0) {
  34723. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34724. finalMatrix.addToSelf(tempMatrix);
  34725. }
  34726. }
  34727. }
  34728. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34729. tempVector3.toArray(positionsData, index);
  34730. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34731. tempVector3.toArray(normalsData, index);
  34732. finalMatrix.reset();
  34733. }
  34734. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34735. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34736. return this;
  34737. };
  34738. // Tools
  34739. /**
  34740. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  34741. * @param meshes defines the list of meshes to scan
  34742. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34743. */
  34744. Mesh.MinMax = function (meshes) {
  34745. var minVector = null;
  34746. var maxVector = null;
  34747. meshes.forEach(function (mesh, index, array) {
  34748. var boundingInfo = mesh.getBoundingInfo();
  34749. var boundingBox = boundingInfo.boundingBox;
  34750. if (!minVector || !maxVector) {
  34751. minVector = boundingBox.minimumWorld;
  34752. maxVector = boundingBox.maximumWorld;
  34753. }
  34754. else {
  34755. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34756. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34757. }
  34758. });
  34759. if (!minVector || !maxVector) {
  34760. return {
  34761. min: BABYLON.Vector3.Zero(),
  34762. max: BABYLON.Vector3.Zero()
  34763. };
  34764. }
  34765. return {
  34766. min: minVector,
  34767. max: maxVector
  34768. };
  34769. };
  34770. /**
  34771. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34772. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34773. * @returns a vector3
  34774. */
  34775. Mesh.Center = function (meshesOrMinMaxVector) {
  34776. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34777. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34778. };
  34779. /**
  34780. * Merge the array of meshes into a single mesh for performance reasons.
  34781. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34782. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34783. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34784. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34785. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34786. * @returns a new mesh
  34787. */
  34788. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34789. if (disposeSource === void 0) { disposeSource = true; }
  34790. var index;
  34791. if (!allow32BitsIndices) {
  34792. var totalVertices = 0;
  34793. // Counting vertices
  34794. for (index = 0; index < meshes.length; index++) {
  34795. if (meshes[index]) {
  34796. totalVertices += meshes[index].getTotalVertices();
  34797. if (totalVertices > 65536) {
  34798. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34799. return null;
  34800. }
  34801. }
  34802. }
  34803. }
  34804. // Merge
  34805. var vertexData = null;
  34806. var otherVertexData;
  34807. var indiceArray = new Array();
  34808. var source = null;
  34809. for (index = 0; index < meshes.length; index++) {
  34810. if (meshes[index]) {
  34811. var wm = meshes[index].computeWorldMatrix(true);
  34812. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34813. otherVertexData.transform(wm);
  34814. if (vertexData) {
  34815. vertexData.merge(otherVertexData, allow32BitsIndices);
  34816. }
  34817. else {
  34818. vertexData = otherVertexData;
  34819. source = meshes[index];
  34820. }
  34821. if (subdivideWithSubMeshes) {
  34822. indiceArray.push(meshes[index].getTotalIndices());
  34823. }
  34824. }
  34825. }
  34826. source = source;
  34827. if (!meshSubclass) {
  34828. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34829. }
  34830. vertexData.applyToMesh(meshSubclass);
  34831. // Setting properties
  34832. meshSubclass.material = source.material;
  34833. meshSubclass.checkCollisions = source.checkCollisions;
  34834. // Cleaning
  34835. if (disposeSource) {
  34836. for (index = 0; index < meshes.length; index++) {
  34837. if (meshes[index]) {
  34838. meshes[index].dispose();
  34839. }
  34840. }
  34841. }
  34842. // Subdivide
  34843. if (subdivideWithSubMeshes) {
  34844. //-- removal of global submesh
  34845. meshSubclass.releaseSubMeshes();
  34846. index = 0;
  34847. var offset = 0;
  34848. //-- apply subdivision according to index table
  34849. while (index < indiceArray.length) {
  34850. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34851. offset += indiceArray[index];
  34852. index++;
  34853. }
  34854. }
  34855. return meshSubclass;
  34856. };
  34857. // Consts
  34858. /**
  34859. * Mesh side orientation : usually the external or front surface
  34860. */
  34861. Mesh.FRONTSIDE = 0;
  34862. /**
  34863. * Mesh side orientation : usually the internal or back surface
  34864. */
  34865. Mesh.BACKSIDE = 1;
  34866. /**
  34867. * Mesh side orientation : both internal and external or front and back surfaces
  34868. */
  34869. Mesh.DOUBLESIDE = 2;
  34870. /**
  34871. * Mesh side orientation : by default, `FRONTSIDE`
  34872. */
  34873. Mesh.DEFAULTSIDE = 0;
  34874. /**
  34875. * Mesh cap setting : no cap
  34876. */
  34877. Mesh.NO_CAP = 0;
  34878. /**
  34879. * Mesh cap setting : one cap at the beginning of the mesh
  34880. */
  34881. Mesh.CAP_START = 1;
  34882. /**
  34883. * Mesh cap setting : one cap at the end of the mesh
  34884. */
  34885. Mesh.CAP_END = 2;
  34886. /**
  34887. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34888. */
  34889. Mesh.CAP_ALL = 3;
  34890. return Mesh;
  34891. }(BABYLON.AbstractMesh));
  34892. BABYLON.Mesh = Mesh;
  34893. })(BABYLON || (BABYLON = {}));
  34894. //# sourceMappingURL=babylon.mesh.js.map
  34895. var BABYLON;
  34896. (function (BABYLON) {
  34897. /**
  34898. * Base class for submeshes
  34899. */
  34900. var BaseSubMesh = /** @class */ (function () {
  34901. function BaseSubMesh() {
  34902. }
  34903. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34904. /**
  34905. * Gets associated effect
  34906. */
  34907. get: function () {
  34908. return this._materialEffect;
  34909. },
  34910. enumerable: true,
  34911. configurable: true
  34912. });
  34913. /**
  34914. * Sets associated effect (effect used to render this submesh)
  34915. * @param effect defines the effect to associate with
  34916. * @param defines defines the set of defines used to compile this effect
  34917. */
  34918. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34919. if (defines === void 0) { defines = null; }
  34920. if (this._materialEffect === effect) {
  34921. if (!effect) {
  34922. this._materialDefines = null;
  34923. }
  34924. return;
  34925. }
  34926. this._materialDefines = defines;
  34927. this._materialEffect = effect;
  34928. };
  34929. return BaseSubMesh;
  34930. }());
  34931. BABYLON.BaseSubMesh = BaseSubMesh;
  34932. /**
  34933. * Defines a subdivision inside a mesh
  34934. */
  34935. var SubMesh = /** @class */ (function (_super) {
  34936. __extends(SubMesh, _super);
  34937. /**
  34938. * Creates a new submesh
  34939. * @param materialIndex defines the material index to use
  34940. * @param verticesStart defines vertex index start
  34941. * @param verticesCount defines vertices count
  34942. * @param indexStart defines index start
  34943. * @param indexCount defines indices count
  34944. * @param mesh defines the parent mesh
  34945. * @param renderingMesh defines an optional rendering mesh
  34946. * @param createBoundingBox defines if bounding box should be created for this submesh
  34947. */
  34948. function SubMesh(
  34949. /** the material index to use */
  34950. materialIndex,
  34951. /** vertex index start */
  34952. verticesStart,
  34953. /** vertices count */
  34954. verticesCount,
  34955. /** index start */
  34956. indexStart,
  34957. /** indices count */
  34958. indexCount, mesh, renderingMesh, createBoundingBox) {
  34959. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34960. var _this = _super.call(this) || this;
  34961. _this.materialIndex = materialIndex;
  34962. _this.verticesStart = verticesStart;
  34963. _this.verticesCount = verticesCount;
  34964. _this.indexStart = indexStart;
  34965. _this.indexCount = indexCount;
  34966. /** @hidden */
  34967. _this._renderId = 0;
  34968. _this._mesh = mesh;
  34969. _this._renderingMesh = renderingMesh || mesh;
  34970. mesh.subMeshes.push(_this);
  34971. _this._trianglePlanes = [];
  34972. _this._id = mesh.subMeshes.length - 1;
  34973. if (createBoundingBox) {
  34974. _this.refreshBoundingInfo();
  34975. mesh.computeWorldMatrix(true);
  34976. }
  34977. return _this;
  34978. }
  34979. /**
  34980. * Add a new submesh to a mesh
  34981. * @param materialIndex defines the material index to use
  34982. * @param verticesStart defines vertex index start
  34983. * @param verticesCount defines vertices count
  34984. * @param indexStart defines index start
  34985. * @param indexCount defines indices count
  34986. * @param mesh defines the parent mesh
  34987. * @param renderingMesh defines an optional rendering mesh
  34988. * @param createBoundingBox defines if bounding box should be created for this submesh
  34989. * @returns the new submesh
  34990. */
  34991. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34992. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34993. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34994. };
  34995. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34996. /**
  34997. * Returns true if this submesh covers the entire parent mesh
  34998. * @ignorenaming
  34999. */
  35000. get: function () {
  35001. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35002. },
  35003. enumerable: true,
  35004. configurable: true
  35005. });
  35006. /**
  35007. * Returns the submesh BoudingInfo object
  35008. * @returns current bounding info (or mesh's one if the submesh is global)
  35009. */
  35010. SubMesh.prototype.getBoundingInfo = function () {
  35011. if (this.IsGlobal) {
  35012. return this._mesh.getBoundingInfo();
  35013. }
  35014. return this._boundingInfo;
  35015. };
  35016. /**
  35017. * Sets the submesh BoundingInfo
  35018. * @param boundingInfo defines the new bounding info to use
  35019. * @returns the SubMesh
  35020. */
  35021. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35022. this._boundingInfo = boundingInfo;
  35023. return this;
  35024. };
  35025. /**
  35026. * Returns the mesh of the current submesh
  35027. * @return the parent mesh
  35028. */
  35029. SubMesh.prototype.getMesh = function () {
  35030. return this._mesh;
  35031. };
  35032. /**
  35033. * Returns the rendering mesh of the submesh
  35034. * @returns the rendering mesh (could be different from parent mesh)
  35035. */
  35036. SubMesh.prototype.getRenderingMesh = function () {
  35037. return this._renderingMesh;
  35038. };
  35039. /**
  35040. * Returns the submesh material
  35041. * @returns null or the current material
  35042. */
  35043. SubMesh.prototype.getMaterial = function () {
  35044. var rootMaterial = this._renderingMesh.material;
  35045. if (rootMaterial === null || rootMaterial === undefined) {
  35046. return this._mesh.getScene().defaultMaterial;
  35047. }
  35048. else if (rootMaterial.getSubMaterial) {
  35049. var multiMaterial = rootMaterial;
  35050. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35051. if (this._currentMaterial !== effectiveMaterial) {
  35052. this._currentMaterial = effectiveMaterial;
  35053. this._materialDefines = null;
  35054. }
  35055. return effectiveMaterial;
  35056. }
  35057. return rootMaterial;
  35058. };
  35059. // Methods
  35060. /**
  35061. * Sets a new updated BoundingInfo object to the submesh
  35062. * @returns the SubMesh
  35063. */
  35064. SubMesh.prototype.refreshBoundingInfo = function () {
  35065. this._lastColliderWorldVertices = null;
  35066. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35067. return this;
  35068. }
  35069. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35070. if (!data) {
  35071. this._boundingInfo = this._mesh.getBoundingInfo();
  35072. return this;
  35073. }
  35074. var indices = this._renderingMesh.getIndices();
  35075. var extend;
  35076. //is this the only submesh?
  35077. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35078. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35079. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35080. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35081. }
  35082. else {
  35083. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35084. }
  35085. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35086. return this;
  35087. };
  35088. /** @hidden */
  35089. SubMesh.prototype._checkCollision = function (collider) {
  35090. var boundingInfo = this.getBoundingInfo();
  35091. return boundingInfo._checkCollision(collider);
  35092. };
  35093. /**
  35094. * Updates the submesh BoundingInfo
  35095. * @param world defines the world matrix to use to update the bounding info
  35096. * @returns the submesh
  35097. */
  35098. SubMesh.prototype.updateBoundingInfo = function (world) {
  35099. var boundingInfo = this.getBoundingInfo();
  35100. if (!boundingInfo) {
  35101. this.refreshBoundingInfo();
  35102. boundingInfo = this.getBoundingInfo();
  35103. }
  35104. boundingInfo.update(world);
  35105. return this;
  35106. };
  35107. /**
  35108. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35109. * @param frustumPlanes defines the frustum planes
  35110. * @returns true if the submesh is intersecting with the frustum
  35111. */
  35112. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35113. var boundingInfo = this.getBoundingInfo();
  35114. if (!boundingInfo) {
  35115. return false;
  35116. }
  35117. return boundingInfo.isInFrustum(frustumPlanes);
  35118. };
  35119. /**
  35120. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35121. * @param frustumPlanes defines the frustum planes
  35122. * @returns true if the submesh is inside the frustum
  35123. */
  35124. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35125. var boundingInfo = this.getBoundingInfo();
  35126. if (!boundingInfo) {
  35127. return false;
  35128. }
  35129. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35130. };
  35131. /**
  35132. * Renders the submesh
  35133. * @param enableAlphaMode defines if alpha needs to be used
  35134. * @returns the submesh
  35135. */
  35136. SubMesh.prototype.render = function (enableAlphaMode) {
  35137. this._renderingMesh.render(this, enableAlphaMode);
  35138. return this;
  35139. };
  35140. /**
  35141. * @hidden
  35142. */
  35143. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35144. if (!this._linesIndexBuffer) {
  35145. var linesIndices = [];
  35146. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35147. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35148. }
  35149. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35150. this._linesIndexCount = linesIndices.length;
  35151. }
  35152. return this._linesIndexBuffer;
  35153. };
  35154. /**
  35155. * Checks if the submesh intersects with a ray
  35156. * @param ray defines the ray to test
  35157. * @returns true is the passed ray intersects the submesh bounding box
  35158. */
  35159. SubMesh.prototype.canIntersects = function (ray) {
  35160. var boundingInfo = this.getBoundingInfo();
  35161. if (!boundingInfo) {
  35162. return false;
  35163. }
  35164. return ray.intersectsBox(boundingInfo.boundingBox);
  35165. };
  35166. /**
  35167. * Intersects current submesh with a ray
  35168. * @param ray defines the ray to test
  35169. * @param positions defines mesh's positions array
  35170. * @param indices defines mesh's indices array
  35171. * @param fastCheck defines if only bounding info should be used
  35172. * @returns intersection info or null if no intersection
  35173. */
  35174. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35175. var intersectInfo = null;
  35176. var material = this.getMaterial();
  35177. if (!material) {
  35178. return null;
  35179. }
  35180. switch (material.fillMode) {
  35181. case BABYLON.Material.PointListDrawMode:
  35182. case BABYLON.Material.LineListDrawMode:
  35183. case BABYLON.Material.LineLoopDrawMode:
  35184. case BABYLON.Material.LineStripDrawMode:
  35185. case BABYLON.Material.TriangleFanDrawMode:
  35186. case BABYLON.Material.TriangleStripDrawMode:
  35187. return null;
  35188. }
  35189. // LineMesh first as it's also a Mesh...
  35190. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  35191. var lineMesh = this._mesh;
  35192. // Line test
  35193. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35194. var p0 = positions[indices[index]];
  35195. var p1 = positions[indices[index + 1]];
  35196. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  35197. if (length < 0) {
  35198. continue;
  35199. }
  35200. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35201. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35202. if (fastCheck) {
  35203. break;
  35204. }
  35205. }
  35206. }
  35207. }
  35208. else {
  35209. // Triangles test
  35210. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35211. var p0 = positions[indices[index]];
  35212. var p1 = positions[indices[index + 1]];
  35213. var p2 = positions[indices[index + 2]];
  35214. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35215. if (currentIntersectInfo) {
  35216. if (currentIntersectInfo.distance < 0) {
  35217. continue;
  35218. }
  35219. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35220. intersectInfo = currentIntersectInfo;
  35221. intersectInfo.faceId = index / 3;
  35222. if (fastCheck) {
  35223. break;
  35224. }
  35225. }
  35226. }
  35227. }
  35228. }
  35229. return intersectInfo;
  35230. };
  35231. /** @hidden */
  35232. SubMesh.prototype._rebuild = function () {
  35233. if (this._linesIndexBuffer) {
  35234. this._linesIndexBuffer = null;
  35235. }
  35236. };
  35237. // Clone
  35238. /**
  35239. * Creates a new submesh from the passed mesh
  35240. * @param newMesh defines the new hosting mesh
  35241. * @param newRenderingMesh defines an optional rendering mesh
  35242. * @returns the new submesh
  35243. */
  35244. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35245. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35246. if (!this.IsGlobal) {
  35247. var boundingInfo = this.getBoundingInfo();
  35248. if (!boundingInfo) {
  35249. return result;
  35250. }
  35251. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35252. }
  35253. return result;
  35254. };
  35255. // Dispose
  35256. /**
  35257. * Release associated resources
  35258. */
  35259. SubMesh.prototype.dispose = function () {
  35260. if (this._linesIndexBuffer) {
  35261. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35262. this._linesIndexBuffer = null;
  35263. }
  35264. // Remove from mesh
  35265. var index = this._mesh.subMeshes.indexOf(this);
  35266. this._mesh.subMeshes.splice(index, 1);
  35267. };
  35268. // Statics
  35269. /**
  35270. * Creates a new submesh from indices data
  35271. * @param materialIndex the index of the main mesh material
  35272. * @param startIndex the index where to start the copy in the mesh indices array
  35273. * @param indexCount the number of indices to copy then from the startIndex
  35274. * @param mesh the main mesh to create the submesh from
  35275. * @param renderingMesh the optional rendering mesh
  35276. * @returns a new submesh
  35277. */
  35278. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35279. var minVertexIndex = Number.MAX_VALUE;
  35280. var maxVertexIndex = -Number.MAX_VALUE;
  35281. renderingMesh = (renderingMesh || mesh);
  35282. var indices = renderingMesh.getIndices();
  35283. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35284. var vertexIndex = indices[index];
  35285. if (vertexIndex < minVertexIndex)
  35286. minVertexIndex = vertexIndex;
  35287. if (vertexIndex > maxVertexIndex)
  35288. maxVertexIndex = vertexIndex;
  35289. }
  35290. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35291. };
  35292. return SubMesh;
  35293. }(BaseSubMesh));
  35294. BABYLON.SubMesh = SubMesh;
  35295. })(BABYLON || (BABYLON = {}));
  35296. //# sourceMappingURL=babylon.subMesh.js.map
  35297. var __assign = (this && this.__assign) || function () {
  35298. __assign = Object.assign || function(t) {
  35299. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35300. s = arguments[i];
  35301. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35302. t[p] = s[p];
  35303. }
  35304. return t;
  35305. };
  35306. return __assign.apply(this, arguments);
  35307. };
  35308. var BABYLON;
  35309. (function (BABYLON) {
  35310. /**
  35311. * Manages the defines for the Material
  35312. */
  35313. var MaterialDefines = /** @class */ (function () {
  35314. function MaterialDefines() {
  35315. this._isDirty = true;
  35316. /** @hidden */
  35317. this._areLightsDirty = true;
  35318. /** @hidden */
  35319. this._areAttributesDirty = true;
  35320. /** @hidden */
  35321. this._areTexturesDirty = true;
  35322. /** @hidden */
  35323. this._areFresnelDirty = true;
  35324. /** @hidden */
  35325. this._areMiscDirty = true;
  35326. /** @hidden */
  35327. this._areImageProcessingDirty = true;
  35328. /** @hidden */
  35329. this._normals = false;
  35330. /** @hidden */
  35331. this._uvs = false;
  35332. /** @hidden */
  35333. this._needNormals = false;
  35334. /** @hidden */
  35335. this._needUVs = false;
  35336. }
  35337. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35338. /**
  35339. * Specifies if the material needs to be re-calculated
  35340. */
  35341. get: function () {
  35342. return this._isDirty;
  35343. },
  35344. enumerable: true,
  35345. configurable: true
  35346. });
  35347. /**
  35348. * Marks the material to indicate that it has been re-calculated
  35349. */
  35350. MaterialDefines.prototype.markAsProcessed = function () {
  35351. this._isDirty = false;
  35352. this._areAttributesDirty = false;
  35353. this._areTexturesDirty = false;
  35354. this._areFresnelDirty = false;
  35355. this._areLightsDirty = false;
  35356. this._areMiscDirty = false;
  35357. this._areImageProcessingDirty = false;
  35358. };
  35359. /**
  35360. * Marks the material to indicate that it needs to be re-calculated
  35361. */
  35362. MaterialDefines.prototype.markAsUnprocessed = function () {
  35363. this._isDirty = true;
  35364. };
  35365. /**
  35366. * Marks the material to indicate all of its defines need to be re-calculated
  35367. */
  35368. MaterialDefines.prototype.markAllAsDirty = function () {
  35369. this._areTexturesDirty = true;
  35370. this._areAttributesDirty = true;
  35371. this._areLightsDirty = true;
  35372. this._areFresnelDirty = true;
  35373. this._areMiscDirty = true;
  35374. this._areImageProcessingDirty = true;
  35375. this._isDirty = true;
  35376. };
  35377. /**
  35378. * Marks the material to indicate that image processing needs to be re-calculated
  35379. */
  35380. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35381. this._areImageProcessingDirty = true;
  35382. this._isDirty = true;
  35383. };
  35384. /**
  35385. * Marks the material to indicate the lights need to be re-calculated
  35386. */
  35387. MaterialDefines.prototype.markAsLightDirty = function () {
  35388. this._areLightsDirty = true;
  35389. this._isDirty = true;
  35390. };
  35391. /**
  35392. * Marks the attribute state as changed
  35393. */
  35394. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35395. this._areAttributesDirty = true;
  35396. this._isDirty = true;
  35397. };
  35398. /**
  35399. * Marks the texture state as changed
  35400. */
  35401. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35402. this._areTexturesDirty = true;
  35403. this._isDirty = true;
  35404. };
  35405. /**
  35406. * Marks the fresnel state as changed
  35407. */
  35408. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35409. this._areFresnelDirty = true;
  35410. this._isDirty = true;
  35411. };
  35412. /**
  35413. * Marks the misc state as changed
  35414. */
  35415. MaterialDefines.prototype.markAsMiscDirty = function () {
  35416. this._areMiscDirty = true;
  35417. this._isDirty = true;
  35418. };
  35419. /**
  35420. * Rebuilds the material defines
  35421. */
  35422. MaterialDefines.prototype.rebuild = function () {
  35423. if (this._keys) {
  35424. delete this._keys;
  35425. }
  35426. this._keys = [];
  35427. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35428. var key = _a[_i];
  35429. if (key[0] === "_") {
  35430. continue;
  35431. }
  35432. this._keys.push(key);
  35433. }
  35434. };
  35435. /**
  35436. * Specifies if two material defines are equal
  35437. * @param other - A material define instance to compare to
  35438. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35439. */
  35440. MaterialDefines.prototype.isEqual = function (other) {
  35441. if (this._keys.length !== other._keys.length) {
  35442. return false;
  35443. }
  35444. for (var index = 0; index < this._keys.length; index++) {
  35445. var prop = this._keys[index];
  35446. if (this[prop] !== other[prop]) {
  35447. return false;
  35448. }
  35449. }
  35450. return true;
  35451. };
  35452. /**
  35453. * Clones this instance's defines to another instance
  35454. * @param other - material defines to clone values to
  35455. */
  35456. MaterialDefines.prototype.cloneTo = function (other) {
  35457. if (this._keys.length !== other._keys.length) {
  35458. other._keys = this._keys.slice(0);
  35459. }
  35460. for (var index = 0; index < this._keys.length; index++) {
  35461. var prop = this._keys[index];
  35462. other[prop] = this[prop];
  35463. }
  35464. };
  35465. /**
  35466. * Resets the material define values
  35467. */
  35468. MaterialDefines.prototype.reset = function () {
  35469. for (var index = 0; index < this._keys.length; index++) {
  35470. var prop = this._keys[index];
  35471. var type = typeof this[prop];
  35472. switch (type) {
  35473. case "number":
  35474. this[prop] = 0;
  35475. break;
  35476. case "string":
  35477. this[prop] = "";
  35478. break;
  35479. default:
  35480. this[prop] = false;
  35481. break;
  35482. }
  35483. }
  35484. };
  35485. /**
  35486. * Converts the material define values to a string
  35487. * @returns - String of material define information
  35488. */
  35489. MaterialDefines.prototype.toString = function () {
  35490. var result = "";
  35491. for (var index = 0; index < this._keys.length; index++) {
  35492. var prop = this._keys[index];
  35493. var value = this[prop];
  35494. var type = typeof value;
  35495. switch (type) {
  35496. case "number":
  35497. case "string":
  35498. result += "#define " + prop + " " + value + "\n";
  35499. break;
  35500. default:
  35501. if (value) {
  35502. result += "#define " + prop + "\n";
  35503. }
  35504. break;
  35505. }
  35506. }
  35507. return result;
  35508. };
  35509. return MaterialDefines;
  35510. }());
  35511. BABYLON.MaterialDefines = MaterialDefines;
  35512. /**
  35513. * Base class for the main features of a material in Babylon.js
  35514. */
  35515. var Material = /** @class */ (function () {
  35516. /**
  35517. * Creates a material instance
  35518. * @param name defines the name of the material
  35519. * @param scene defines the scene to reference
  35520. * @param doNotAdd specifies if the material should be added to the scene
  35521. */
  35522. function Material(name, scene, doNotAdd) {
  35523. /**
  35524. * Specifies if the ready state should be checked on each call
  35525. */
  35526. this.checkReadyOnEveryCall = false;
  35527. /**
  35528. * Specifies if the ready state should be checked once
  35529. */
  35530. this.checkReadyOnlyOnce = false;
  35531. /**
  35532. * The state of the material
  35533. */
  35534. this.state = "";
  35535. /**
  35536. * The alpha value of the material
  35537. */
  35538. this._alpha = 1.0;
  35539. /**
  35540. * Specifies if back face culling is enabled
  35541. */
  35542. this._backFaceCulling = true;
  35543. /**
  35544. * Specifies if the material should be serialized
  35545. */
  35546. this.doNotSerialize = false;
  35547. /**
  35548. * Specifies if the effect should be stored on sub meshes
  35549. */
  35550. this.storeEffectOnSubMeshes = false;
  35551. /**
  35552. * An event triggered when the material is disposed
  35553. */
  35554. this.onDisposeObservable = new BABYLON.Observable();
  35555. /**
  35556. * Stores the value of the alpha mode
  35557. */
  35558. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35559. /**
  35560. * Stores the state of the need depth pre-pass value
  35561. */
  35562. this._needDepthPrePass = false;
  35563. /**
  35564. * Specifies if depth writing should be disabled
  35565. */
  35566. this.disableDepthWrite = false;
  35567. /**
  35568. * Specifies if depth writing should be forced
  35569. */
  35570. this.forceDepthWrite = false;
  35571. /**
  35572. * Specifies if there should be a separate pass for culling
  35573. */
  35574. this.separateCullingPass = false;
  35575. /**
  35576. * Stores the state specifing if fog should be enabled
  35577. */
  35578. this._fogEnabled = true;
  35579. /**
  35580. * Stores the size of points
  35581. */
  35582. this.pointSize = 1.0;
  35583. /**
  35584. * Stores the z offset value
  35585. */
  35586. this.zOffset = 0;
  35587. /**
  35588. * @hidden
  35589. * Specifies if the material was previously ready
  35590. */
  35591. this._wasPreviouslyReady = false;
  35592. /**
  35593. * Stores the fill mode state
  35594. */
  35595. this._fillMode = Material.TriangleFillMode;
  35596. this.name = name;
  35597. this.id = name || BABYLON.Tools.RandomId();
  35598. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35599. this.uniqueId = this._scene.getUniqueId();
  35600. if (this._scene.useRightHandedSystem) {
  35601. this.sideOrientation = Material.ClockWiseSideOrientation;
  35602. }
  35603. else {
  35604. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35605. }
  35606. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35607. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35608. if (!doNotAdd) {
  35609. this._scene.materials.push(this);
  35610. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  35611. }
  35612. }
  35613. Object.defineProperty(Material, "TriangleFillMode", {
  35614. /**
  35615. * Returns the triangle fill mode
  35616. */
  35617. get: function () {
  35618. return Material._TriangleFillMode;
  35619. },
  35620. enumerable: true,
  35621. configurable: true
  35622. });
  35623. Object.defineProperty(Material, "WireFrameFillMode", {
  35624. /**
  35625. * Returns the wireframe mode
  35626. */
  35627. get: function () {
  35628. return Material._WireFrameFillMode;
  35629. },
  35630. enumerable: true,
  35631. configurable: true
  35632. });
  35633. Object.defineProperty(Material, "PointFillMode", {
  35634. /**
  35635. * Returns the point fill mode
  35636. */
  35637. get: function () {
  35638. return Material._PointFillMode;
  35639. },
  35640. enumerable: true,
  35641. configurable: true
  35642. });
  35643. Object.defineProperty(Material, "PointListDrawMode", {
  35644. /**
  35645. * Returns the point list draw mode
  35646. */
  35647. get: function () {
  35648. return Material._PointListDrawMode;
  35649. },
  35650. enumerable: true,
  35651. configurable: true
  35652. });
  35653. Object.defineProperty(Material, "LineListDrawMode", {
  35654. /**
  35655. * Returns the line list draw mode
  35656. */
  35657. get: function () {
  35658. return Material._LineListDrawMode;
  35659. },
  35660. enumerable: true,
  35661. configurable: true
  35662. });
  35663. Object.defineProperty(Material, "LineLoopDrawMode", {
  35664. /**
  35665. * Returns the line loop draw mode
  35666. */
  35667. get: function () {
  35668. return Material._LineLoopDrawMode;
  35669. },
  35670. enumerable: true,
  35671. configurable: true
  35672. });
  35673. Object.defineProperty(Material, "LineStripDrawMode", {
  35674. /**
  35675. * Returns the line strip draw mode
  35676. */
  35677. get: function () {
  35678. return Material._LineStripDrawMode;
  35679. },
  35680. enumerable: true,
  35681. configurable: true
  35682. });
  35683. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35684. /**
  35685. * Returns the triangle strip draw mode
  35686. */
  35687. get: function () {
  35688. return Material._TriangleStripDrawMode;
  35689. },
  35690. enumerable: true,
  35691. configurable: true
  35692. });
  35693. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35694. /**
  35695. * Returns the triangle fan draw mode
  35696. */
  35697. get: function () {
  35698. return Material._TriangleFanDrawMode;
  35699. },
  35700. enumerable: true,
  35701. configurable: true
  35702. });
  35703. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35704. /**
  35705. * Returns the clock-wise side orientation
  35706. */
  35707. get: function () {
  35708. return Material._ClockWiseSideOrientation;
  35709. },
  35710. enumerable: true,
  35711. configurable: true
  35712. });
  35713. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35714. /**
  35715. * Returns the counter clock-wise side orientation
  35716. */
  35717. get: function () {
  35718. return Material._CounterClockWiseSideOrientation;
  35719. },
  35720. enumerable: true,
  35721. configurable: true
  35722. });
  35723. Object.defineProperty(Material.prototype, "alpha", {
  35724. /**
  35725. * Gets the alpha value of the material
  35726. */
  35727. get: function () {
  35728. return this._alpha;
  35729. },
  35730. /**
  35731. * Sets the alpha value of the material
  35732. */
  35733. set: function (value) {
  35734. if (this._alpha === value) {
  35735. return;
  35736. }
  35737. this._alpha = value;
  35738. this.markAsDirty(Material.MiscDirtyFlag);
  35739. },
  35740. enumerable: true,
  35741. configurable: true
  35742. });
  35743. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35744. /**
  35745. * Gets the back-face culling state
  35746. */
  35747. get: function () {
  35748. return this._backFaceCulling;
  35749. },
  35750. /**
  35751. * Sets the back-face culling state
  35752. */
  35753. set: function (value) {
  35754. if (this._backFaceCulling === value) {
  35755. return;
  35756. }
  35757. this._backFaceCulling = value;
  35758. this.markAsDirty(Material.TextureDirtyFlag);
  35759. },
  35760. enumerable: true,
  35761. configurable: true
  35762. });
  35763. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  35764. /**
  35765. * Gets a boolean indicating that current material needs to register RTT
  35766. */
  35767. get: function () {
  35768. return false;
  35769. },
  35770. enumerable: true,
  35771. configurable: true
  35772. });
  35773. Object.defineProperty(Material.prototype, "onDispose", {
  35774. /**
  35775. * Called during a dispose event
  35776. */
  35777. set: function (callback) {
  35778. if (this._onDisposeObserver) {
  35779. this.onDisposeObservable.remove(this._onDisposeObserver);
  35780. }
  35781. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35782. },
  35783. enumerable: true,
  35784. configurable: true
  35785. });
  35786. Object.defineProperty(Material.prototype, "onBindObservable", {
  35787. /**
  35788. * An event triggered when the material is bound
  35789. */
  35790. get: function () {
  35791. if (!this._onBindObservable) {
  35792. this._onBindObservable = new BABYLON.Observable();
  35793. }
  35794. return this._onBindObservable;
  35795. },
  35796. enumerable: true,
  35797. configurable: true
  35798. });
  35799. Object.defineProperty(Material.prototype, "onBind", {
  35800. /**
  35801. * Called during a bind event
  35802. */
  35803. set: function (callback) {
  35804. if (this._onBindObserver) {
  35805. this.onBindObservable.remove(this._onBindObserver);
  35806. }
  35807. this._onBindObserver = this.onBindObservable.add(callback);
  35808. },
  35809. enumerable: true,
  35810. configurable: true
  35811. });
  35812. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35813. /**
  35814. * An event triggered when the material is unbound
  35815. */
  35816. get: function () {
  35817. if (!this._onUnBindObservable) {
  35818. this._onUnBindObservable = new BABYLON.Observable();
  35819. }
  35820. return this._onUnBindObservable;
  35821. },
  35822. enumerable: true,
  35823. configurable: true
  35824. });
  35825. Object.defineProperty(Material.prototype, "alphaMode", {
  35826. /**
  35827. * Gets the value of the alpha mode
  35828. */
  35829. get: function () {
  35830. return this._alphaMode;
  35831. },
  35832. /**
  35833. * Sets the value of the alpha mode.
  35834. *
  35835. * | Value | Type | Description |
  35836. * | --- | --- | --- |
  35837. * | 0 | ALPHA_DISABLE | |
  35838. * | 1 | ALPHA_ADD | |
  35839. * | 2 | ALPHA_COMBINE | |
  35840. * | 3 | ALPHA_SUBTRACT | |
  35841. * | 4 | ALPHA_MULTIPLY | |
  35842. * | 5 | ALPHA_MAXIMIZED | |
  35843. * | 6 | ALPHA_ONEONE | |
  35844. * | 7 | ALPHA_PREMULTIPLIED | |
  35845. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35846. * | 9 | ALPHA_INTERPOLATE | |
  35847. * | 10 | ALPHA_SCREENMODE | |
  35848. *
  35849. */
  35850. set: function (value) {
  35851. if (this._alphaMode === value) {
  35852. return;
  35853. }
  35854. this._alphaMode = value;
  35855. this.markAsDirty(Material.TextureDirtyFlag);
  35856. },
  35857. enumerable: true,
  35858. configurable: true
  35859. });
  35860. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35861. /**
  35862. * Gets the depth pre-pass value
  35863. */
  35864. get: function () {
  35865. return this._needDepthPrePass;
  35866. },
  35867. /**
  35868. * Sets the need depth pre-pass value
  35869. */
  35870. set: function (value) {
  35871. if (this._needDepthPrePass === value) {
  35872. return;
  35873. }
  35874. this._needDepthPrePass = value;
  35875. if (this._needDepthPrePass) {
  35876. this.checkReadyOnEveryCall = true;
  35877. }
  35878. },
  35879. enumerable: true,
  35880. configurable: true
  35881. });
  35882. Object.defineProperty(Material.prototype, "fogEnabled", {
  35883. /**
  35884. * Gets the value of the fog enabled state
  35885. */
  35886. get: function () {
  35887. return this._fogEnabled;
  35888. },
  35889. /**
  35890. * Sets the state for enabling fog
  35891. */
  35892. set: function (value) {
  35893. if (this._fogEnabled === value) {
  35894. return;
  35895. }
  35896. this._fogEnabled = value;
  35897. this.markAsDirty(Material.MiscDirtyFlag);
  35898. },
  35899. enumerable: true,
  35900. configurable: true
  35901. });
  35902. Object.defineProperty(Material.prototype, "wireframe", {
  35903. /**
  35904. * Gets a value specifying if wireframe mode is enabled
  35905. */
  35906. get: function () {
  35907. switch (this._fillMode) {
  35908. case Material.WireFrameFillMode:
  35909. case Material.LineListDrawMode:
  35910. case Material.LineLoopDrawMode:
  35911. case Material.LineStripDrawMode:
  35912. return true;
  35913. }
  35914. return this._scene.forceWireframe;
  35915. },
  35916. /**
  35917. * Sets the state of wireframe mode
  35918. */
  35919. set: function (value) {
  35920. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35921. },
  35922. enumerable: true,
  35923. configurable: true
  35924. });
  35925. Object.defineProperty(Material.prototype, "pointsCloud", {
  35926. /**
  35927. * Gets the value specifying if point clouds are enabled
  35928. */
  35929. get: function () {
  35930. switch (this._fillMode) {
  35931. case Material.PointFillMode:
  35932. case Material.PointListDrawMode:
  35933. return true;
  35934. }
  35935. return this._scene.forcePointsCloud;
  35936. },
  35937. /**
  35938. * Sets the state of point cloud mode
  35939. */
  35940. set: function (value) {
  35941. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35942. },
  35943. enumerable: true,
  35944. configurable: true
  35945. });
  35946. Object.defineProperty(Material.prototype, "fillMode", {
  35947. /**
  35948. * Gets the material fill mode
  35949. */
  35950. get: function () {
  35951. return this._fillMode;
  35952. },
  35953. /**
  35954. * Sets the material fill mode
  35955. */
  35956. set: function (value) {
  35957. if (this._fillMode === value) {
  35958. return;
  35959. }
  35960. this._fillMode = value;
  35961. this.markAsDirty(Material.MiscDirtyFlag);
  35962. },
  35963. enumerable: true,
  35964. configurable: true
  35965. });
  35966. /**
  35967. * Returns a string representation of the current material
  35968. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35969. * @returns a string with material information
  35970. */
  35971. Material.prototype.toString = function (fullDetails) {
  35972. var ret = "Name: " + this.name;
  35973. if (fullDetails) {
  35974. }
  35975. return ret;
  35976. };
  35977. /**
  35978. * Gets the class name of the material
  35979. * @returns a string with the class name of the material
  35980. */
  35981. Material.prototype.getClassName = function () {
  35982. return "Material";
  35983. };
  35984. Object.defineProperty(Material.prototype, "isFrozen", {
  35985. /**
  35986. * Specifies if updates for the material been locked
  35987. */
  35988. get: function () {
  35989. return this.checkReadyOnlyOnce;
  35990. },
  35991. enumerable: true,
  35992. configurable: true
  35993. });
  35994. /**
  35995. * Locks updates for the material
  35996. */
  35997. Material.prototype.freeze = function () {
  35998. this.checkReadyOnlyOnce = true;
  35999. };
  36000. /**
  36001. * Unlocks updates for the material
  36002. */
  36003. Material.prototype.unfreeze = function () {
  36004. this.checkReadyOnlyOnce = false;
  36005. };
  36006. /**
  36007. * Specifies if the material is ready to be used
  36008. * @param mesh defines the mesh to check
  36009. * @param useInstances specifies if instances should be used
  36010. * @returns a boolean indicating if the material is ready to be used
  36011. */
  36012. Material.prototype.isReady = function (mesh, useInstances) {
  36013. return true;
  36014. };
  36015. /**
  36016. * Specifies that the submesh is ready to be used
  36017. * @param mesh defines the mesh to check
  36018. * @param subMesh defines which submesh to check
  36019. * @param useInstances specifies that instances should be used
  36020. * @returns a boolean indicating that the submesh is ready or not
  36021. */
  36022. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36023. return false;
  36024. };
  36025. /**
  36026. * Returns the material effect
  36027. * @returns the effect associated with the material
  36028. */
  36029. Material.prototype.getEffect = function () {
  36030. return this._effect;
  36031. };
  36032. /**
  36033. * Returns the current scene
  36034. * @returns a Scene
  36035. */
  36036. Material.prototype.getScene = function () {
  36037. return this._scene;
  36038. };
  36039. /**
  36040. * Specifies if the material will require alpha blending
  36041. * @returns a boolean specifying if alpha blending is needed
  36042. */
  36043. Material.prototype.needAlphaBlending = function () {
  36044. return (this.alpha < 1.0);
  36045. };
  36046. /**
  36047. * Specifies if the mesh will require alpha blending
  36048. * @param mesh defines the mesh to check
  36049. * @returns a boolean specifying if alpha blending is needed for the mesh
  36050. */
  36051. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36052. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36053. };
  36054. /**
  36055. * Specifies if this material should be rendered in alpha test mode
  36056. * @returns a boolean specifying if an alpha test is needed.
  36057. */
  36058. Material.prototype.needAlphaTesting = function () {
  36059. return false;
  36060. };
  36061. /**
  36062. * Gets the texture used for the alpha test
  36063. * @returns the texture to use for alpha testing
  36064. */
  36065. Material.prototype.getAlphaTestTexture = function () {
  36066. return null;
  36067. };
  36068. /**
  36069. * Marks the material to indicate that it needs to be re-calculated
  36070. */
  36071. Material.prototype.markDirty = function () {
  36072. this._wasPreviouslyReady = false;
  36073. };
  36074. /** @hidden */
  36075. Material.prototype._preBind = function (effect, overrideOrientation) {
  36076. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36077. var engine = this._scene.getEngine();
  36078. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36079. var reverse = orientation === Material.ClockWiseSideOrientation;
  36080. engine.enableEffect(effect ? effect : this._effect);
  36081. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36082. return reverse;
  36083. };
  36084. /**
  36085. * Binds the material to the mesh
  36086. * @param world defines the world transformation matrix
  36087. * @param mesh defines the mesh to bind the material to
  36088. */
  36089. Material.prototype.bind = function (world, mesh) {
  36090. };
  36091. /**
  36092. * Binds the submesh to the material
  36093. * @param world defines the world transformation matrix
  36094. * @param mesh defines the mesh containing the submesh
  36095. * @param subMesh defines the submesh to bind the material to
  36096. */
  36097. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36098. };
  36099. /**
  36100. * Binds the world matrix to the material
  36101. * @param world defines the world transformation matrix
  36102. */
  36103. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36104. };
  36105. /**
  36106. * Binds the scene's uniform buffer to the effect.
  36107. * @param effect defines the effect to bind to the scene uniform buffer
  36108. * @param sceneUbo defines the uniform buffer storing scene data
  36109. */
  36110. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36111. sceneUbo.bindToEffect(effect, "Scene");
  36112. };
  36113. /**
  36114. * Binds the view matrix to the effect
  36115. * @param effect defines the effect to bind the view matrix to
  36116. */
  36117. Material.prototype.bindView = function (effect) {
  36118. if (!this._useUBO) {
  36119. effect.setMatrix("view", this.getScene().getViewMatrix());
  36120. }
  36121. else {
  36122. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36123. }
  36124. };
  36125. /**
  36126. * Binds the view projection matrix to the effect
  36127. * @param effect defines the effect to bind the view projection matrix to
  36128. */
  36129. Material.prototype.bindViewProjection = function (effect) {
  36130. if (!this._useUBO) {
  36131. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36132. }
  36133. else {
  36134. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36135. }
  36136. };
  36137. /**
  36138. * Specifies if material alpha testing should be turned on for the mesh
  36139. * @param mesh defines the mesh to check
  36140. */
  36141. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36142. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36143. };
  36144. /**
  36145. * Processes to execute after binding the material to a mesh
  36146. * @param mesh defines the rendered mesh
  36147. */
  36148. Material.prototype._afterBind = function (mesh) {
  36149. this._scene._cachedMaterial = this;
  36150. if (mesh) {
  36151. this._scene._cachedVisibility = mesh.visibility;
  36152. }
  36153. else {
  36154. this._scene._cachedVisibility = 1;
  36155. }
  36156. if (this._onBindObservable && mesh) {
  36157. this._onBindObservable.notifyObservers(mesh);
  36158. }
  36159. if (this.disableDepthWrite) {
  36160. var engine = this._scene.getEngine();
  36161. this._cachedDepthWriteState = engine.getDepthWrite();
  36162. engine.setDepthWrite(false);
  36163. }
  36164. };
  36165. /**
  36166. * Unbinds the material from the mesh
  36167. */
  36168. Material.prototype.unbind = function () {
  36169. if (this._onUnBindObservable) {
  36170. this._onUnBindObservable.notifyObservers(this);
  36171. }
  36172. if (this.disableDepthWrite) {
  36173. var engine = this._scene.getEngine();
  36174. engine.setDepthWrite(this._cachedDepthWriteState);
  36175. }
  36176. };
  36177. /**
  36178. * Gets the active textures from the material
  36179. * @returns an array of textures
  36180. */
  36181. Material.prototype.getActiveTextures = function () {
  36182. return [];
  36183. };
  36184. /**
  36185. * Specifies if the material uses a texture
  36186. * @param texture defines the texture to check against the material
  36187. * @returns a boolean specifying if the material uses the texture
  36188. */
  36189. Material.prototype.hasTexture = function (texture) {
  36190. return false;
  36191. };
  36192. /**
  36193. * Makes a duplicate of the material, and gives it a new name
  36194. * @param name defines the new name for the duplicated material
  36195. * @returns the cloned material
  36196. */
  36197. Material.prototype.clone = function (name) {
  36198. return null;
  36199. };
  36200. /**
  36201. * Gets the meshes bound to the material
  36202. * @returns an array of meshes bound to the material
  36203. */
  36204. Material.prototype.getBindedMeshes = function () {
  36205. var result = new Array();
  36206. for (var index = 0; index < this._scene.meshes.length; index++) {
  36207. var mesh = this._scene.meshes[index];
  36208. if (mesh.material === this) {
  36209. result.push(mesh);
  36210. }
  36211. }
  36212. return result;
  36213. };
  36214. /**
  36215. * Force shader compilation
  36216. * @param mesh defines the mesh associated with this material
  36217. * @param onCompiled defines a function to execute once the material is compiled
  36218. * @param options defines the options to configure the compilation
  36219. */
  36220. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36221. var _this = this;
  36222. var localOptions = __assign({ clipPlane: false }, options);
  36223. var subMesh = new BABYLON.BaseSubMesh();
  36224. var scene = this.getScene();
  36225. var checkReady = function () {
  36226. if (!_this._scene || !_this._scene.getEngine()) {
  36227. return;
  36228. }
  36229. if (subMesh._materialDefines) {
  36230. subMesh._materialDefines._renderId = -1;
  36231. }
  36232. var clipPlaneState = scene.clipPlane;
  36233. if (localOptions.clipPlane) {
  36234. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36235. }
  36236. if (_this.storeEffectOnSubMeshes) {
  36237. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36238. if (onCompiled) {
  36239. onCompiled(_this);
  36240. }
  36241. }
  36242. else {
  36243. setTimeout(checkReady, 16);
  36244. }
  36245. }
  36246. else {
  36247. if (_this.isReady(mesh)) {
  36248. if (onCompiled) {
  36249. onCompiled(_this);
  36250. }
  36251. }
  36252. else {
  36253. setTimeout(checkReady, 16);
  36254. }
  36255. }
  36256. if (localOptions.clipPlane) {
  36257. scene.clipPlane = clipPlaneState;
  36258. }
  36259. };
  36260. checkReady();
  36261. };
  36262. /**
  36263. * Force shader compilation
  36264. * @param mesh defines the mesh that will use this material
  36265. * @param options defines additional options for compiling the shaders
  36266. * @returns a promise that resolves when the compilation completes
  36267. */
  36268. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36269. var _this = this;
  36270. return new Promise(function (resolve) {
  36271. _this.forceCompilation(mesh, function () {
  36272. resolve();
  36273. }, options);
  36274. });
  36275. };
  36276. /**
  36277. * Marks a define in the material to indicate that it needs to be re-computed
  36278. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36279. */
  36280. Material.prototype.markAsDirty = function (flag) {
  36281. if (flag & Material.TextureDirtyFlag) {
  36282. this._markAllSubMeshesAsTexturesDirty();
  36283. }
  36284. if (flag & Material.LightDirtyFlag) {
  36285. this._markAllSubMeshesAsLightsDirty();
  36286. }
  36287. if (flag & Material.FresnelDirtyFlag) {
  36288. this._markAllSubMeshesAsFresnelDirty();
  36289. }
  36290. if (flag & Material.AttributesDirtyFlag) {
  36291. this._markAllSubMeshesAsAttributesDirty();
  36292. }
  36293. if (flag & Material.MiscDirtyFlag) {
  36294. this._markAllSubMeshesAsMiscDirty();
  36295. }
  36296. this.getScene().resetCachedMaterial();
  36297. };
  36298. /**
  36299. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36300. * @param func defines a function which checks material defines against the submeshes
  36301. */
  36302. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36303. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36304. var mesh = _a[_i];
  36305. if (!mesh.subMeshes) {
  36306. continue;
  36307. }
  36308. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36309. var subMesh = _c[_b];
  36310. if (subMesh.getMaterial() !== this) {
  36311. continue;
  36312. }
  36313. if (!subMesh._materialDefines) {
  36314. continue;
  36315. }
  36316. func(subMesh._materialDefines);
  36317. }
  36318. }
  36319. };
  36320. /**
  36321. * Indicates that image processing needs to be re-calculated for all submeshes
  36322. */
  36323. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36324. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36325. };
  36326. /**
  36327. * Indicates that textures need to be re-calculated for all submeshes
  36328. */
  36329. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36330. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36331. };
  36332. /**
  36333. * Indicates that fresnel needs to be re-calculated for all submeshes
  36334. */
  36335. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36336. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36337. };
  36338. /**
  36339. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36340. */
  36341. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36342. this._markAllSubMeshesAsDirty(function (defines) {
  36343. defines.markAsFresnelDirty();
  36344. defines.markAsMiscDirty();
  36345. });
  36346. };
  36347. /**
  36348. * Indicates that lights need to be re-calculated for all submeshes
  36349. */
  36350. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36351. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36352. };
  36353. /**
  36354. * Indicates that attributes need to be re-calculated for all submeshes
  36355. */
  36356. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36357. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36358. };
  36359. /**
  36360. * Indicates that misc needs to be re-calculated for all submeshes
  36361. */
  36362. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36363. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36364. };
  36365. /**
  36366. * Indicates that textures and misc need to be re-calculated for all submeshes
  36367. */
  36368. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36369. this._markAllSubMeshesAsDirty(function (defines) {
  36370. defines.markAsTexturesDirty();
  36371. defines.markAsMiscDirty();
  36372. });
  36373. };
  36374. /**
  36375. * Disposes the material
  36376. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36377. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36378. */
  36379. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36380. // Animations
  36381. this.getScene().stopAnimation(this);
  36382. this.getScene().freeProcessedMaterials();
  36383. // Remove from scene
  36384. var index = this._scene.materials.indexOf(this);
  36385. if (index >= 0) {
  36386. this._scene.materials.splice(index, 1);
  36387. }
  36388. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36389. // Remove from meshes
  36390. for (index = 0; index < this._scene.meshes.length; index++) {
  36391. var mesh = this._scene.meshes[index];
  36392. if (mesh.material === this) {
  36393. mesh.material = null;
  36394. if (mesh.geometry) {
  36395. var geometry = (mesh.geometry);
  36396. if (this.storeEffectOnSubMeshes) {
  36397. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36398. var subMesh = _a[_i];
  36399. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36400. if (forceDisposeEffect && subMesh._materialEffect) {
  36401. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36402. }
  36403. }
  36404. }
  36405. else {
  36406. geometry._releaseVertexArrayObject(this._effect);
  36407. }
  36408. }
  36409. }
  36410. }
  36411. this._uniformBuffer.dispose();
  36412. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36413. if (forceDisposeEffect && this._effect) {
  36414. if (!this.storeEffectOnSubMeshes) {
  36415. this._scene.getEngine()._releaseEffect(this._effect);
  36416. }
  36417. this._effect = null;
  36418. }
  36419. // Callback
  36420. this.onDisposeObservable.notifyObservers(this);
  36421. this.onDisposeObservable.clear();
  36422. if (this._onBindObservable) {
  36423. this._onBindObservable.clear();
  36424. }
  36425. if (this._onUnBindObservable) {
  36426. this._onUnBindObservable.clear();
  36427. }
  36428. };
  36429. /**
  36430. * Serializes this material
  36431. * @returns the serialized material object
  36432. */
  36433. Material.prototype.serialize = function () {
  36434. return BABYLON.SerializationHelper.Serialize(this);
  36435. };
  36436. /**
  36437. * Creates a MultiMaterial from parsed MultiMaterial data.
  36438. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36439. * @param scene defines the hosting scene
  36440. * @returns a new MultiMaterial
  36441. */
  36442. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36443. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36444. multiMaterial.id = parsedMultiMaterial.id;
  36445. if (BABYLON.Tags) {
  36446. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36447. }
  36448. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36449. var subMatId = parsedMultiMaterial.materials[matIndex];
  36450. if (subMatId) {
  36451. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36452. }
  36453. else {
  36454. multiMaterial.subMaterials.push(null);
  36455. }
  36456. }
  36457. return multiMaterial;
  36458. };
  36459. /**
  36460. * Creates a material from parsed material data
  36461. * @param parsedMaterial defines parsed material data
  36462. * @param scene defines the hosting scene
  36463. * @param rootUrl defines the root URL to use to load textures
  36464. * @returns a new material
  36465. */
  36466. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36467. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36468. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36469. }
  36470. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36471. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36472. if (!BABYLON.LegacyPBRMaterial) {
  36473. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36474. return;
  36475. }
  36476. }
  36477. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36478. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36479. };
  36480. // Triangle views
  36481. Material._TriangleFillMode = 0;
  36482. Material._WireFrameFillMode = 1;
  36483. Material._PointFillMode = 2;
  36484. // Draw modes
  36485. Material._PointListDrawMode = 3;
  36486. Material._LineListDrawMode = 4;
  36487. Material._LineLoopDrawMode = 5;
  36488. Material._LineStripDrawMode = 6;
  36489. Material._TriangleStripDrawMode = 7;
  36490. Material._TriangleFanDrawMode = 8;
  36491. /**
  36492. * Stores the clock-wise side orientation
  36493. */
  36494. Material._ClockWiseSideOrientation = 0;
  36495. /**
  36496. * Stores the counter clock-wise side orientation
  36497. */
  36498. Material._CounterClockWiseSideOrientation = 1;
  36499. /**
  36500. * The dirty texture flag value
  36501. */
  36502. Material.TextureDirtyFlag = 1;
  36503. /**
  36504. * The dirty light flag value
  36505. */
  36506. Material.LightDirtyFlag = 2;
  36507. /**
  36508. * The dirty fresnel flag value
  36509. */
  36510. Material.FresnelDirtyFlag = 4;
  36511. /**
  36512. * The dirty attribute flag value
  36513. */
  36514. Material.AttributesDirtyFlag = 8;
  36515. /**
  36516. * The dirty misc flag value
  36517. */
  36518. Material.MiscDirtyFlag = 16;
  36519. /**
  36520. * The all dirty flag value
  36521. */
  36522. Material.AllDirtyFlag = 31;
  36523. __decorate([
  36524. BABYLON.serialize()
  36525. ], Material.prototype, "id", void 0);
  36526. __decorate([
  36527. BABYLON.serialize()
  36528. ], Material.prototype, "uniqueId", void 0);
  36529. __decorate([
  36530. BABYLON.serialize()
  36531. ], Material.prototype, "name", void 0);
  36532. __decorate([
  36533. BABYLON.serialize()
  36534. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36535. __decorate([
  36536. BABYLON.serialize()
  36537. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36538. __decorate([
  36539. BABYLON.serialize()
  36540. ], Material.prototype, "state", void 0);
  36541. __decorate([
  36542. BABYLON.serialize("alpha")
  36543. ], Material.prototype, "_alpha", void 0);
  36544. __decorate([
  36545. BABYLON.serialize("backFaceCulling")
  36546. ], Material.prototype, "_backFaceCulling", void 0);
  36547. __decorate([
  36548. BABYLON.serialize()
  36549. ], Material.prototype, "sideOrientation", void 0);
  36550. __decorate([
  36551. BABYLON.serialize("alphaMode")
  36552. ], Material.prototype, "_alphaMode", void 0);
  36553. __decorate([
  36554. BABYLON.serialize()
  36555. ], Material.prototype, "_needDepthPrePass", void 0);
  36556. __decorate([
  36557. BABYLON.serialize()
  36558. ], Material.prototype, "disableDepthWrite", void 0);
  36559. __decorate([
  36560. BABYLON.serialize()
  36561. ], Material.prototype, "forceDepthWrite", void 0);
  36562. __decorate([
  36563. BABYLON.serialize()
  36564. ], Material.prototype, "separateCullingPass", void 0);
  36565. __decorate([
  36566. BABYLON.serialize("fogEnabled")
  36567. ], Material.prototype, "_fogEnabled", void 0);
  36568. __decorate([
  36569. BABYLON.serialize()
  36570. ], Material.prototype, "pointSize", void 0);
  36571. __decorate([
  36572. BABYLON.serialize()
  36573. ], Material.prototype, "zOffset", void 0);
  36574. __decorate([
  36575. BABYLON.serialize()
  36576. ], Material.prototype, "wireframe", null);
  36577. __decorate([
  36578. BABYLON.serialize()
  36579. ], Material.prototype, "pointsCloud", null);
  36580. __decorate([
  36581. BABYLON.serialize()
  36582. ], Material.prototype, "fillMode", null);
  36583. return Material;
  36584. }());
  36585. BABYLON.Material = Material;
  36586. })(BABYLON || (BABYLON = {}));
  36587. //# sourceMappingURL=babylon.material.js.map
  36588. var BABYLON;
  36589. (function (BABYLON) {
  36590. /**
  36591. * Uniform buffer objects.
  36592. *
  36593. * Handles blocks of uniform on the GPU.
  36594. *
  36595. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36596. *
  36597. * For more information, please refer to :
  36598. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36599. */
  36600. var UniformBuffer = /** @class */ (function () {
  36601. /**
  36602. * Instantiates a new Uniform buffer objects.
  36603. *
  36604. * Handles blocks of uniform on the GPU.
  36605. *
  36606. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36607. *
  36608. * For more information, please refer to :
  36609. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36610. * @param engine Define the engine the buffer is associated with
  36611. * @param data Define the data contained in the buffer
  36612. * @param dynamic Define if the buffer is updatable
  36613. */
  36614. function UniformBuffer(engine, data, dynamic) {
  36615. this._engine = engine;
  36616. this._noUBO = !engine.supportsUniformBuffers;
  36617. this._dynamic = dynamic;
  36618. this._data = data || [];
  36619. this._uniformLocations = {};
  36620. this._uniformSizes = {};
  36621. this._uniformLocationPointer = 0;
  36622. this._needSync = false;
  36623. if (this._noUBO) {
  36624. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36625. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36626. this.updateFloat = this._updateFloatForEffect;
  36627. this.updateFloat2 = this._updateFloat2ForEffect;
  36628. this.updateFloat3 = this._updateFloat3ForEffect;
  36629. this.updateFloat4 = this._updateFloat4ForEffect;
  36630. this.updateMatrix = this._updateMatrixForEffect;
  36631. this.updateVector3 = this._updateVector3ForEffect;
  36632. this.updateVector4 = this._updateVector4ForEffect;
  36633. this.updateColor3 = this._updateColor3ForEffect;
  36634. this.updateColor4 = this._updateColor4ForEffect;
  36635. }
  36636. else {
  36637. this._engine._uniformBuffers.push(this);
  36638. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36639. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36640. this.updateFloat = this._updateFloatForUniform;
  36641. this.updateFloat2 = this._updateFloat2ForUniform;
  36642. this.updateFloat3 = this._updateFloat3ForUniform;
  36643. this.updateFloat4 = this._updateFloat4ForUniform;
  36644. this.updateMatrix = this._updateMatrixForUniform;
  36645. this.updateVector3 = this._updateVector3ForUniform;
  36646. this.updateVector4 = this._updateVector4ForUniform;
  36647. this.updateColor3 = this._updateColor3ForUniform;
  36648. this.updateColor4 = this._updateColor4ForUniform;
  36649. }
  36650. }
  36651. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36652. /**
  36653. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36654. * or just falling back on setUniformXXX calls.
  36655. */
  36656. get: function () {
  36657. return !this._noUBO;
  36658. },
  36659. enumerable: true,
  36660. configurable: true
  36661. });
  36662. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36663. /**
  36664. * Indicates if the WebGL underlying uniform buffer is in sync
  36665. * with the javascript cache data.
  36666. */
  36667. get: function () {
  36668. return !this._needSync;
  36669. },
  36670. enumerable: true,
  36671. configurable: true
  36672. });
  36673. /**
  36674. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36675. * Also, a dynamic UniformBuffer will disable cache verification and always
  36676. * update the underlying WebGL uniform buffer to the GPU.
  36677. * @returns if Dynamic, otherwise false
  36678. */
  36679. UniformBuffer.prototype.isDynamic = function () {
  36680. return this._dynamic !== undefined;
  36681. };
  36682. /**
  36683. * The data cache on JS side.
  36684. * @returns the underlying data as a float array
  36685. */
  36686. UniformBuffer.prototype.getData = function () {
  36687. return this._bufferData;
  36688. };
  36689. /**
  36690. * The underlying WebGL Uniform buffer.
  36691. * @returns the webgl buffer
  36692. */
  36693. UniformBuffer.prototype.getBuffer = function () {
  36694. return this._buffer;
  36695. };
  36696. /**
  36697. * std140 layout specifies how to align data within an UBO structure.
  36698. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36699. * for specs.
  36700. */
  36701. UniformBuffer.prototype._fillAlignment = function (size) {
  36702. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36703. // and 4x4 matrices
  36704. // TODO : change if other types are used
  36705. var alignment;
  36706. if (size <= 2) {
  36707. alignment = size;
  36708. }
  36709. else {
  36710. alignment = 4;
  36711. }
  36712. if ((this._uniformLocationPointer % alignment) !== 0) {
  36713. var oldPointer = this._uniformLocationPointer;
  36714. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36715. var diff = this._uniformLocationPointer - oldPointer;
  36716. for (var i = 0; i < diff; i++) {
  36717. this._data.push(0);
  36718. }
  36719. }
  36720. };
  36721. /**
  36722. * Adds an uniform in the buffer.
  36723. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36724. * for the layout to be correct !
  36725. * @param name Name of the uniform, as used in the uniform block in the shader.
  36726. * @param size Data size, or data directly.
  36727. */
  36728. UniformBuffer.prototype.addUniform = function (name, size) {
  36729. if (this._noUBO) {
  36730. return;
  36731. }
  36732. if (this._uniformLocations[name] !== undefined) {
  36733. // Already existing uniform
  36734. return;
  36735. }
  36736. // This function must be called in the order of the shader layout !
  36737. // size can be the size of the uniform, or data directly
  36738. var data;
  36739. if (size instanceof Array) {
  36740. data = size;
  36741. size = data.length;
  36742. }
  36743. else {
  36744. size = size;
  36745. data = [];
  36746. // Fill with zeros
  36747. for (var i = 0; i < size; i++) {
  36748. data.push(0);
  36749. }
  36750. }
  36751. this._fillAlignment(size);
  36752. this._uniformSizes[name] = size;
  36753. this._uniformLocations[name] = this._uniformLocationPointer;
  36754. this._uniformLocationPointer += size;
  36755. for (var i = 0; i < size; i++) {
  36756. this._data.push(data[i]);
  36757. }
  36758. this._needSync = true;
  36759. };
  36760. /**
  36761. * Adds a Matrix 4x4 to the uniform buffer.
  36762. * @param name Name of the uniform, as used in the uniform block in the shader.
  36763. * @param mat A 4x4 matrix.
  36764. */
  36765. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36766. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36767. };
  36768. /**
  36769. * Adds a vec2 to the uniform buffer.
  36770. * @param name Name of the uniform, as used in the uniform block in the shader.
  36771. * @param x Define the x component value of the vec2
  36772. * @param y Define the y component value of the vec2
  36773. */
  36774. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36775. var temp = [x, y];
  36776. this.addUniform(name, temp);
  36777. };
  36778. /**
  36779. * Adds a vec3 to the uniform buffer.
  36780. * @param name Name of the uniform, as used in the uniform block in the shader.
  36781. * @param x Define the x component value of the vec3
  36782. * @param y Define the y component value of the vec3
  36783. * @param z Define the z component value of the vec3
  36784. */
  36785. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36786. var temp = [x, y, z];
  36787. this.addUniform(name, temp);
  36788. };
  36789. /**
  36790. * Adds a vec3 to the uniform buffer.
  36791. * @param name Name of the uniform, as used in the uniform block in the shader.
  36792. * @param color Define the vec3 from a Color
  36793. */
  36794. UniformBuffer.prototype.addColor3 = function (name, color) {
  36795. var temp = new Array();
  36796. color.toArray(temp);
  36797. this.addUniform(name, temp);
  36798. };
  36799. /**
  36800. * Adds a vec4 to the uniform buffer.
  36801. * @param name Name of the uniform, as used in the uniform block in the shader.
  36802. * @param color Define the rgb components from a Color
  36803. * @param alpha Define the a component of the vec4
  36804. */
  36805. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36806. var temp = new Array();
  36807. color.toArray(temp);
  36808. temp.push(alpha);
  36809. this.addUniform(name, temp);
  36810. };
  36811. /**
  36812. * Adds a vec3 to the uniform buffer.
  36813. * @param name Name of the uniform, as used in the uniform block in the shader.
  36814. * @param vector Define the vec3 components from a Vector
  36815. */
  36816. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36817. var temp = new Array();
  36818. vector.toArray(temp);
  36819. this.addUniform(name, temp);
  36820. };
  36821. /**
  36822. * Adds a Matrix 3x3 to the uniform buffer.
  36823. * @param name Name of the uniform, as used in the uniform block in the shader.
  36824. */
  36825. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36826. this.addUniform(name, 12);
  36827. };
  36828. /**
  36829. * Adds a Matrix 2x2 to the uniform buffer.
  36830. * @param name Name of the uniform, as used in the uniform block in the shader.
  36831. */
  36832. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36833. this.addUniform(name, 8);
  36834. };
  36835. /**
  36836. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36837. */
  36838. UniformBuffer.prototype.create = function () {
  36839. if (this._noUBO) {
  36840. return;
  36841. }
  36842. if (this._buffer) {
  36843. return; // nothing to do
  36844. }
  36845. // See spec, alignment must be filled as a vec4
  36846. this._fillAlignment(4);
  36847. this._bufferData = new Float32Array(this._data);
  36848. this._rebuild();
  36849. this._needSync = true;
  36850. };
  36851. /** @hidden */
  36852. UniformBuffer.prototype._rebuild = function () {
  36853. if (this._noUBO) {
  36854. return;
  36855. }
  36856. if (this._dynamic) {
  36857. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36858. }
  36859. else {
  36860. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36861. }
  36862. };
  36863. /**
  36864. * Updates the WebGL Uniform Buffer on the GPU.
  36865. * If the `dynamic` flag is set to true, no cache comparison is done.
  36866. * Otherwise, the buffer will be updated only if the cache differs.
  36867. */
  36868. UniformBuffer.prototype.update = function () {
  36869. if (!this._buffer) {
  36870. this.create();
  36871. return;
  36872. }
  36873. if (!this._dynamic && !this._needSync) {
  36874. return;
  36875. }
  36876. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36877. this._needSync = false;
  36878. };
  36879. /**
  36880. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36881. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  36882. * @param data Define the flattened data
  36883. * @param size Define the size of the data.
  36884. */
  36885. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36886. var location = this._uniformLocations[uniformName];
  36887. if (location === undefined) {
  36888. if (this._buffer) {
  36889. // Cannot add an uniform if the buffer is already created
  36890. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36891. return;
  36892. }
  36893. this.addUniform(uniformName, size);
  36894. location = this._uniformLocations[uniformName];
  36895. }
  36896. if (!this._buffer) {
  36897. this.create();
  36898. }
  36899. if (!this._dynamic) {
  36900. // Cache for static uniform buffers
  36901. var changed = false;
  36902. for (var i = 0; i < size; i++) {
  36903. if (this._bufferData[location + i] !== data[i]) {
  36904. changed = true;
  36905. this._bufferData[location + i] = data[i];
  36906. }
  36907. }
  36908. this._needSync = this._needSync || changed;
  36909. }
  36910. else {
  36911. // No cache for dynamic
  36912. for (var i = 0; i < size; i++) {
  36913. this._bufferData[location + i] = data[i];
  36914. }
  36915. }
  36916. };
  36917. // Update methods
  36918. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36919. // To match std140, matrix must be realigned
  36920. for (var i = 0; i < 3; i++) {
  36921. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36922. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36923. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36924. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36925. }
  36926. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36927. };
  36928. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36929. this._currentEffect.setMatrix3x3(name, matrix);
  36930. };
  36931. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36932. this._currentEffect.setMatrix2x2(name, matrix);
  36933. };
  36934. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36935. // To match std140, matrix must be realigned
  36936. for (var i = 0; i < 2; i++) {
  36937. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36938. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36939. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36940. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36941. }
  36942. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36943. };
  36944. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36945. this._currentEffect.setFloat(name, x);
  36946. };
  36947. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36948. UniformBuffer._tempBuffer[0] = x;
  36949. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36950. };
  36951. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36952. if (suffix === void 0) { suffix = ""; }
  36953. this._currentEffect.setFloat2(name + suffix, x, y);
  36954. };
  36955. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36956. if (suffix === void 0) { suffix = ""; }
  36957. UniformBuffer._tempBuffer[0] = x;
  36958. UniformBuffer._tempBuffer[1] = y;
  36959. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36960. };
  36961. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36962. if (suffix === void 0) { suffix = ""; }
  36963. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36964. };
  36965. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36966. if (suffix === void 0) { suffix = ""; }
  36967. UniformBuffer._tempBuffer[0] = x;
  36968. UniformBuffer._tempBuffer[1] = y;
  36969. UniformBuffer._tempBuffer[2] = z;
  36970. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36971. };
  36972. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36973. if (suffix === void 0) { suffix = ""; }
  36974. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36975. };
  36976. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36977. if (suffix === void 0) { suffix = ""; }
  36978. UniformBuffer._tempBuffer[0] = x;
  36979. UniformBuffer._tempBuffer[1] = y;
  36980. UniformBuffer._tempBuffer[2] = z;
  36981. UniformBuffer._tempBuffer[3] = w;
  36982. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36983. };
  36984. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36985. this._currentEffect.setMatrix(name, mat);
  36986. };
  36987. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36988. this.updateUniform(name, mat.toArray(), 16);
  36989. };
  36990. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36991. this._currentEffect.setVector3(name, vector);
  36992. };
  36993. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36994. vector.toArray(UniformBuffer._tempBuffer);
  36995. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36996. };
  36997. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36998. this._currentEffect.setVector4(name, vector);
  36999. };
  37000. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37001. vector.toArray(UniformBuffer._tempBuffer);
  37002. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37003. };
  37004. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37005. if (suffix === void 0) { suffix = ""; }
  37006. this._currentEffect.setColor3(name + suffix, color);
  37007. };
  37008. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37009. if (suffix === void 0) { suffix = ""; }
  37010. color.toArray(UniformBuffer._tempBuffer);
  37011. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37012. };
  37013. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37014. if (suffix === void 0) { suffix = ""; }
  37015. this._currentEffect.setColor4(name + suffix, color, alpha);
  37016. };
  37017. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37018. if (suffix === void 0) { suffix = ""; }
  37019. color.toArray(UniformBuffer._tempBuffer);
  37020. UniformBuffer._tempBuffer[3] = alpha;
  37021. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37022. };
  37023. /**
  37024. * Sets a sampler uniform on the effect.
  37025. * @param name Define the name of the sampler.
  37026. * @param texture Define the texture to set in the sampler
  37027. */
  37028. UniformBuffer.prototype.setTexture = function (name, texture) {
  37029. this._currentEffect.setTexture(name, texture);
  37030. };
  37031. /**
  37032. * Directly updates the value of the uniform in the cache AND on the GPU.
  37033. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37034. * @param data Define the flattened data
  37035. */
  37036. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37037. this.updateUniform(uniformName, data, data.length);
  37038. this.update();
  37039. };
  37040. /**
  37041. * Binds this uniform buffer to an effect.
  37042. * @param effect Define the effect to bind the buffer to
  37043. * @param name Name of the uniform block in the shader.
  37044. */
  37045. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37046. this._currentEffect = effect;
  37047. if (this._noUBO || !this._buffer) {
  37048. return;
  37049. }
  37050. effect.bindUniformBuffer(this._buffer, name);
  37051. };
  37052. /**
  37053. * Disposes the uniform buffer.
  37054. */
  37055. UniformBuffer.prototype.dispose = function () {
  37056. if (this._noUBO) {
  37057. return;
  37058. }
  37059. var index = this._engine._uniformBuffers.indexOf(this);
  37060. if (index !== -1) {
  37061. this._engine._uniformBuffers.splice(index, 1);
  37062. }
  37063. if (!this._buffer) {
  37064. return;
  37065. }
  37066. if (this._engine._releaseBuffer(this._buffer)) {
  37067. this._buffer = null;
  37068. }
  37069. };
  37070. // Pool for avoiding memory leaks
  37071. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37072. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37073. return UniformBuffer;
  37074. }());
  37075. BABYLON.UniformBuffer = UniformBuffer;
  37076. })(BABYLON || (BABYLON = {}));
  37077. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37078. var BABYLON;
  37079. (function (BABYLON) {
  37080. /**
  37081. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37082. */
  37083. var VertexData = /** @class */ (function () {
  37084. function VertexData() {
  37085. }
  37086. /**
  37087. * Uses the passed data array to set the set the values for the specified kind of data
  37088. * @param data a linear array of floating numbers
  37089. * @param kind the type of data that is being set, eg positions, colors etc
  37090. */
  37091. VertexData.prototype.set = function (data, kind) {
  37092. switch (kind) {
  37093. case BABYLON.VertexBuffer.PositionKind:
  37094. this.positions = data;
  37095. break;
  37096. case BABYLON.VertexBuffer.NormalKind:
  37097. this.normals = data;
  37098. break;
  37099. case BABYLON.VertexBuffer.TangentKind:
  37100. this.tangents = data;
  37101. break;
  37102. case BABYLON.VertexBuffer.UVKind:
  37103. this.uvs = data;
  37104. break;
  37105. case BABYLON.VertexBuffer.UV2Kind:
  37106. this.uvs2 = data;
  37107. break;
  37108. case BABYLON.VertexBuffer.UV3Kind:
  37109. this.uvs3 = data;
  37110. break;
  37111. case BABYLON.VertexBuffer.UV4Kind:
  37112. this.uvs4 = data;
  37113. break;
  37114. case BABYLON.VertexBuffer.UV5Kind:
  37115. this.uvs5 = data;
  37116. break;
  37117. case BABYLON.VertexBuffer.UV6Kind:
  37118. this.uvs6 = data;
  37119. break;
  37120. case BABYLON.VertexBuffer.ColorKind:
  37121. this.colors = data;
  37122. break;
  37123. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37124. this.matricesIndices = data;
  37125. break;
  37126. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37127. this.matricesWeights = data;
  37128. break;
  37129. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37130. this.matricesIndicesExtra = data;
  37131. break;
  37132. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37133. this.matricesWeightsExtra = data;
  37134. break;
  37135. }
  37136. };
  37137. /**
  37138. * Associates the vertexData to the passed Mesh.
  37139. * Sets it as updatable or not (default `false`)
  37140. * @param mesh the mesh the vertexData is applied to
  37141. * @param updatable when used and having the value true allows new data to update the vertexData
  37142. * @returns the VertexData
  37143. */
  37144. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37145. this._applyTo(mesh, updatable);
  37146. return this;
  37147. };
  37148. /**
  37149. * Associates the vertexData to the passed Geometry.
  37150. * Sets it as updatable or not (default `false`)
  37151. * @param geometry the geometry the vertexData is applied to
  37152. * @param updatable when used and having the value true allows new data to update the vertexData
  37153. * @returns VertexData
  37154. */
  37155. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37156. this._applyTo(geometry, updatable);
  37157. return this;
  37158. };
  37159. /**
  37160. * Updates the associated mesh
  37161. * @param mesh the mesh to be updated
  37162. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37163. * @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
  37164. * @returns VertexData
  37165. */
  37166. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37167. this._update(mesh);
  37168. return this;
  37169. };
  37170. /**
  37171. * Updates the associated geometry
  37172. * @param geometry the geometry to be updated
  37173. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37174. * @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
  37175. * @returns VertexData.
  37176. */
  37177. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37178. this._update(geometry);
  37179. return this;
  37180. };
  37181. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37182. if (updatable === void 0) { updatable = false; }
  37183. if (this.positions) {
  37184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37185. }
  37186. if (this.normals) {
  37187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37188. }
  37189. if (this.tangents) {
  37190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37191. }
  37192. if (this.uvs) {
  37193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37194. }
  37195. if (this.uvs2) {
  37196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37197. }
  37198. if (this.uvs3) {
  37199. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37200. }
  37201. if (this.uvs4) {
  37202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37203. }
  37204. if (this.uvs5) {
  37205. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37206. }
  37207. if (this.uvs6) {
  37208. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37209. }
  37210. if (this.colors) {
  37211. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37212. }
  37213. if (this.matricesIndices) {
  37214. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37215. }
  37216. if (this.matricesWeights) {
  37217. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37218. }
  37219. if (this.matricesIndicesExtra) {
  37220. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37221. }
  37222. if (this.matricesWeightsExtra) {
  37223. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37224. }
  37225. if (this.indices) {
  37226. meshOrGeometry.setIndices(this.indices, null, updatable);
  37227. }
  37228. else {
  37229. meshOrGeometry.setIndices([], null);
  37230. }
  37231. return this;
  37232. };
  37233. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37234. if (this.positions) {
  37235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37236. }
  37237. if (this.normals) {
  37238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37239. }
  37240. if (this.tangents) {
  37241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37242. }
  37243. if (this.uvs) {
  37244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37245. }
  37246. if (this.uvs2) {
  37247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37248. }
  37249. if (this.uvs3) {
  37250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37251. }
  37252. if (this.uvs4) {
  37253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37254. }
  37255. if (this.uvs5) {
  37256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37257. }
  37258. if (this.uvs6) {
  37259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37260. }
  37261. if (this.colors) {
  37262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37263. }
  37264. if (this.matricesIndices) {
  37265. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37266. }
  37267. if (this.matricesWeights) {
  37268. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37269. }
  37270. if (this.matricesIndicesExtra) {
  37271. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37272. }
  37273. if (this.matricesWeightsExtra) {
  37274. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37275. }
  37276. if (this.indices) {
  37277. meshOrGeometry.setIndices(this.indices, null);
  37278. }
  37279. return this;
  37280. };
  37281. /**
  37282. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37283. * @param matrix the transforming matrix
  37284. * @returns the VertexData
  37285. */
  37286. VertexData.prototype.transform = function (matrix) {
  37287. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37288. var transformed = BABYLON.Vector3.Zero();
  37289. var index;
  37290. if (this.positions) {
  37291. var position = BABYLON.Vector3.Zero();
  37292. for (index = 0; index < this.positions.length; index += 3) {
  37293. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37294. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37295. this.positions[index] = transformed.x;
  37296. this.positions[index + 1] = transformed.y;
  37297. this.positions[index + 2] = transformed.z;
  37298. }
  37299. }
  37300. if (this.normals) {
  37301. var normal = BABYLON.Vector3.Zero();
  37302. for (index = 0; index < this.normals.length; index += 3) {
  37303. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37304. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37305. this.normals[index] = transformed.x;
  37306. this.normals[index + 1] = transformed.y;
  37307. this.normals[index + 2] = transformed.z;
  37308. }
  37309. }
  37310. if (this.tangents) {
  37311. var tangent = BABYLON.Vector4.Zero();
  37312. var tangentTransformed = BABYLON.Vector4.Zero();
  37313. for (index = 0; index < this.tangents.length; index += 4) {
  37314. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37315. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37316. this.tangents[index] = tangentTransformed.x;
  37317. this.tangents[index + 1] = tangentTransformed.y;
  37318. this.tangents[index + 2] = tangentTransformed.z;
  37319. this.tangents[index + 3] = tangentTransformed.w;
  37320. }
  37321. }
  37322. if (flip && this.indices) {
  37323. for (index = 0; index < this.indices.length; index += 3) {
  37324. var tmp = this.indices[index + 1];
  37325. this.indices[index + 1] = this.indices[index + 2];
  37326. this.indices[index + 2] = tmp;
  37327. }
  37328. }
  37329. return this;
  37330. };
  37331. /**
  37332. * Merges the passed VertexData into the current one
  37333. * @param other the VertexData to be merged into the current one
  37334. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37335. * @returns the modified VertexData
  37336. */
  37337. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37338. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37339. this._validate();
  37340. other._validate();
  37341. if (!this.normals !== !other.normals ||
  37342. !this.tangents !== !other.tangents ||
  37343. !this.uvs !== !other.uvs ||
  37344. !this.uvs2 !== !other.uvs2 ||
  37345. !this.uvs3 !== !other.uvs3 ||
  37346. !this.uvs4 !== !other.uvs4 ||
  37347. !this.uvs5 !== !other.uvs5 ||
  37348. !this.uvs6 !== !other.uvs6 ||
  37349. !this.colors !== !other.colors ||
  37350. !this.matricesIndices !== !other.matricesIndices ||
  37351. !this.matricesWeights !== !other.matricesWeights ||
  37352. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37353. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37354. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37355. }
  37356. if (other.indices) {
  37357. if (!this.indices) {
  37358. this.indices = [];
  37359. }
  37360. var offset = this.positions ? this.positions.length / 3 : 0;
  37361. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37362. if (isSrcTypedArray) {
  37363. var len = this.indices.length + other.indices.length;
  37364. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37365. temp.set(this.indices);
  37366. var decal = this.indices.length;
  37367. for (var index = 0; index < other.indices.length; index++) {
  37368. temp[decal + index] = other.indices[index] + offset;
  37369. }
  37370. this.indices = temp;
  37371. }
  37372. else {
  37373. for (var index = 0; index < other.indices.length; index++) {
  37374. this.indices.push(other.indices[index] + offset);
  37375. }
  37376. }
  37377. }
  37378. this.positions = this._mergeElement(this.positions, other.positions);
  37379. this.normals = this._mergeElement(this.normals, other.normals);
  37380. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37381. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37382. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37383. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37384. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37385. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37386. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37387. this.colors = this._mergeElement(this.colors, other.colors);
  37388. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37389. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37390. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37391. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37392. return this;
  37393. };
  37394. VertexData.prototype._mergeElement = function (source, other) {
  37395. if (!source) {
  37396. return other;
  37397. }
  37398. if (!other) {
  37399. return source;
  37400. }
  37401. var len = other.length + source.length;
  37402. var isSrcTypedArray = source instanceof Float32Array;
  37403. var isOthTypedArray = other instanceof Float32Array;
  37404. // use non-loop method when the source is Float32Array
  37405. if (isSrcTypedArray) {
  37406. var ret32 = new Float32Array(len);
  37407. ret32.set(source);
  37408. ret32.set(other, source.length);
  37409. return ret32;
  37410. // source is number[], when other is also use concat
  37411. }
  37412. else if (!isOthTypedArray) {
  37413. return source.concat(other);
  37414. // source is a number[], but other is a Float32Array, loop required
  37415. }
  37416. else {
  37417. var ret = source.slice(0); // copy source to a separate array
  37418. for (var i = 0, len = other.length; i < len; i++) {
  37419. ret.push(other[i]);
  37420. }
  37421. return ret;
  37422. }
  37423. };
  37424. VertexData.prototype._validate = function () {
  37425. if (!this.positions) {
  37426. throw new Error("Positions are required");
  37427. }
  37428. var getElementCount = function (kind, values) {
  37429. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37430. if ((values.length % stride) !== 0) {
  37431. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37432. }
  37433. return values.length / stride;
  37434. };
  37435. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37436. var validateElementCount = function (kind, values) {
  37437. var elementCount = getElementCount(kind, values);
  37438. if (elementCount !== positionsElementCount) {
  37439. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37440. }
  37441. };
  37442. if (this.normals)
  37443. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37444. if (this.tangents)
  37445. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37446. if (this.uvs)
  37447. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37448. if (this.uvs2)
  37449. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37450. if (this.uvs3)
  37451. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37452. if (this.uvs4)
  37453. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37454. if (this.uvs5)
  37455. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37456. if (this.uvs6)
  37457. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37458. if (this.colors)
  37459. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37460. if (this.matricesIndices)
  37461. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37462. if (this.matricesWeights)
  37463. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37464. if (this.matricesIndicesExtra)
  37465. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37466. if (this.matricesWeightsExtra)
  37467. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37468. };
  37469. /**
  37470. * Serializes the VertexData
  37471. * @returns a serialized object
  37472. */
  37473. VertexData.prototype.serialize = function () {
  37474. var serializationObject = this.serialize();
  37475. if (this.positions) {
  37476. serializationObject.positions = this.positions;
  37477. }
  37478. if (this.normals) {
  37479. serializationObject.normals = this.normals;
  37480. }
  37481. if (this.tangents) {
  37482. serializationObject.tangents = this.tangents;
  37483. }
  37484. if (this.uvs) {
  37485. serializationObject.uvs = this.uvs;
  37486. }
  37487. if (this.uvs2) {
  37488. serializationObject.uvs2 = this.uvs2;
  37489. }
  37490. if (this.uvs3) {
  37491. serializationObject.uvs3 = this.uvs3;
  37492. }
  37493. if (this.uvs4) {
  37494. serializationObject.uvs4 = this.uvs4;
  37495. }
  37496. if (this.uvs5) {
  37497. serializationObject.uvs5 = this.uvs5;
  37498. }
  37499. if (this.uvs6) {
  37500. serializationObject.uvs6 = this.uvs6;
  37501. }
  37502. if (this.colors) {
  37503. serializationObject.colors = this.colors;
  37504. }
  37505. if (this.matricesIndices) {
  37506. serializationObject.matricesIndices = this.matricesIndices;
  37507. serializationObject.matricesIndices._isExpanded = true;
  37508. }
  37509. if (this.matricesWeights) {
  37510. serializationObject.matricesWeights = this.matricesWeights;
  37511. }
  37512. if (this.matricesIndicesExtra) {
  37513. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37514. serializationObject.matricesIndicesExtra._isExpanded = true;
  37515. }
  37516. if (this.matricesWeightsExtra) {
  37517. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37518. }
  37519. serializationObject.indices = this.indices;
  37520. return serializationObject;
  37521. };
  37522. // Statics
  37523. /**
  37524. * Extracts the vertexData from a mesh
  37525. * @param mesh the mesh from which to extract the VertexData
  37526. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37527. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37528. * @returns the object VertexData associated to the passed mesh
  37529. */
  37530. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37531. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37532. };
  37533. /**
  37534. * Extracts the vertexData from the geometry
  37535. * @param geometry the geometry from which to extract the VertexData
  37536. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37537. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37538. * @returns the object VertexData associated to the passed mesh
  37539. */
  37540. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37541. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37542. };
  37543. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37544. var result = new VertexData();
  37545. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37546. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37547. }
  37548. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37549. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37550. }
  37551. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37552. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37553. }
  37554. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37555. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37556. }
  37557. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37558. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37559. }
  37560. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37561. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37562. }
  37563. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37564. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37565. }
  37566. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37567. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37568. }
  37569. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37570. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37571. }
  37572. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37573. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37574. }
  37575. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37576. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37577. }
  37578. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37579. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37580. }
  37581. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37582. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37583. }
  37584. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37585. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37586. }
  37587. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  37588. return result;
  37589. };
  37590. /**
  37591. * Creates the VertexData for a Ribbon
  37592. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37593. * * pathArray array of paths, each of which an array of successive Vector3
  37594. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37595. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37596. * * 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
  37597. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37598. * * 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)
  37599. * * 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)
  37600. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37601. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37602. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37603. * @returns the VertexData of the ribbon
  37604. */
  37605. VertexData.CreateRibbon = function (options) {
  37606. var pathArray = options.pathArray;
  37607. var closeArray = options.closeArray || false;
  37608. var closePath = options.closePath || false;
  37609. var invertUV = options.invertUV || false;
  37610. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37611. var offset = options.offset || defaultOffset;
  37612. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37613. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37614. var customUV = options.uvs;
  37615. var customColors = options.colors;
  37616. var positions = [];
  37617. var indices = [];
  37618. var normals = [];
  37619. var uvs = [];
  37620. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37621. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37622. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37623. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37624. var minlg; // minimal length among all paths from pathArray
  37625. var lg = []; // array of path lengths : nb of vertex per path
  37626. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37627. var p; // path iterator
  37628. var i; // point iterator
  37629. var j; // point iterator
  37630. // if single path in pathArray
  37631. if (pathArray.length < 2) {
  37632. var ar1 = [];
  37633. var ar2 = [];
  37634. for (i = 0; i < pathArray[0].length - offset; i++) {
  37635. ar1.push(pathArray[0][i]);
  37636. ar2.push(pathArray[0][i + offset]);
  37637. }
  37638. pathArray = [ar1, ar2];
  37639. }
  37640. // positions and horizontal distances (u)
  37641. var idc = 0;
  37642. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37643. var path;
  37644. var l;
  37645. minlg = pathArray[0].length;
  37646. var vectlg;
  37647. var dist;
  37648. for (p = 0; p < pathArray.length; p++) {
  37649. uTotalDistance[p] = 0;
  37650. us[p] = [0];
  37651. path = pathArray[p];
  37652. l = path.length;
  37653. minlg = (minlg < l) ? minlg : l;
  37654. j = 0;
  37655. while (j < l) {
  37656. positions.push(path[j].x, path[j].y, path[j].z);
  37657. if (j > 0) {
  37658. vectlg = path[j].subtract(path[j - 1]).length();
  37659. dist = vectlg + uTotalDistance[p];
  37660. us[p].push(dist);
  37661. uTotalDistance[p] = dist;
  37662. }
  37663. j++;
  37664. }
  37665. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37666. j--;
  37667. positions.push(path[0].x, path[0].y, path[0].z);
  37668. vectlg = path[j].subtract(path[0]).length();
  37669. dist = vectlg + uTotalDistance[p];
  37670. us[p].push(dist);
  37671. uTotalDistance[p] = dist;
  37672. }
  37673. lg[p] = l + closePathCorr;
  37674. idx[p] = idc;
  37675. idc += (l + closePathCorr);
  37676. }
  37677. // vertical distances (v)
  37678. var path1;
  37679. var path2;
  37680. var vertex1 = null;
  37681. var vertex2 = null;
  37682. for (i = 0; i < minlg + closePathCorr; i++) {
  37683. vTotalDistance[i] = 0;
  37684. vs[i] = [0];
  37685. for (p = 0; p < pathArray.length - 1; p++) {
  37686. path1 = pathArray[p];
  37687. path2 = pathArray[p + 1];
  37688. if (i === minlg) { // closePath
  37689. vertex1 = path1[0];
  37690. vertex2 = path2[0];
  37691. }
  37692. else {
  37693. vertex1 = path1[i];
  37694. vertex2 = path2[i];
  37695. }
  37696. vectlg = vertex2.subtract(vertex1).length();
  37697. dist = vectlg + vTotalDistance[i];
  37698. vs[i].push(dist);
  37699. vTotalDistance[i] = dist;
  37700. }
  37701. if (closeArray && vertex2 && vertex1) {
  37702. path1 = pathArray[p];
  37703. path2 = pathArray[0];
  37704. if (i === minlg) { // closePath
  37705. vertex2 = path2[0];
  37706. }
  37707. vectlg = vertex2.subtract(vertex1).length();
  37708. dist = vectlg + vTotalDistance[i];
  37709. vTotalDistance[i] = dist;
  37710. }
  37711. }
  37712. // uvs
  37713. var u;
  37714. var v;
  37715. if (customUV) {
  37716. for (p = 0; p < customUV.length; p++) {
  37717. uvs.push(customUV[p].x, customUV[p].y);
  37718. }
  37719. }
  37720. else {
  37721. for (p = 0; p < pathArray.length; p++) {
  37722. for (i = 0; i < minlg + closePathCorr; i++) {
  37723. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37724. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37725. if (invertUV) {
  37726. uvs.push(v, u);
  37727. }
  37728. else {
  37729. uvs.push(u, v);
  37730. }
  37731. }
  37732. }
  37733. }
  37734. // indices
  37735. p = 0; // path index
  37736. var pi = 0; // positions array index
  37737. var l1 = lg[p] - 1; // path1 length
  37738. var l2 = lg[p + 1] - 1; // path2 length
  37739. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37740. var shft = idx[1] - idx[0]; // shift
  37741. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37742. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37743. // 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
  37744. indices.push(pi, pi + shft, pi + 1);
  37745. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37746. pi += 1;
  37747. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37748. p++;
  37749. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37750. shft = idx[0] - idx[p];
  37751. l1 = lg[p] - 1;
  37752. l2 = lg[0] - 1;
  37753. }
  37754. else {
  37755. shft = idx[p + 1] - idx[p];
  37756. l1 = lg[p] - 1;
  37757. l2 = lg[p + 1] - 1;
  37758. }
  37759. pi = idx[p];
  37760. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37761. }
  37762. }
  37763. // normals
  37764. VertexData.ComputeNormals(positions, indices, normals);
  37765. if (closePath) { // update both the first and last vertex normals to their average value
  37766. var indexFirst = 0;
  37767. var indexLast = 0;
  37768. for (p = 0; p < pathArray.length; p++) {
  37769. indexFirst = idx[p] * 3;
  37770. if (p + 1 < pathArray.length) {
  37771. indexLast = (idx[p + 1] - 1) * 3;
  37772. }
  37773. else {
  37774. indexLast = normals.length - 3;
  37775. }
  37776. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37777. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37778. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37779. normals[indexLast] = normals[indexFirst];
  37780. normals[indexLast + 1] = normals[indexFirst + 1];
  37781. normals[indexLast + 2] = normals[indexFirst + 2];
  37782. }
  37783. }
  37784. // sides
  37785. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37786. // Colors
  37787. var colors = null;
  37788. if (customColors) {
  37789. colors = new Float32Array(customColors.length * 4);
  37790. for (var c = 0; c < customColors.length; c++) {
  37791. colors[c * 4] = customColors[c].r;
  37792. colors[c * 4 + 1] = customColors[c].g;
  37793. colors[c * 4 + 2] = customColors[c].b;
  37794. colors[c * 4 + 3] = customColors[c].a;
  37795. }
  37796. }
  37797. // Result
  37798. var vertexData = new VertexData();
  37799. var positions32 = new Float32Array(positions);
  37800. var normals32 = new Float32Array(normals);
  37801. var uvs32 = new Float32Array(uvs);
  37802. vertexData.indices = indices;
  37803. vertexData.positions = positions32;
  37804. vertexData.normals = normals32;
  37805. vertexData.uvs = uvs32;
  37806. if (colors) {
  37807. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37808. }
  37809. if (closePath) {
  37810. vertexData._idx = idx;
  37811. }
  37812. return vertexData;
  37813. };
  37814. /**
  37815. * Creates the VertexData for a box
  37816. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37817. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37818. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37819. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37820. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37821. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37822. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37823. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37824. * * 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)
  37825. * * 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)
  37826. * @returns the VertexData of the box
  37827. */
  37828. VertexData.CreateBox = function (options) {
  37829. var normalsSource = [
  37830. new BABYLON.Vector3(0, 0, 1),
  37831. new BABYLON.Vector3(0, 0, -1),
  37832. new BABYLON.Vector3(1, 0, 0),
  37833. new BABYLON.Vector3(-1, 0, 0),
  37834. new BABYLON.Vector3(0, 1, 0),
  37835. new BABYLON.Vector3(0, -1, 0)
  37836. ];
  37837. var indices = [];
  37838. var positions = [];
  37839. var normals = [];
  37840. var uvs = [];
  37841. var width = options.width || options.size || 1;
  37842. var height = options.height || options.size || 1;
  37843. var depth = options.depth || options.size || 1;
  37844. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37845. var faceUV = options.faceUV || new Array(6);
  37846. var faceColors = options.faceColors;
  37847. var colors = [];
  37848. // default face colors and UV if undefined
  37849. for (var f = 0; f < 6; f++) {
  37850. if (faceUV[f] === undefined) {
  37851. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37852. }
  37853. if (faceColors && faceColors[f] === undefined) {
  37854. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37855. }
  37856. }
  37857. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37858. // Create each face in turn.
  37859. for (var index = 0; index < normalsSource.length; index++) {
  37860. var normal = normalsSource[index];
  37861. // Get two vectors perpendicular to the face normal and to each other.
  37862. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37863. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37864. // Six indices (two triangles) per face.
  37865. var verticesLength = positions.length / 3;
  37866. indices.push(verticesLength);
  37867. indices.push(verticesLength + 1);
  37868. indices.push(verticesLength + 2);
  37869. indices.push(verticesLength);
  37870. indices.push(verticesLength + 2);
  37871. indices.push(verticesLength + 3);
  37872. // Four vertices per face.
  37873. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37874. positions.push(vertex.x, vertex.y, vertex.z);
  37875. normals.push(normal.x, normal.y, normal.z);
  37876. uvs.push(faceUV[index].z, faceUV[index].w);
  37877. if (faceColors) {
  37878. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37879. }
  37880. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37881. positions.push(vertex.x, vertex.y, vertex.z);
  37882. normals.push(normal.x, normal.y, normal.z);
  37883. uvs.push(faceUV[index].x, faceUV[index].w);
  37884. if (faceColors) {
  37885. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37886. }
  37887. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37888. positions.push(vertex.x, vertex.y, vertex.z);
  37889. normals.push(normal.x, normal.y, normal.z);
  37890. uvs.push(faceUV[index].x, faceUV[index].y);
  37891. if (faceColors) {
  37892. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37893. }
  37894. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37895. positions.push(vertex.x, vertex.y, vertex.z);
  37896. normals.push(normal.x, normal.y, normal.z);
  37897. uvs.push(faceUV[index].z, faceUV[index].y);
  37898. if (faceColors) {
  37899. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37900. }
  37901. }
  37902. // sides
  37903. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37904. // Result
  37905. var vertexData = new VertexData();
  37906. vertexData.indices = indices;
  37907. vertexData.positions = positions;
  37908. vertexData.normals = normals;
  37909. vertexData.uvs = uvs;
  37910. if (faceColors) {
  37911. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37912. vertexData.colors = totalColors;
  37913. }
  37914. return vertexData;
  37915. };
  37916. /**
  37917. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37918. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37919. * * segments sets the number of horizontal strips optional, default 32
  37920. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37921. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37922. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37923. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37924. * * 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
  37925. * * 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
  37926. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37927. * * 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)
  37928. * * 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)
  37929. * @returns the VertexData of the ellipsoid
  37930. */
  37931. VertexData.CreateSphere = function (options) {
  37932. var segments = options.segments || 32;
  37933. var diameterX = options.diameterX || options.diameter || 1;
  37934. var diameterY = options.diameterY || options.diameter || 1;
  37935. var diameterZ = options.diameterZ || options.diameter || 1;
  37936. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37937. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37938. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37939. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37940. var totalZRotationSteps = 2 + segments;
  37941. var totalYRotationSteps = 2 * totalZRotationSteps;
  37942. var indices = [];
  37943. var positions = [];
  37944. var normals = [];
  37945. var uvs = [];
  37946. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37947. var normalizedZ = zRotationStep / totalZRotationSteps;
  37948. var angleZ = normalizedZ * Math.PI * slice;
  37949. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37950. var normalizedY = yRotationStep / totalYRotationSteps;
  37951. var angleY = normalizedY * Math.PI * 2 * arc;
  37952. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37953. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37954. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37955. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37956. var vertex = complete.multiply(radius);
  37957. var normal = complete.divide(radius).normalize();
  37958. positions.push(vertex.x, vertex.y, vertex.z);
  37959. normals.push(normal.x, normal.y, normal.z);
  37960. uvs.push(normalizedY, normalizedZ);
  37961. }
  37962. if (zRotationStep > 0) {
  37963. var verticesCount = positions.length / 3;
  37964. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37965. indices.push((firstIndex));
  37966. indices.push((firstIndex + 1));
  37967. indices.push(firstIndex + totalYRotationSteps + 1);
  37968. indices.push((firstIndex + totalYRotationSteps + 1));
  37969. indices.push((firstIndex + 1));
  37970. indices.push((firstIndex + totalYRotationSteps + 2));
  37971. }
  37972. }
  37973. }
  37974. // Sides
  37975. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37976. // Result
  37977. var vertexData = new VertexData();
  37978. vertexData.indices = indices;
  37979. vertexData.positions = positions;
  37980. vertexData.normals = normals;
  37981. vertexData.uvs = uvs;
  37982. return vertexData;
  37983. };
  37984. /**
  37985. * Creates the VertexData for a cylinder, cone or prism
  37986. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37987. * * height sets the height (y direction) of the cylinder, optional, default 2
  37988. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37989. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37990. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37991. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37992. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37993. * * 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
  37994. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37995. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37996. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37997. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37998. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37999. * * 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)
  38000. * * 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)
  38001. * @returns the VertexData of the cylinder, cone or prism
  38002. */
  38003. VertexData.CreateCylinder = function (options) {
  38004. var height = options.height || 2;
  38005. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38006. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38007. var tessellation = options.tessellation || 24;
  38008. var subdivisions = options.subdivisions || 1;
  38009. var hasRings = options.hasRings ? true : false;
  38010. var enclose = options.enclose ? true : false;
  38011. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38013. var faceUV = options.faceUV || new Array(3);
  38014. var faceColors = options.faceColors;
  38015. // default face colors and UV if undefined
  38016. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38017. var ringNb = (hasRings) ? subdivisions : 1;
  38018. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38019. var f;
  38020. for (f = 0; f < surfaceNb; f++) {
  38021. if (faceColors && faceColors[f] === undefined) {
  38022. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38023. }
  38024. }
  38025. for (f = 0; f < surfaceNb; f++) {
  38026. if (faceUV && faceUV[f] === undefined) {
  38027. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38028. }
  38029. }
  38030. var indices = new Array();
  38031. var positions = new Array();
  38032. var normals = new Array();
  38033. var uvs = new Array();
  38034. var colors = new Array();
  38035. var angle_step = Math.PI * 2 * arc / tessellation;
  38036. var angle;
  38037. var h;
  38038. var radius;
  38039. var tan = (diameterBottom - diameterTop) / 2 / height;
  38040. var ringVertex = BABYLON.Vector3.Zero();
  38041. var ringNormal = BABYLON.Vector3.Zero();
  38042. var ringFirstVertex = BABYLON.Vector3.Zero();
  38043. var ringFirstNormal = BABYLON.Vector3.Zero();
  38044. var quadNormal = BABYLON.Vector3.Zero();
  38045. var Y = BABYLON.Axis.Y;
  38046. // positions, normals, uvs
  38047. var i;
  38048. var j;
  38049. var r;
  38050. var ringIdx = 1;
  38051. var s = 1; // surface index
  38052. var cs = 0;
  38053. var v = 0;
  38054. for (i = 0; i <= subdivisions; i++) {
  38055. h = i / subdivisions;
  38056. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38057. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38058. for (r = 0; r < ringIdx; r++) {
  38059. if (hasRings) {
  38060. s += r;
  38061. }
  38062. if (enclose) {
  38063. s += 2 * r;
  38064. }
  38065. for (j = 0; j <= tessellation; j++) {
  38066. angle = j * angle_step;
  38067. // position
  38068. ringVertex.x = Math.cos(-angle) * radius;
  38069. ringVertex.y = -height / 2 + h * height;
  38070. ringVertex.z = Math.sin(-angle) * radius;
  38071. // normal
  38072. if (diameterTop === 0 && i === subdivisions) {
  38073. // if no top cap, reuse former normals
  38074. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38075. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38076. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38077. }
  38078. else {
  38079. ringNormal.x = ringVertex.x;
  38080. ringNormal.z = ringVertex.z;
  38081. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38082. ringNormal.normalize();
  38083. }
  38084. // keep first ring vertex values for enclose
  38085. if (j === 0) {
  38086. ringFirstVertex.copyFrom(ringVertex);
  38087. ringFirstNormal.copyFrom(ringNormal);
  38088. }
  38089. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38090. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38091. if (hasRings) {
  38092. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38093. }
  38094. else {
  38095. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38096. }
  38097. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38098. if (faceColors) {
  38099. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38100. }
  38101. }
  38102. // if enclose, add four vertices and their dedicated normals
  38103. if (arc !== 1 && enclose) {
  38104. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38105. positions.push(0, ringVertex.y, 0);
  38106. positions.push(0, ringVertex.y, 0);
  38107. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38108. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38109. quadNormal.normalize();
  38110. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38111. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38112. quadNormal.normalize();
  38113. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38114. if (hasRings) {
  38115. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38116. }
  38117. else {
  38118. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38119. }
  38120. uvs.push(faceUV[s + 1].x, v);
  38121. uvs.push(faceUV[s + 1].z, v);
  38122. if (hasRings) {
  38123. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38124. }
  38125. else {
  38126. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38127. }
  38128. uvs.push(faceUV[s + 2].x, v);
  38129. uvs.push(faceUV[s + 2].z, v);
  38130. if (faceColors) {
  38131. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38132. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38133. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38134. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38135. }
  38136. }
  38137. if (cs !== s) {
  38138. cs = s;
  38139. }
  38140. }
  38141. }
  38142. // indices
  38143. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38144. var s;
  38145. i = 0;
  38146. for (s = 0; s < subdivisions; s++) {
  38147. var i0 = 0;
  38148. var i1 = 0;
  38149. var i2 = 0;
  38150. var i3 = 0;
  38151. for (j = 0; j < tessellation; j++) {
  38152. i0 = i * (e + 1) + j;
  38153. i1 = (i + 1) * (e + 1) + j;
  38154. i2 = i * (e + 1) + (j + 1);
  38155. i3 = (i + 1) * (e + 1) + (j + 1);
  38156. indices.push(i0, i1, i2);
  38157. indices.push(i3, i2, i1);
  38158. }
  38159. if (arc !== 1 && enclose) { // if enclose, add two quads
  38160. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38161. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38162. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38163. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38164. }
  38165. i = (hasRings) ? (i + 2) : (i + 1);
  38166. }
  38167. // Caps
  38168. var createCylinderCap = function (isTop) {
  38169. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38170. if (radius === 0) {
  38171. return;
  38172. }
  38173. // Cap positions, normals & uvs
  38174. var angle;
  38175. var circleVector;
  38176. var i;
  38177. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38178. var c = null;
  38179. if (faceColors) {
  38180. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38181. }
  38182. // cap center
  38183. var vbase = positions.length / 3;
  38184. var offset = isTop ? height / 2 : -height / 2;
  38185. var center = new BABYLON.Vector3(0, offset, 0);
  38186. positions.push(center.x, center.y, center.z);
  38187. normals.push(0, isTop ? 1 : -1, 0);
  38188. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38189. if (c) {
  38190. colors.push(c.r, c.g, c.b, c.a);
  38191. }
  38192. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38193. for (i = 0; i <= tessellation; i++) {
  38194. angle = Math.PI * 2 * i * arc / tessellation;
  38195. var cos = Math.cos(-angle);
  38196. var sin = Math.sin(-angle);
  38197. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38198. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38199. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38200. normals.push(0, isTop ? 1 : -1, 0);
  38201. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38202. if (c) {
  38203. colors.push(c.r, c.g, c.b, c.a);
  38204. }
  38205. }
  38206. // Cap indices
  38207. for (i = 0; i < tessellation; i++) {
  38208. if (!isTop) {
  38209. indices.push(vbase);
  38210. indices.push(vbase + (i + 1));
  38211. indices.push(vbase + (i + 2));
  38212. }
  38213. else {
  38214. indices.push(vbase);
  38215. indices.push(vbase + (i + 2));
  38216. indices.push(vbase + (i + 1));
  38217. }
  38218. }
  38219. };
  38220. // add caps to geometry
  38221. createCylinderCap(false);
  38222. createCylinderCap(true);
  38223. // Sides
  38224. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38225. var vertexData = new VertexData();
  38226. vertexData.indices = indices;
  38227. vertexData.positions = positions;
  38228. vertexData.normals = normals;
  38229. vertexData.uvs = uvs;
  38230. if (faceColors) {
  38231. vertexData.colors = colors;
  38232. }
  38233. return vertexData;
  38234. };
  38235. /**
  38236. * Creates the VertexData for a torus
  38237. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38238. * * diameter the diameter of the torus, optional default 1
  38239. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38240. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38241. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38242. * * 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)
  38243. * * 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)
  38244. * @returns the VertexData of the torus
  38245. */
  38246. VertexData.CreateTorus = function (options) {
  38247. var indices = [];
  38248. var positions = [];
  38249. var normals = [];
  38250. var uvs = [];
  38251. var diameter = options.diameter || 1;
  38252. var thickness = options.thickness || 0.5;
  38253. var tessellation = options.tessellation || 16;
  38254. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38255. var stride = tessellation + 1;
  38256. for (var i = 0; i <= tessellation; i++) {
  38257. var u = i / tessellation;
  38258. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38259. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38260. for (var j = 0; j <= tessellation; j++) {
  38261. var v = 1 - j / tessellation;
  38262. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38263. var dx = Math.cos(innerAngle);
  38264. var dy = Math.sin(innerAngle);
  38265. // Create a vertex.
  38266. var normal = new BABYLON.Vector3(dx, dy, 0);
  38267. var position = normal.scale(thickness / 2);
  38268. var textureCoordinate = new BABYLON.Vector2(u, v);
  38269. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38270. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38271. positions.push(position.x, position.y, position.z);
  38272. normals.push(normal.x, normal.y, normal.z);
  38273. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38274. // And create indices for two triangles.
  38275. var nextI = (i + 1) % stride;
  38276. var nextJ = (j + 1) % stride;
  38277. indices.push(i * stride + j);
  38278. indices.push(i * stride + nextJ);
  38279. indices.push(nextI * stride + j);
  38280. indices.push(i * stride + nextJ);
  38281. indices.push(nextI * stride + nextJ);
  38282. indices.push(nextI * stride + j);
  38283. }
  38284. }
  38285. // Sides
  38286. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38287. // Result
  38288. var vertexData = new VertexData();
  38289. vertexData.indices = indices;
  38290. vertexData.positions = positions;
  38291. vertexData.normals = normals;
  38292. vertexData.uvs = uvs;
  38293. return vertexData;
  38294. };
  38295. /**
  38296. * Creates the VertexData of the LineSystem
  38297. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38298. * - lines an array of lines, each line being an array of successive Vector3
  38299. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38300. * @returns the VertexData of the LineSystem
  38301. */
  38302. VertexData.CreateLineSystem = function (options) {
  38303. var indices = [];
  38304. var positions = [];
  38305. var lines = options.lines;
  38306. var colors = options.colors;
  38307. var vertexColors = [];
  38308. var idx = 0;
  38309. for (var l = 0; l < lines.length; l++) {
  38310. var points = lines[l];
  38311. for (var index = 0; index < points.length; index++) {
  38312. positions.push(points[index].x, points[index].y, points[index].z);
  38313. if (colors) {
  38314. var color = colors[l];
  38315. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38316. }
  38317. if (index > 0) {
  38318. indices.push(idx - 1);
  38319. indices.push(idx);
  38320. }
  38321. idx++;
  38322. }
  38323. }
  38324. var vertexData = new VertexData();
  38325. vertexData.indices = indices;
  38326. vertexData.positions = positions;
  38327. if (colors) {
  38328. vertexData.colors = vertexColors;
  38329. }
  38330. return vertexData;
  38331. };
  38332. /**
  38333. * Create the VertexData for a DashedLines
  38334. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38335. * - points an array successive Vector3
  38336. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38337. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38338. * - dashNb the intended total number of dashes, optional, default 200
  38339. * @returns the VertexData for the DashedLines
  38340. */
  38341. VertexData.CreateDashedLines = function (options) {
  38342. var dashSize = options.dashSize || 3;
  38343. var gapSize = options.gapSize || 1;
  38344. var dashNb = options.dashNb || 200;
  38345. var points = options.points;
  38346. var positions = new Array();
  38347. var indices = new Array();
  38348. var curvect = BABYLON.Vector3.Zero();
  38349. var lg = 0;
  38350. var nb = 0;
  38351. var shft = 0;
  38352. var dashshft = 0;
  38353. var curshft = 0;
  38354. var idx = 0;
  38355. var i = 0;
  38356. for (i = 0; i < points.length - 1; i++) {
  38357. points[i + 1].subtractToRef(points[i], curvect);
  38358. lg += curvect.length();
  38359. }
  38360. shft = lg / dashNb;
  38361. dashshft = dashSize * shft / (dashSize + gapSize);
  38362. for (i = 0; i < points.length - 1; i++) {
  38363. points[i + 1].subtractToRef(points[i], curvect);
  38364. nb = Math.floor(curvect.length() / shft);
  38365. curvect.normalize();
  38366. for (var j = 0; j < nb; j++) {
  38367. curshft = shft * j;
  38368. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38369. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38370. indices.push(idx, idx + 1);
  38371. idx += 2;
  38372. }
  38373. }
  38374. // Result
  38375. var vertexData = new VertexData();
  38376. vertexData.positions = positions;
  38377. vertexData.indices = indices;
  38378. return vertexData;
  38379. };
  38380. /**
  38381. * Creates the VertexData for a Ground
  38382. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38383. * - width the width (x direction) of the ground, optional, default 1
  38384. * - height the height (z direction) of the ground, optional, default 1
  38385. * - subdivisions the number of subdivisions per side, optional, default 1
  38386. * @returns the VertexData of the Ground
  38387. */
  38388. VertexData.CreateGround = function (options) {
  38389. var indices = [];
  38390. var positions = [];
  38391. var normals = [];
  38392. var uvs = [];
  38393. var row, col;
  38394. var width = options.width || 1;
  38395. var height = options.height || 1;
  38396. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38397. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38398. for (row = 0; row <= subdivisionsY; row++) {
  38399. for (col = 0; col <= subdivisionsX; col++) {
  38400. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38401. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38402. positions.push(position.x, position.y, position.z);
  38403. normals.push(normal.x, normal.y, normal.z);
  38404. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38405. }
  38406. }
  38407. for (row = 0; row < subdivisionsY; row++) {
  38408. for (col = 0; col < subdivisionsX; col++) {
  38409. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38410. indices.push(col + 1 + row * (subdivisionsX + 1));
  38411. indices.push(col + row * (subdivisionsX + 1));
  38412. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38413. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38414. indices.push(col + row * (subdivisionsX + 1));
  38415. }
  38416. }
  38417. // Result
  38418. var vertexData = new VertexData();
  38419. vertexData.indices = indices;
  38420. vertexData.positions = positions;
  38421. vertexData.normals = normals;
  38422. vertexData.uvs = uvs;
  38423. return vertexData;
  38424. };
  38425. /**
  38426. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38427. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38428. * * xmin the ground minimum X coordinate, optional, default -1
  38429. * * zmin the ground minimum Z coordinate, optional, default -1
  38430. * * xmax the ground maximum X coordinate, optional, default 1
  38431. * * zmax the ground maximum Z coordinate, optional, default 1
  38432. * * 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}
  38433. * * 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}
  38434. * @returns the VertexData of the TiledGround
  38435. */
  38436. VertexData.CreateTiledGround = function (options) {
  38437. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38438. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38439. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38440. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38441. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38442. var precision = options.precision || { w: 1, h: 1 };
  38443. var indices = new Array();
  38444. var positions = new Array();
  38445. var normals = new Array();
  38446. var uvs = new Array();
  38447. var row, col, tileRow, tileCol;
  38448. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38449. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38450. precision.w = (precision.w < 1) ? 1 : precision.w;
  38451. precision.h = (precision.h < 1) ? 1 : precision.h;
  38452. var tileSize = {
  38453. 'w': (xmax - xmin) / subdivisions.w,
  38454. 'h': (zmax - zmin) / subdivisions.h
  38455. };
  38456. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38457. // Indices
  38458. var base = positions.length / 3;
  38459. var rowLength = precision.w + 1;
  38460. for (row = 0; row < precision.h; row++) {
  38461. for (col = 0; col < precision.w; col++) {
  38462. var square = [
  38463. base + col + row * rowLength,
  38464. base + (col + 1) + row * rowLength,
  38465. base + (col + 1) + (row + 1) * rowLength,
  38466. base + col + (row + 1) * rowLength
  38467. ];
  38468. indices.push(square[1]);
  38469. indices.push(square[2]);
  38470. indices.push(square[3]);
  38471. indices.push(square[0]);
  38472. indices.push(square[1]);
  38473. indices.push(square[3]);
  38474. }
  38475. }
  38476. // Position, normals and uvs
  38477. var position = BABYLON.Vector3.Zero();
  38478. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38479. for (row = 0; row <= precision.h; row++) {
  38480. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38481. for (col = 0; col <= precision.w; col++) {
  38482. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38483. position.y = 0;
  38484. positions.push(position.x, position.y, position.z);
  38485. normals.push(normal.x, normal.y, normal.z);
  38486. uvs.push(col / precision.w, row / precision.h);
  38487. }
  38488. }
  38489. }
  38490. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38491. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38492. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38493. }
  38494. }
  38495. // Result
  38496. var vertexData = new VertexData();
  38497. vertexData.indices = indices;
  38498. vertexData.positions = positions;
  38499. vertexData.normals = normals;
  38500. vertexData.uvs = uvs;
  38501. return vertexData;
  38502. };
  38503. /**
  38504. * Creates the VertexData of the Ground designed from a heightmap
  38505. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38506. * * width the width (x direction) of the ground
  38507. * * height the height (z direction) of the ground
  38508. * * subdivisions the number of subdivisions per side
  38509. * * minHeight the minimum altitude on the ground, optional, default 0
  38510. * * maxHeight the maximum altitude on the ground, optional default 1
  38511. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38512. * * buffer the array holding the image color data
  38513. * * bufferWidth the width of image
  38514. * * bufferHeight the height of image
  38515. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38516. * @returns the VertexData of the Ground designed from a heightmap
  38517. */
  38518. VertexData.CreateGroundFromHeightMap = function (options) {
  38519. var indices = [];
  38520. var positions = [];
  38521. var normals = [];
  38522. var uvs = [];
  38523. var row, col;
  38524. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38525. var alphaFilter = options.alphaFilter || 0.0;
  38526. // Vertices
  38527. for (row = 0; row <= options.subdivisions; row++) {
  38528. for (col = 0; col <= options.subdivisions; col++) {
  38529. 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));
  38530. // Compute height
  38531. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38532. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38533. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38534. var r = options.buffer[pos] / 255.0;
  38535. var g = options.buffer[pos + 1] / 255.0;
  38536. var b = options.buffer[pos + 2] / 255.0;
  38537. var a = options.buffer[pos + 3] / 255.0;
  38538. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38539. // If our alpha channel is not within our filter then we will assign a 'special' height
  38540. // Then when building the indices, we will ignore any vertex that is using the special height
  38541. if (a >= alphaFilter)
  38542. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38543. else {
  38544. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38545. }
  38546. // Add vertex
  38547. positions.push(position.x, position.y, position.z);
  38548. normals.push(0, 0, 0);
  38549. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38550. }
  38551. }
  38552. // Indices
  38553. for (row = 0; row < options.subdivisions; row++) {
  38554. for (col = 0; col < options.subdivisions; col++) {
  38555. // Calculate Indices
  38556. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38557. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38558. var idx3 = (col + row * (options.subdivisions + 1));
  38559. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38560. // Check that all indices are visible (based on our special height)
  38561. // Only display the vertex if all Indices are visible
  38562. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38563. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38564. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38565. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38566. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38567. indices.push(idx1);
  38568. indices.push(idx2);
  38569. indices.push(idx3);
  38570. }
  38571. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38572. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38573. indices.push(idx4);
  38574. indices.push(idx1);
  38575. indices.push(idx3);
  38576. }
  38577. }
  38578. }
  38579. // Normals
  38580. VertexData.ComputeNormals(positions, indices, normals);
  38581. // Result
  38582. var vertexData = new VertexData();
  38583. vertexData.indices = indices;
  38584. vertexData.positions = positions;
  38585. vertexData.normals = normals;
  38586. vertexData.uvs = uvs;
  38587. return vertexData;
  38588. };
  38589. /**
  38590. * Creates the VertexData for a Plane
  38591. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38592. * * size sets the width and height of the plane to the value of size, optional default 1
  38593. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38594. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38595. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38596. * * 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)
  38597. * * 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)
  38598. * @returns the VertexData of the box
  38599. */
  38600. VertexData.CreatePlane = function (options) {
  38601. var indices = [];
  38602. var positions = [];
  38603. var normals = [];
  38604. var uvs = [];
  38605. var width = options.width || options.size || 1;
  38606. var height = options.height || options.size || 1;
  38607. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38608. // Vertices
  38609. var halfWidth = width / 2.0;
  38610. var halfHeight = height / 2.0;
  38611. positions.push(-halfWidth, -halfHeight, 0);
  38612. normals.push(0, 0, -1.0);
  38613. uvs.push(0.0, 0.0);
  38614. positions.push(halfWidth, -halfHeight, 0);
  38615. normals.push(0, 0, -1.0);
  38616. uvs.push(1.0, 0.0);
  38617. positions.push(halfWidth, halfHeight, 0);
  38618. normals.push(0, 0, -1.0);
  38619. uvs.push(1.0, 1.0);
  38620. positions.push(-halfWidth, halfHeight, 0);
  38621. normals.push(0, 0, -1.0);
  38622. uvs.push(0.0, 1.0);
  38623. // Indices
  38624. indices.push(0);
  38625. indices.push(1);
  38626. indices.push(2);
  38627. indices.push(0);
  38628. indices.push(2);
  38629. indices.push(3);
  38630. // Sides
  38631. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38632. // Result
  38633. var vertexData = new VertexData();
  38634. vertexData.indices = indices;
  38635. vertexData.positions = positions;
  38636. vertexData.normals = normals;
  38637. vertexData.uvs = uvs;
  38638. return vertexData;
  38639. };
  38640. /**
  38641. * Creates the VertexData of the Disc or regular Polygon
  38642. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38643. * * radius the radius of the disc, optional default 0.5
  38644. * * tessellation the number of polygon sides, optional, default 64
  38645. * * 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
  38646. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38647. * * 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)
  38648. * * 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)
  38649. * @returns the VertexData of the box
  38650. */
  38651. VertexData.CreateDisc = function (options) {
  38652. var positions = new Array();
  38653. var indices = new Array();
  38654. var normals = new Array();
  38655. var uvs = new Array();
  38656. var radius = options.radius || 0.5;
  38657. var tessellation = options.tessellation || 64;
  38658. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38659. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38660. // positions and uvs
  38661. positions.push(0, 0, 0); // disc center first
  38662. uvs.push(0.5, 0.5);
  38663. var theta = Math.PI * 2 * arc;
  38664. var step = theta / tessellation;
  38665. for (var a = 0; a < theta; a += step) {
  38666. var x = Math.cos(a);
  38667. var y = Math.sin(a);
  38668. var u = (x + 1) / 2;
  38669. var v = (1 - y) / 2;
  38670. positions.push(radius * x, radius * y, 0);
  38671. uvs.push(u, v);
  38672. }
  38673. if (arc === 1) {
  38674. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38675. uvs.push(uvs[2], uvs[3]);
  38676. }
  38677. //indices
  38678. var vertexNb = positions.length / 3;
  38679. for (var i = 1; i < vertexNb - 1; i++) {
  38680. indices.push(i + 1, 0, i);
  38681. }
  38682. // result
  38683. VertexData.ComputeNormals(positions, indices, normals);
  38684. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38685. var vertexData = new VertexData();
  38686. vertexData.indices = indices;
  38687. vertexData.positions = positions;
  38688. vertexData.normals = normals;
  38689. vertexData.uvs = uvs;
  38690. return vertexData;
  38691. };
  38692. /**
  38693. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38694. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38695. * @param polygon a mesh built from polygonTriangulation.build()
  38696. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38697. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38698. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38699. * @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)
  38700. * @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)
  38701. * @returns the VertexData of the Polygon
  38702. */
  38703. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38704. var faceUV = fUV || new Array(3);
  38705. var faceColors = fColors;
  38706. var colors = [];
  38707. // default face colors and UV if undefined
  38708. for (var f = 0; f < 3; f++) {
  38709. if (faceUV[f] === undefined) {
  38710. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38711. }
  38712. if (faceColors && faceColors[f] === undefined) {
  38713. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38714. }
  38715. }
  38716. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38717. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38718. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38719. var indices = polygon.getIndices();
  38720. // set face colours and textures
  38721. var idx = 0;
  38722. var face = 0;
  38723. for (var index = 0; index < normals.length; index += 3) {
  38724. //Edge Face no. 1
  38725. if (Math.abs(normals[index + 1]) < 0.001) {
  38726. face = 1;
  38727. }
  38728. //Top Face no. 0
  38729. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38730. face = 0;
  38731. }
  38732. //Bottom Face no. 2
  38733. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38734. face = 2;
  38735. }
  38736. idx = index / 3;
  38737. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38738. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38739. if (faceColors) {
  38740. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38741. }
  38742. }
  38743. // sides
  38744. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38745. // Result
  38746. var vertexData = new VertexData();
  38747. vertexData.indices = indices;
  38748. vertexData.positions = positions;
  38749. vertexData.normals = normals;
  38750. vertexData.uvs = uvs;
  38751. if (faceColors) {
  38752. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38753. vertexData.colors = totalColors;
  38754. }
  38755. return vertexData;
  38756. };
  38757. /**
  38758. * Creates the VertexData of the IcoSphere
  38759. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38760. * * radius the radius of the IcoSphere, optional default 1
  38761. * * radiusX allows stretching in the x direction, optional, default radius
  38762. * * radiusY allows stretching in the y direction, optional, default radius
  38763. * * radiusZ allows stretching in the z direction, optional, default radius
  38764. * * flat when true creates a flat shaded mesh, optional, default true
  38765. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38766. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38767. * * 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)
  38768. * * 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)
  38769. * @returns the VertexData of the IcoSphere
  38770. */
  38771. VertexData.CreateIcoSphere = function (options) {
  38772. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38773. var radius = options.radius || 1;
  38774. var flat = (options.flat === undefined) ? true : options.flat;
  38775. var subdivisions = options.subdivisions || 4;
  38776. var radiusX = options.radiusX || radius;
  38777. var radiusY = options.radiusY || radius;
  38778. var radiusZ = options.radiusZ || radius;
  38779. var t = (1 + Math.sqrt(5)) / 2;
  38780. // 12 vertex x,y,z
  38781. var ico_vertices = [
  38782. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38783. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38784. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38785. ];
  38786. // index of 3 vertex makes a face of icopshere
  38787. var ico_indices = [
  38788. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38789. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38790. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38791. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38792. ];
  38793. // vertex for uv have aliased position, not for UV
  38794. var vertices_unalias_id = [
  38795. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38796. // vertex alias
  38797. 0,
  38798. 2,
  38799. 3,
  38800. 3,
  38801. 3,
  38802. 4,
  38803. 7,
  38804. 8,
  38805. 9,
  38806. 9,
  38807. 10,
  38808. 11 // 23: B + 12
  38809. ];
  38810. // uv as integer step (not pixels !)
  38811. var ico_vertexuv = [
  38812. 5, 1, 3, 1, 6, 4, 0, 0,
  38813. 5, 3, 4, 2, 2, 2, 4, 0,
  38814. 2, 0, 1, 1, 6, 0, 6, 2,
  38815. // vertex alias (for same vertex on different faces)
  38816. 0, 4,
  38817. 3, 3,
  38818. 4, 4,
  38819. 3, 1,
  38820. 4, 2,
  38821. 4, 4,
  38822. 0, 2,
  38823. 1, 1,
  38824. 2, 2,
  38825. 3, 3,
  38826. 1, 3,
  38827. 2, 4 // 23: B + 12
  38828. ];
  38829. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38830. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38831. // First island of uv mapping
  38832. // v = 4h 3+ 2
  38833. // v = 3h 9+ 4
  38834. // v = 2h 9+ 5 B
  38835. // v = 1h 9 1 0
  38836. // v = 0h 3 8 7 A
  38837. // u = 0 1 2 3 4 5 6 *a
  38838. // Second island of uv mapping
  38839. // v = 4h 0+ B+ 4+
  38840. // v = 3h A+ 2+
  38841. // v = 2h 7+ 6 3+
  38842. // v = 1h 8+ 3+
  38843. // v = 0h
  38844. // u = 0 1 2 3 4 5 6 *a
  38845. // Face layout on texture UV mapping
  38846. // ============
  38847. // \ 4 /\ 16 / ======
  38848. // \ / \ / /\ 11 /
  38849. // \/ 7 \/ / \ /
  38850. // ======= / 10 \/
  38851. // /\ 17 /\ =======
  38852. // / \ / \ \ 15 /\
  38853. // / 8 \/ 12 \ \ / \
  38854. // ============ \/ 6 \
  38855. // \ 18 /\ ============
  38856. // \ / \ \ 5 /\ 0 /
  38857. // \/ 13 \ \ / \ /
  38858. // ======= \/ 1 \/
  38859. // =============
  38860. // /\ 19 /\ 2 /\
  38861. // / \ / \ / \
  38862. // / 14 \/ 9 \/ 3 \
  38863. // ===================
  38864. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38865. var ustep = 138 / 1024;
  38866. var vstep = 239 / 1024;
  38867. var uoffset = 60 / 1024;
  38868. var voffset = 26 / 1024;
  38869. // Second island should have margin, not to touch the first island
  38870. // avoid any borderline artefact in pixel rounding
  38871. var island_u_offset = -40 / 1024;
  38872. var island_v_offset = +20 / 1024;
  38873. // face is either island 0 or 1 :
  38874. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38875. var island = [
  38876. 0, 0, 0, 0, 1,
  38877. 0, 0, 1, 1, 0,
  38878. 0, 0, 1, 1, 0,
  38879. 0, 1, 1, 1, 0 // 15 - 19
  38880. ];
  38881. var indices = new Array();
  38882. var positions = new Array();
  38883. var normals = new Array();
  38884. var uvs = new Array();
  38885. var current_indice = 0;
  38886. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38887. var face_vertex_pos = new Array(3);
  38888. var face_vertex_uv = new Array(3);
  38889. var v012;
  38890. for (v012 = 0; v012 < 3; v012++) {
  38891. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38892. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38893. }
  38894. // create all with normals
  38895. for (var face = 0; face < 20; face++) {
  38896. // 3 vertex per face
  38897. for (v012 = 0; v012 < 3; v012++) {
  38898. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38899. var v_id = ico_indices[3 * face + v012];
  38900. // vertex have 3D position (x,y,z)
  38901. 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]);
  38902. // Normalize to get normal, then scale to radius
  38903. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38904. // uv Coordinates from vertex ID
  38905. 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);
  38906. }
  38907. // Subdivide the face (interpolate pos, norm, uv)
  38908. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38909. // - norm is linear interpolation of vertex corner normal
  38910. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38911. // - uv is linear interpolation
  38912. //
  38913. // Topology is as below for sub-divide by 2
  38914. // vertex shown as v0,v1,v2
  38915. // interp index is i1 to progress in range [v0,v1[
  38916. // interp index is i2 to progress in range [v0,v2[
  38917. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38918. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38919. //
  38920. //
  38921. // i2 v2
  38922. // ^ ^
  38923. // / / \
  38924. // / / \
  38925. // / / \
  38926. // / / (0,1) \
  38927. // / #---------\
  38928. // / / \ (0,0)'/ \
  38929. // / / \ / \
  38930. // / / \ / \
  38931. // / / (0,0) \ / (1,0) \
  38932. // / #---------#---------\
  38933. // v0 v1
  38934. //
  38935. // --------------------> i1
  38936. //
  38937. // interp of (i1,i2):
  38938. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38939. // along i1 : lerp(x0,x1, i1/(S-i2))
  38940. //
  38941. // centroid of triangle is needed to get help normal computation
  38942. // (c1,c2) are used for centroid location
  38943. var interp_vertex = function (i1, i2, c1, c2) {
  38944. // vertex is interpolated from
  38945. // - face_vertex_pos[0..2]
  38946. // - face_vertex_uv[0..2]
  38947. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38948. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38949. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38950. pos_interp.normalize();
  38951. var vertex_normal;
  38952. if (flat) {
  38953. // in flat mode, recalculate normal as face centroid normal
  38954. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38955. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38956. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38957. }
  38958. else {
  38959. // in smooth mode, recalculate normal from each single vertex position
  38960. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38961. }
  38962. // Vertex normal need correction due to X,Y,Z radius scaling
  38963. vertex_normal.x /= radiusX;
  38964. vertex_normal.y /= radiusY;
  38965. vertex_normal.z /= radiusZ;
  38966. vertex_normal.normalize();
  38967. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38968. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38969. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38970. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38971. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38972. uvs.push(uv_interp.x, uv_interp.y);
  38973. // push each vertex has member of a face
  38974. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38975. indices.push(current_indice);
  38976. current_indice++;
  38977. };
  38978. for (var i2 = 0; i2 < subdivisions; i2++) {
  38979. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38980. // face : (i1,i2) for /\ :
  38981. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38982. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38983. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38984. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38985. if (i1 + i2 + 1 < subdivisions) {
  38986. // face : (i1,i2)' for \/ :
  38987. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38988. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38989. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38990. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38991. }
  38992. }
  38993. }
  38994. }
  38995. // Sides
  38996. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38997. // Result
  38998. var vertexData = new VertexData();
  38999. vertexData.indices = indices;
  39000. vertexData.positions = positions;
  39001. vertexData.normals = normals;
  39002. vertexData.uvs = uvs;
  39003. return vertexData;
  39004. };
  39005. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39006. /**
  39007. * Creates the VertexData for a Polyhedron
  39008. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39009. * * type provided types are:
  39010. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39011. * * 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)
  39012. * * size the size of the IcoSphere, optional default 1
  39013. * * sizeX allows stretching in the x direction, optional, default size
  39014. * * sizeY allows stretching in the y direction, optional, default size
  39015. * * sizeZ allows stretching in the z direction, optional, default size
  39016. * * 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
  39017. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39018. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39019. * * flat when true creates a flat shaded mesh, optional, default true
  39020. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39021. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39022. * * 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)
  39023. * * 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)
  39024. * @returns the VertexData of the Polyhedron
  39025. */
  39026. VertexData.CreatePolyhedron = function (options) {
  39027. // provided polyhedron types :
  39028. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39029. // 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)
  39030. var polyhedra = [];
  39031. 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]] };
  39032. 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]] };
  39033. polyhedra[2] = {
  39034. 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]],
  39035. 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]]
  39036. };
  39037. polyhedra[3] = {
  39038. 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]],
  39039. 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]]
  39040. };
  39041. polyhedra[4] = {
  39042. 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]],
  39043. 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]]
  39044. };
  39045. 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]] };
  39046. 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]] };
  39047. 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]] };
  39048. 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]] };
  39049. 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]] };
  39050. 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]] };
  39051. 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]] };
  39052. 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]] };
  39053. 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]] };
  39054. polyhedra[14] = {
  39055. 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]],
  39056. 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]]
  39057. };
  39058. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39059. var size = options.size;
  39060. var sizeX = options.sizeX || size || 1;
  39061. var sizeY = options.sizeY || size || 1;
  39062. var sizeZ = options.sizeZ || size || 1;
  39063. var data = options.custom || polyhedra[type];
  39064. var nbfaces = data.face.length;
  39065. var faceUV = options.faceUV || new Array(nbfaces);
  39066. var faceColors = options.faceColors;
  39067. var flat = (options.flat === undefined) ? true : options.flat;
  39068. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39069. var positions = new Array();
  39070. var indices = new Array();
  39071. var normals = new Array();
  39072. var uvs = new Array();
  39073. var colors = new Array();
  39074. var index = 0;
  39075. var faceIdx = 0; // face cursor in the array "indexes"
  39076. var indexes = new Array();
  39077. var i = 0;
  39078. var f = 0;
  39079. var u, v, ang, x, y, tmp;
  39080. // default face colors and UV if undefined
  39081. if (flat) {
  39082. for (f = 0; f < nbfaces; f++) {
  39083. if (faceColors && faceColors[f] === undefined) {
  39084. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39085. }
  39086. if (faceUV && faceUV[f] === undefined) {
  39087. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39088. }
  39089. }
  39090. }
  39091. if (!flat) {
  39092. for (i = 0; i < data.vertex.length; i++) {
  39093. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39094. uvs.push(0, 0);
  39095. }
  39096. for (f = 0; f < nbfaces; f++) {
  39097. for (i = 0; i < data.face[f].length - 2; i++) {
  39098. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39099. }
  39100. }
  39101. }
  39102. else {
  39103. for (f = 0; f < nbfaces; f++) {
  39104. var fl = data.face[f].length; // number of vertices of the current face
  39105. ang = 2 * Math.PI / fl;
  39106. x = 0.5 * Math.tan(ang / 2);
  39107. y = 0.5;
  39108. // positions, uvs, colors
  39109. for (i = 0; i < fl; i++) {
  39110. // positions
  39111. 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);
  39112. indexes.push(index);
  39113. index++;
  39114. // uvs
  39115. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39116. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39117. uvs.push(u, v);
  39118. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39119. y = x * Math.sin(ang) + y * Math.cos(ang);
  39120. x = tmp;
  39121. // colors
  39122. if (faceColors) {
  39123. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39124. }
  39125. }
  39126. // indices from indexes
  39127. for (i = 0; i < fl - 2; i++) {
  39128. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39129. }
  39130. faceIdx += fl;
  39131. }
  39132. }
  39133. VertexData.ComputeNormals(positions, indices, normals);
  39134. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39135. var vertexData = new VertexData();
  39136. vertexData.positions = positions;
  39137. vertexData.indices = indices;
  39138. vertexData.normals = normals;
  39139. vertexData.uvs = uvs;
  39140. if (faceColors && flat) {
  39141. vertexData.colors = colors;
  39142. }
  39143. return vertexData;
  39144. };
  39145. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39146. /**
  39147. * Creates the VertexData for a TorusKnot
  39148. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39149. * * radius the radius of the torus knot, optional, default 2
  39150. * * tube the thickness of the tube, optional, default 0.5
  39151. * * radialSegments the number of sides on each tube segments, optional, default 32
  39152. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39153. * * p the number of windings around the z axis, optional, default 2
  39154. * * q the number of windings around the x axis, optional, default 3
  39155. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39156. * * 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)
  39157. * * 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)
  39158. * @returns the VertexData of the Torus Knot
  39159. */
  39160. VertexData.CreateTorusKnot = function (options) {
  39161. var indices = new Array();
  39162. var positions = new Array();
  39163. var normals = new Array();
  39164. var uvs = new Array();
  39165. var radius = options.radius || 2;
  39166. var tube = options.tube || 0.5;
  39167. var radialSegments = options.radialSegments || 32;
  39168. var tubularSegments = options.tubularSegments || 32;
  39169. var p = options.p || 2;
  39170. var q = options.q || 3;
  39171. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39172. // Helper
  39173. var getPos = function (angle) {
  39174. var cu = Math.cos(angle);
  39175. var su = Math.sin(angle);
  39176. var quOverP = q / p * angle;
  39177. var cs = Math.cos(quOverP);
  39178. var tx = radius * (2 + cs) * 0.5 * cu;
  39179. var ty = radius * (2 + cs) * su * 0.5;
  39180. var tz = radius * Math.sin(quOverP) * 0.5;
  39181. return new BABYLON.Vector3(tx, ty, tz);
  39182. };
  39183. // Vertices
  39184. var i;
  39185. var j;
  39186. for (i = 0; i <= radialSegments; i++) {
  39187. var modI = i % radialSegments;
  39188. var u = modI / radialSegments * 2 * p * Math.PI;
  39189. var p1 = getPos(u);
  39190. var p2 = getPos(u + 0.01);
  39191. var tang = p2.subtract(p1);
  39192. var n = p2.add(p1);
  39193. var bitan = BABYLON.Vector3.Cross(tang, n);
  39194. n = BABYLON.Vector3.Cross(bitan, tang);
  39195. bitan.normalize();
  39196. n.normalize();
  39197. for (j = 0; j < tubularSegments; j++) {
  39198. var modJ = j % tubularSegments;
  39199. var v = modJ / tubularSegments * 2 * Math.PI;
  39200. var cx = -tube * Math.cos(v);
  39201. var cy = tube * Math.sin(v);
  39202. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39203. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39204. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39205. uvs.push(i / radialSegments);
  39206. uvs.push(j / tubularSegments);
  39207. }
  39208. }
  39209. for (i = 0; i < radialSegments; i++) {
  39210. for (j = 0; j < tubularSegments; j++) {
  39211. var jNext = (j + 1) % tubularSegments;
  39212. var a = i * tubularSegments + j;
  39213. var b = (i + 1) * tubularSegments + j;
  39214. var c = (i + 1) * tubularSegments + jNext;
  39215. var d = i * tubularSegments + jNext;
  39216. indices.push(d);
  39217. indices.push(b);
  39218. indices.push(a);
  39219. indices.push(d);
  39220. indices.push(c);
  39221. indices.push(b);
  39222. }
  39223. }
  39224. // Normals
  39225. VertexData.ComputeNormals(positions, indices, normals);
  39226. // Sides
  39227. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39228. // Result
  39229. var vertexData = new VertexData();
  39230. vertexData.indices = indices;
  39231. vertexData.positions = positions;
  39232. vertexData.normals = normals;
  39233. vertexData.uvs = uvs;
  39234. return vertexData;
  39235. };
  39236. // Tools
  39237. /**
  39238. * Compute normals for given positions and indices
  39239. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39240. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39241. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39242. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39243. * * facetNormals : optional array of facet normals (vector3)
  39244. * * facetPositions : optional array of facet positions (vector3)
  39245. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39246. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39247. * * bInfo : optional bounding info, required for facetPartitioning computation
  39248. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39249. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39250. * * useRightHandedSystem: optional boolean to for right handed system computation
  39251. * * depthSort : optional boolean to enable the facet depth sort computation
  39252. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39253. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39254. */
  39255. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39256. // temporary scalar variables
  39257. var index = 0; // facet index
  39258. var p1p2x = 0.0; // p1p2 vector x coordinate
  39259. var p1p2y = 0.0; // p1p2 vector y coordinate
  39260. var p1p2z = 0.0; // p1p2 vector z coordinate
  39261. var p3p2x = 0.0; // p3p2 vector x coordinate
  39262. var p3p2y = 0.0; // p3p2 vector y coordinate
  39263. var p3p2z = 0.0; // p3p2 vector z coordinate
  39264. var faceNormalx = 0.0; // facet normal x coordinate
  39265. var faceNormaly = 0.0; // facet normal y coordinate
  39266. var faceNormalz = 0.0; // facet normal z coordinate
  39267. var length = 0.0; // facet normal length before normalization
  39268. var v1x = 0; // vector1 x index in the positions array
  39269. var v1y = 0; // vector1 y index in the positions array
  39270. var v1z = 0; // vector1 z index in the positions array
  39271. var v2x = 0; // vector2 x index in the positions array
  39272. var v2y = 0; // vector2 y index in the positions array
  39273. var v2z = 0; // vector2 z index in the positions array
  39274. var v3x = 0; // vector3 x index in the positions array
  39275. var v3y = 0; // vector3 y index in the positions array
  39276. var v3z = 0; // vector3 z index in the positions array
  39277. var computeFacetNormals = false;
  39278. var computeFacetPositions = false;
  39279. var computeFacetPartitioning = false;
  39280. var computeDepthSort = false;
  39281. var faceNormalSign = 1;
  39282. var ratio = 0;
  39283. var distanceTo = null;
  39284. if (options) {
  39285. computeFacetNormals = (options.facetNormals) ? true : false;
  39286. computeFacetPositions = (options.facetPositions) ? true : false;
  39287. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39288. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39289. ratio = options.ratio || 0;
  39290. computeDepthSort = (options.depthSort) ? true : false;
  39291. distanceTo = (options.distanceTo);
  39292. if (computeDepthSort) {
  39293. if (distanceTo === undefined) {
  39294. distanceTo = BABYLON.Vector3.Zero();
  39295. }
  39296. var depthSortedFacets = options.depthSortedFacets;
  39297. }
  39298. }
  39299. // facetPartitioning reinit if needed
  39300. var xSubRatio = 0;
  39301. var ySubRatio = 0;
  39302. var zSubRatio = 0;
  39303. var subSq = 0;
  39304. if (computeFacetPartitioning && options && options.bbSize) {
  39305. var ox = 0; // X partitioning index for facet position
  39306. var oy = 0; // Y partinioning index for facet position
  39307. var oz = 0; // Z partinioning index for facet position
  39308. var b1x = 0; // X partitioning index for facet v1 vertex
  39309. var b1y = 0; // Y partitioning index for facet v1 vertex
  39310. var b1z = 0; // z partitioning index for facet v1 vertex
  39311. var b2x = 0; // X partitioning index for facet v2 vertex
  39312. var b2y = 0; // Y partitioning index for facet v2 vertex
  39313. var b2z = 0; // Z partitioning index for facet v2 vertex
  39314. var b3x = 0; // X partitioning index for facet v3 vertex
  39315. var b3y = 0; // Y partitioning index for facet v3 vertex
  39316. var b3z = 0; // Z partitioning index for facet v3 vertex
  39317. var block_idx_o = 0; // facet barycenter block index
  39318. var block_idx_v1 = 0; // v1 vertex block index
  39319. var block_idx_v2 = 0; // v2 vertex block index
  39320. var block_idx_v3 = 0; // v3 vertex block index
  39321. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39322. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39323. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39324. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39325. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39326. subSq = options.subDiv.max * options.subDiv.max;
  39327. options.facetPartitioning.length = 0;
  39328. }
  39329. // reset the normals
  39330. for (index = 0; index < positions.length; index++) {
  39331. normals[index] = 0.0;
  39332. }
  39333. // Loop : 1 indice triplet = 1 facet
  39334. var nbFaces = (indices.length / 3) | 0;
  39335. for (index = 0; index < nbFaces; index++) {
  39336. // get the indexes of the coordinates of each vertex of the facet
  39337. v1x = indices[index * 3] * 3;
  39338. v1y = v1x + 1;
  39339. v1z = v1x + 2;
  39340. v2x = indices[index * 3 + 1] * 3;
  39341. v2y = v2x + 1;
  39342. v2z = v2x + 2;
  39343. v3x = indices[index * 3 + 2] * 3;
  39344. v3y = v3x + 1;
  39345. v3z = v3x + 2;
  39346. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39347. p1p2y = positions[v1y] - positions[v2y];
  39348. p1p2z = positions[v1z] - positions[v2z];
  39349. p3p2x = positions[v3x] - positions[v2x];
  39350. p3p2y = positions[v3y] - positions[v2y];
  39351. p3p2z = positions[v3z] - positions[v2z];
  39352. // compute the face normal with the cross product
  39353. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39354. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39355. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39356. // normalize this normal and store it in the array facetData
  39357. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39358. length = (length === 0) ? 1.0 : length;
  39359. faceNormalx /= length;
  39360. faceNormaly /= length;
  39361. faceNormalz /= length;
  39362. if (computeFacetNormals && options) {
  39363. options.facetNormals[index].x = faceNormalx;
  39364. options.facetNormals[index].y = faceNormaly;
  39365. options.facetNormals[index].z = faceNormalz;
  39366. }
  39367. if (computeFacetPositions && options) {
  39368. // compute and the facet barycenter coordinates in the array facetPositions
  39369. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39370. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39371. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39372. }
  39373. if (computeFacetPartitioning && options) {
  39374. // store the facet indexes in arrays in the main facetPartitioning array :
  39375. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39376. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39377. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39378. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39379. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39380. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39381. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39382. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39383. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39384. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39385. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39386. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39387. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39388. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39389. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39390. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39391. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39392. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39393. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39394. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39395. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39396. // push each facet index in each block containing the vertex
  39397. options.facetPartitioning[block_idx_v1].push(index);
  39398. if (block_idx_v2 != block_idx_v1) {
  39399. options.facetPartitioning[block_idx_v2].push(index);
  39400. }
  39401. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39402. options.facetPartitioning[block_idx_v3].push(index);
  39403. }
  39404. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39405. options.facetPartitioning[block_idx_o].push(index);
  39406. }
  39407. }
  39408. if (computeDepthSort && options && options.facetPositions) {
  39409. var dsf = depthSortedFacets[index];
  39410. dsf.ind = index * 3;
  39411. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39412. }
  39413. // compute the normals anyway
  39414. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39415. normals[v1y] += faceNormaly;
  39416. normals[v1z] += faceNormalz;
  39417. normals[v2x] += faceNormalx;
  39418. normals[v2y] += faceNormaly;
  39419. normals[v2z] += faceNormalz;
  39420. normals[v3x] += faceNormalx;
  39421. normals[v3y] += faceNormaly;
  39422. normals[v3z] += faceNormalz;
  39423. }
  39424. // last normalization of each normal
  39425. for (index = 0; index < normals.length / 3; index++) {
  39426. faceNormalx = normals[index * 3];
  39427. faceNormaly = normals[index * 3 + 1];
  39428. faceNormalz = normals[index * 3 + 2];
  39429. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39430. length = (length === 0) ? 1.0 : length;
  39431. faceNormalx /= length;
  39432. faceNormaly /= length;
  39433. faceNormalz /= length;
  39434. normals[index * 3] = faceNormalx;
  39435. normals[index * 3 + 1] = faceNormaly;
  39436. normals[index * 3 + 2] = faceNormalz;
  39437. }
  39438. };
  39439. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39440. var li = indices.length;
  39441. var ln = normals.length;
  39442. var i;
  39443. var n;
  39444. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39445. switch (sideOrientation) {
  39446. case BABYLON.Mesh.FRONTSIDE:
  39447. // nothing changed
  39448. break;
  39449. case BABYLON.Mesh.BACKSIDE:
  39450. var tmp;
  39451. // indices
  39452. for (i = 0; i < li; i += 3) {
  39453. tmp = indices[i];
  39454. indices[i] = indices[i + 2];
  39455. indices[i + 2] = tmp;
  39456. }
  39457. // normals
  39458. for (n = 0; n < ln; n++) {
  39459. normals[n] = -normals[n];
  39460. }
  39461. break;
  39462. case BABYLON.Mesh.DOUBLESIDE:
  39463. // positions
  39464. var lp = positions.length;
  39465. var l = lp / 3;
  39466. for (var p = 0; p < lp; p++) {
  39467. positions[lp + p] = positions[p];
  39468. }
  39469. // indices
  39470. for (i = 0; i < li; i += 3) {
  39471. indices[i + li] = indices[i + 2] + l;
  39472. indices[i + 1 + li] = indices[i + 1] + l;
  39473. indices[i + 2 + li] = indices[i] + l;
  39474. }
  39475. // normals
  39476. for (n = 0; n < ln; n++) {
  39477. normals[ln + n] = -normals[n];
  39478. }
  39479. // uvs
  39480. var lu = uvs.length;
  39481. var u = 0;
  39482. for (u = 0; u < lu; u++) {
  39483. uvs[u + lu] = uvs[u];
  39484. }
  39485. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39486. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39487. u = 0;
  39488. for (i = 0; i < lu / 2; i++) {
  39489. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39490. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39491. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39492. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39493. u += 2;
  39494. }
  39495. break;
  39496. }
  39497. };
  39498. /**
  39499. * Applies VertexData created from the imported parameters to the geometry
  39500. * @param parsedVertexData the parsed data from an imported file
  39501. * @param geometry the geometry to apply the VertexData to
  39502. */
  39503. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39504. var vertexData = new VertexData();
  39505. // positions
  39506. var positions = parsedVertexData.positions;
  39507. if (positions) {
  39508. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39509. }
  39510. // normals
  39511. var normals = parsedVertexData.normals;
  39512. if (normals) {
  39513. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39514. }
  39515. // tangents
  39516. var tangents = parsedVertexData.tangents;
  39517. if (tangents) {
  39518. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39519. }
  39520. // uvs
  39521. var uvs = parsedVertexData.uvs;
  39522. if (uvs) {
  39523. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39524. }
  39525. // uv2s
  39526. var uv2s = parsedVertexData.uv2s;
  39527. if (uv2s) {
  39528. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39529. }
  39530. // uv3s
  39531. var uv3s = parsedVertexData.uv3s;
  39532. if (uv3s) {
  39533. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39534. }
  39535. // uv4s
  39536. var uv4s = parsedVertexData.uv4s;
  39537. if (uv4s) {
  39538. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39539. }
  39540. // uv5s
  39541. var uv5s = parsedVertexData.uv5s;
  39542. if (uv5s) {
  39543. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39544. }
  39545. // uv6s
  39546. var uv6s = parsedVertexData.uv6s;
  39547. if (uv6s) {
  39548. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39549. }
  39550. // colors
  39551. var colors = parsedVertexData.colors;
  39552. if (colors) {
  39553. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39554. }
  39555. // matricesIndices
  39556. var matricesIndices = parsedVertexData.matricesIndices;
  39557. if (matricesIndices) {
  39558. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39559. }
  39560. // matricesWeights
  39561. var matricesWeights = parsedVertexData.matricesWeights;
  39562. if (matricesWeights) {
  39563. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39564. }
  39565. // indices
  39566. var indices = parsedVertexData.indices;
  39567. if (indices) {
  39568. vertexData.indices = indices;
  39569. }
  39570. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39571. };
  39572. return VertexData;
  39573. }());
  39574. BABYLON.VertexData = VertexData;
  39575. })(BABYLON || (BABYLON = {}));
  39576. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39577. var BABYLON;
  39578. (function (BABYLON) {
  39579. /**
  39580. * Class used to store geometry data (vertex buffers + index buffer)
  39581. */
  39582. var Geometry = /** @class */ (function () {
  39583. /**
  39584. * Creates a new geometry
  39585. * @param id defines the unique ID
  39586. * @param scene defines the hosting scene
  39587. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39588. * @param updatable defines if geometry must be updatable (false by default)
  39589. * @param mesh defines the mesh that will be associated with the geometry
  39590. */
  39591. function Geometry(id, scene, vertexData, updatable, mesh) {
  39592. if (updatable === void 0) { updatable = false; }
  39593. if (mesh === void 0) { mesh = null; }
  39594. /**
  39595. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39596. */
  39597. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39598. this._totalVertices = 0;
  39599. this._isDisposed = false;
  39600. this._indexBufferIsUpdatable = false;
  39601. this.id = id;
  39602. this._engine = scene.getEngine();
  39603. this._meshes = [];
  39604. this._scene = scene;
  39605. //Init vertex buffer cache
  39606. this._vertexBuffers = {};
  39607. this._indices = [];
  39608. this._updatable = updatable;
  39609. // vertexData
  39610. if (vertexData) {
  39611. this.setAllVerticesData(vertexData, updatable);
  39612. }
  39613. else {
  39614. this._totalVertices = 0;
  39615. this._indices = [];
  39616. }
  39617. if (this._engine.getCaps().vertexArrayObject) {
  39618. this._vertexArrayObjects = {};
  39619. }
  39620. // applyToMesh
  39621. if (mesh) {
  39622. if (mesh.getClassName() === "LinesMesh") {
  39623. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39624. this._updateExtend();
  39625. }
  39626. this.applyToMesh(mesh);
  39627. mesh.computeWorldMatrix(true);
  39628. }
  39629. }
  39630. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39631. /**
  39632. * 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
  39633. */
  39634. get: function () {
  39635. return this._boundingBias;
  39636. },
  39637. /**
  39638. * 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
  39639. */
  39640. set: function (value) {
  39641. if (this._boundingBias) {
  39642. if (this._boundingBias.equals(value)) {
  39643. return;
  39644. }
  39645. this._boundingBias.copyFrom(value);
  39646. }
  39647. else {
  39648. this._boundingBias = value.clone();
  39649. }
  39650. this._updateBoundingInfo(true, null);
  39651. },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. /**
  39656. * Static function used to attach a new empty geometry to a mesh
  39657. * @param mesh defines the mesh to attach the geometry to
  39658. * @returns the new {BABYLON.Geometry}
  39659. */
  39660. Geometry.CreateGeometryForMesh = function (mesh) {
  39661. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39662. geometry.applyToMesh(mesh);
  39663. return geometry;
  39664. };
  39665. Object.defineProperty(Geometry.prototype, "extend", {
  39666. /**
  39667. * Gets the current extend of the geometry
  39668. */
  39669. get: function () {
  39670. return this._extend;
  39671. },
  39672. enumerable: true,
  39673. configurable: true
  39674. });
  39675. /**
  39676. * Gets the hosting scene
  39677. * @returns the hosting {BABYLON.Scene}
  39678. */
  39679. Geometry.prototype.getScene = function () {
  39680. return this._scene;
  39681. };
  39682. /**
  39683. * Gets the hosting engine
  39684. * @returns the hosting {BABYLON.Engine}
  39685. */
  39686. Geometry.prototype.getEngine = function () {
  39687. return this._engine;
  39688. };
  39689. /**
  39690. * Defines if the geometry is ready to use
  39691. * @returns true if the geometry is ready to be used
  39692. */
  39693. Geometry.prototype.isReady = function () {
  39694. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39695. };
  39696. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39697. /**
  39698. * Gets a value indicating that the geometry should not be serialized
  39699. */
  39700. get: function () {
  39701. for (var index = 0; index < this._meshes.length; index++) {
  39702. if (!this._meshes[index].doNotSerialize) {
  39703. return false;
  39704. }
  39705. }
  39706. return true;
  39707. },
  39708. enumerable: true,
  39709. configurable: true
  39710. });
  39711. /** @hidden */
  39712. Geometry.prototype._rebuild = function () {
  39713. if (this._vertexArrayObjects) {
  39714. this._vertexArrayObjects = {};
  39715. }
  39716. // Index buffer
  39717. if (this._meshes.length !== 0 && this._indices) {
  39718. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39719. }
  39720. // Vertex buffers
  39721. for (var key in this._vertexBuffers) {
  39722. var vertexBuffer = this._vertexBuffers[key];
  39723. vertexBuffer._rebuild();
  39724. }
  39725. };
  39726. /**
  39727. * Affects all geometry data in one call
  39728. * @param vertexData defines the geometry data
  39729. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39730. */
  39731. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39732. vertexData.applyToGeometry(this, updatable);
  39733. this.notifyUpdate();
  39734. };
  39735. /**
  39736. * Set specific vertex data
  39737. * @param kind defines the data kind (Position, normal, etc...)
  39738. * @param data defines the vertex data to use
  39739. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39740. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39741. */
  39742. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39743. if (updatable === void 0) { updatable = false; }
  39744. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39745. this.setVerticesBuffer(buffer);
  39746. };
  39747. /**
  39748. * Removes a specific vertex data
  39749. * @param kind defines the data kind (Position, normal, etc...)
  39750. */
  39751. Geometry.prototype.removeVerticesData = function (kind) {
  39752. if (this._vertexBuffers[kind]) {
  39753. this._vertexBuffers[kind].dispose();
  39754. delete this._vertexBuffers[kind];
  39755. }
  39756. };
  39757. /**
  39758. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39759. * @param buffer defines the vertex buffer to use
  39760. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39761. */
  39762. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39763. if (totalVertices === void 0) { totalVertices = null; }
  39764. var kind = buffer.getKind();
  39765. if (this._vertexBuffers[kind]) {
  39766. this._vertexBuffers[kind].dispose();
  39767. }
  39768. this._vertexBuffers[kind] = buffer;
  39769. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39770. var data = buffer.getData();
  39771. if (totalVertices != null) {
  39772. this._totalVertices = totalVertices;
  39773. }
  39774. else {
  39775. if (data != null) {
  39776. this._totalVertices = data.length / (buffer.byteStride / 4);
  39777. }
  39778. }
  39779. this._updateExtend(data);
  39780. this._resetPointsArrayCache();
  39781. var meshes = this._meshes;
  39782. var numOfMeshes = meshes.length;
  39783. for (var index = 0; index < numOfMeshes; index++) {
  39784. var mesh = meshes[index];
  39785. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39786. mesh._createGlobalSubMesh(false);
  39787. mesh.computeWorldMatrix(true);
  39788. }
  39789. }
  39790. this.notifyUpdate(kind);
  39791. if (this._vertexArrayObjects) {
  39792. this._disposeVertexArrayObjects();
  39793. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39794. }
  39795. };
  39796. /**
  39797. * Update a specific vertex buffer
  39798. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39799. * It will do nothing if the buffer is not updatable
  39800. * @param kind defines the data kind (Position, normal, etc...)
  39801. * @param data defines the data to use
  39802. * @param offset defines the offset in the target buffer where to store the data
  39803. * @param useBytes set to true if the offset is in bytes
  39804. */
  39805. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39806. if (useBytes === void 0) { useBytes = false; }
  39807. var vertexBuffer = this.getVertexBuffer(kind);
  39808. if (!vertexBuffer) {
  39809. return;
  39810. }
  39811. vertexBuffer.updateDirectly(data, offset, useBytes);
  39812. this.notifyUpdate(kind);
  39813. };
  39814. /**
  39815. * Update a specific vertex buffer
  39816. * This function will create a new buffer if the current one is not updatable
  39817. * @param kind defines the data kind (Position, normal, etc...)
  39818. * @param data defines the data to use
  39819. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39820. */
  39821. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39822. if (updateExtends === void 0) { updateExtends = false; }
  39823. var vertexBuffer = this.getVertexBuffer(kind);
  39824. if (!vertexBuffer) {
  39825. return;
  39826. }
  39827. vertexBuffer.update(data);
  39828. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39829. this._updateBoundingInfo(updateExtends, data);
  39830. }
  39831. this.notifyUpdate(kind);
  39832. };
  39833. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39834. if (updateExtends) {
  39835. this._updateExtend(data);
  39836. }
  39837. var meshes = this._meshes;
  39838. var numOfMeshes = meshes.length;
  39839. this._resetPointsArrayCache();
  39840. for (var index = 0; index < numOfMeshes; index++) {
  39841. var mesh = meshes[index];
  39842. if (updateExtends) {
  39843. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39844. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39845. var subMesh = mesh.subMeshes[subIndex];
  39846. subMesh.refreshBoundingInfo();
  39847. }
  39848. }
  39849. }
  39850. };
  39851. /** @hidden */
  39852. Geometry.prototype._bind = function (effect, indexToBind) {
  39853. if (!effect) {
  39854. return;
  39855. }
  39856. if (indexToBind === undefined) {
  39857. indexToBind = this._indexBuffer;
  39858. }
  39859. var vbs = this.getVertexBuffers();
  39860. if (!vbs) {
  39861. return;
  39862. }
  39863. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39864. this._engine.bindBuffers(vbs, indexToBind, effect);
  39865. return;
  39866. }
  39867. // Using VAO
  39868. if (!this._vertexArrayObjects[effect.key]) {
  39869. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39870. }
  39871. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39872. };
  39873. /**
  39874. * Gets total number of vertices
  39875. * @returns the total number of vertices
  39876. */
  39877. Geometry.prototype.getTotalVertices = function () {
  39878. if (!this.isReady()) {
  39879. return 0;
  39880. }
  39881. return this._totalVertices;
  39882. };
  39883. /**
  39884. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39885. * @param kind defines the data kind (Position, normal, etc...)
  39886. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39887. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39888. * @returns a float array containing vertex data
  39889. */
  39890. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39891. var vertexBuffer = this.getVertexBuffer(kind);
  39892. if (!vertexBuffer) {
  39893. return null;
  39894. }
  39895. var data = vertexBuffer.getData();
  39896. if (!data) {
  39897. return null;
  39898. }
  39899. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39900. var count = this._totalVertices * vertexBuffer.getSize();
  39901. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39902. var copy_1 = new Array(count);
  39903. vertexBuffer.forEach(count, function (value, index) {
  39904. copy_1[index] = value;
  39905. });
  39906. return copy_1;
  39907. }
  39908. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39909. if (data instanceof Array) {
  39910. var offset = vertexBuffer.byteOffset / 4;
  39911. return BABYLON.Tools.Slice(data, offset, offset + count);
  39912. }
  39913. else if (data instanceof ArrayBuffer) {
  39914. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39915. }
  39916. else {
  39917. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39918. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39919. var result = new Float32Array(count);
  39920. var source = new Float32Array(data.buffer, offset, count);
  39921. result.set(source);
  39922. return result;
  39923. }
  39924. return new Float32Array(data.buffer, offset, count);
  39925. }
  39926. }
  39927. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39928. return BABYLON.Tools.Slice(data);
  39929. }
  39930. return data;
  39931. };
  39932. /**
  39933. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39934. * @param kind defines the data kind (Position, normal, etc...)
  39935. * @returns true if the vertex buffer with the specified kind is updatable
  39936. */
  39937. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39938. var vb = this._vertexBuffers[kind];
  39939. if (!vb) {
  39940. return false;
  39941. }
  39942. return vb.isUpdatable();
  39943. };
  39944. /**
  39945. * Gets a specific vertex buffer
  39946. * @param kind defines the data kind (Position, normal, etc...)
  39947. * @returns a {BABYLON.VertexBuffer}
  39948. */
  39949. Geometry.prototype.getVertexBuffer = function (kind) {
  39950. if (!this.isReady()) {
  39951. return null;
  39952. }
  39953. return this._vertexBuffers[kind];
  39954. };
  39955. /**
  39956. * Returns all vertex buffers
  39957. * @return an object holding all vertex buffers indexed by kind
  39958. */
  39959. Geometry.prototype.getVertexBuffers = function () {
  39960. if (!this.isReady()) {
  39961. return null;
  39962. }
  39963. return this._vertexBuffers;
  39964. };
  39965. /**
  39966. * Gets a boolean indicating if specific vertex buffer is present
  39967. * @param kind defines the data kind (Position, normal, etc...)
  39968. * @returns true if data is present
  39969. */
  39970. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39971. if (!this._vertexBuffers) {
  39972. if (this._delayInfo) {
  39973. return this._delayInfo.indexOf(kind) !== -1;
  39974. }
  39975. return false;
  39976. }
  39977. return this._vertexBuffers[kind] !== undefined;
  39978. };
  39979. /**
  39980. * Gets a list of all attached data kinds (Position, normal, etc...)
  39981. * @returns a list of string containing all kinds
  39982. */
  39983. Geometry.prototype.getVerticesDataKinds = function () {
  39984. var result = [];
  39985. var kind;
  39986. if (!this._vertexBuffers && this._delayInfo) {
  39987. for (kind in this._delayInfo) {
  39988. result.push(kind);
  39989. }
  39990. }
  39991. else {
  39992. for (kind in this._vertexBuffers) {
  39993. result.push(kind);
  39994. }
  39995. }
  39996. return result;
  39997. };
  39998. /**
  39999. * Update index buffer
  40000. * @param indices defines the indices to store in the index buffer
  40001. * @param offset defines the offset in the target buffer where to store the data
  40002. */
  40003. Geometry.prototype.updateIndices = function (indices, offset) {
  40004. if (!this._indexBuffer) {
  40005. return;
  40006. }
  40007. if (!this._indexBufferIsUpdatable) {
  40008. this.setIndices(indices, null, true);
  40009. }
  40010. else {
  40011. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40012. }
  40013. };
  40014. /**
  40015. * Creates a new index buffer
  40016. * @param indices defines the indices to store in the index buffer
  40017. * @param totalVertices defines the total number of vertices (could be null)
  40018. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40019. */
  40020. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40021. if (totalVertices === void 0) { totalVertices = null; }
  40022. if (updatable === void 0) { updatable = false; }
  40023. if (this._indexBuffer) {
  40024. this._engine._releaseBuffer(this._indexBuffer);
  40025. }
  40026. this._disposeVertexArrayObjects();
  40027. this._indices = indices;
  40028. this._indexBufferIsUpdatable = updatable;
  40029. if (this._meshes.length !== 0 && this._indices) {
  40030. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40031. }
  40032. if (totalVertices != undefined) { // including null and undefined
  40033. this._totalVertices = totalVertices;
  40034. }
  40035. var meshes = this._meshes;
  40036. var numOfMeshes = meshes.length;
  40037. for (var index = 0; index < numOfMeshes; index++) {
  40038. meshes[index]._createGlobalSubMesh(true);
  40039. }
  40040. this.notifyUpdate();
  40041. };
  40042. /**
  40043. * Return the total number of indices
  40044. * @returns the total number of indices
  40045. */
  40046. Geometry.prototype.getTotalIndices = function () {
  40047. if (!this.isReady()) {
  40048. return 0;
  40049. }
  40050. return this._indices.length;
  40051. };
  40052. /**
  40053. * Gets the index buffer array
  40054. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40055. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40056. * @returns the index buffer array
  40057. */
  40058. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40059. if (!this.isReady()) {
  40060. return null;
  40061. }
  40062. var orig = this._indices;
  40063. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40064. return orig;
  40065. }
  40066. else {
  40067. var len = orig.length;
  40068. var copy = [];
  40069. for (var i = 0; i < len; i++) {
  40070. copy.push(orig[i]);
  40071. }
  40072. return copy;
  40073. }
  40074. };
  40075. /**
  40076. * Gets the index buffer
  40077. * @return the index buffer
  40078. */
  40079. Geometry.prototype.getIndexBuffer = function () {
  40080. if (!this.isReady()) {
  40081. return null;
  40082. }
  40083. return this._indexBuffer;
  40084. };
  40085. /** @hidden */
  40086. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40087. if (effect === void 0) { effect = null; }
  40088. if (!effect || !this._vertexArrayObjects) {
  40089. return;
  40090. }
  40091. if (this._vertexArrayObjects[effect.key]) {
  40092. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40093. delete this._vertexArrayObjects[effect.key];
  40094. }
  40095. };
  40096. /**
  40097. * Release the associated resources for a specific mesh
  40098. * @param mesh defines the source mesh
  40099. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40100. */
  40101. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40102. var meshes = this._meshes;
  40103. var index = meshes.indexOf(mesh);
  40104. if (index === -1) {
  40105. return;
  40106. }
  40107. meshes.splice(index, 1);
  40108. mesh._geometry = null;
  40109. if (meshes.length === 0 && shouldDispose) {
  40110. this.dispose();
  40111. }
  40112. };
  40113. /**
  40114. * Apply current geometry to a given mesh
  40115. * @param mesh defines the mesh to apply geometry to
  40116. */
  40117. Geometry.prototype.applyToMesh = function (mesh) {
  40118. if (mesh._geometry === this) {
  40119. return;
  40120. }
  40121. var previousGeometry = mesh._geometry;
  40122. if (previousGeometry) {
  40123. previousGeometry.releaseForMesh(mesh);
  40124. }
  40125. var meshes = this._meshes;
  40126. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40127. mesh._geometry = this;
  40128. this._scene.pushGeometry(this);
  40129. meshes.push(mesh);
  40130. if (this.isReady()) {
  40131. this._applyToMesh(mesh);
  40132. }
  40133. else {
  40134. mesh._boundingInfo = this._boundingInfo;
  40135. }
  40136. };
  40137. Geometry.prototype._updateExtend = function (data) {
  40138. if (data === void 0) { data = null; }
  40139. if (!data) {
  40140. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40141. }
  40142. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40143. };
  40144. Geometry.prototype._applyToMesh = function (mesh) {
  40145. var numOfMeshes = this._meshes.length;
  40146. // vertexBuffers
  40147. for (var kind in this._vertexBuffers) {
  40148. if (numOfMeshes === 1) {
  40149. this._vertexBuffers[kind].create();
  40150. }
  40151. var buffer = this._vertexBuffers[kind].getBuffer();
  40152. if (buffer)
  40153. buffer.references = numOfMeshes;
  40154. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40155. if (!this._extend) {
  40156. this._updateExtend();
  40157. }
  40158. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40159. mesh._createGlobalSubMesh(false);
  40160. //bounding info was just created again, world matrix should be applied again.
  40161. mesh._updateBoundingInfo();
  40162. }
  40163. }
  40164. // indexBuffer
  40165. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40166. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40167. }
  40168. if (this._indexBuffer) {
  40169. this._indexBuffer.references = numOfMeshes;
  40170. }
  40171. };
  40172. Geometry.prototype.notifyUpdate = function (kind) {
  40173. if (this.onGeometryUpdated) {
  40174. this.onGeometryUpdated(this, kind);
  40175. }
  40176. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40177. var mesh = _a[_i];
  40178. mesh._markSubMeshesAsAttributesDirty();
  40179. }
  40180. };
  40181. /**
  40182. * Load the geometry if it was flagged as delay loaded
  40183. * @param scene defines the hosting scene
  40184. * @param onLoaded defines a callback called when the geometry is loaded
  40185. */
  40186. Geometry.prototype.load = function (scene, onLoaded) {
  40187. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40188. return;
  40189. }
  40190. if (this.isReady()) {
  40191. if (onLoaded) {
  40192. onLoaded();
  40193. }
  40194. return;
  40195. }
  40196. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40197. this._queueLoad(scene, onLoaded);
  40198. };
  40199. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40200. var _this = this;
  40201. if (!this.delayLoadingFile) {
  40202. return;
  40203. }
  40204. scene._addPendingData(this);
  40205. scene._loadFile(this.delayLoadingFile, function (data) {
  40206. if (!_this._delayLoadingFunction) {
  40207. return;
  40208. }
  40209. _this._delayLoadingFunction(JSON.parse(data), _this);
  40210. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40211. _this._delayInfo = [];
  40212. scene._removePendingData(_this);
  40213. var meshes = _this._meshes;
  40214. var numOfMeshes = meshes.length;
  40215. for (var index = 0; index < numOfMeshes; index++) {
  40216. _this._applyToMesh(meshes[index]);
  40217. }
  40218. if (onLoaded) {
  40219. onLoaded();
  40220. }
  40221. }, undefined, true);
  40222. };
  40223. /**
  40224. * Invert the geometry to move from a right handed system to a left handed one.
  40225. */
  40226. Geometry.prototype.toLeftHanded = function () {
  40227. // Flip faces
  40228. var tIndices = this.getIndices(false);
  40229. if (tIndices != null && tIndices.length > 0) {
  40230. for (var i = 0; i < tIndices.length; i += 3) {
  40231. var tTemp = tIndices[i + 0];
  40232. tIndices[i + 0] = tIndices[i + 2];
  40233. tIndices[i + 2] = tTemp;
  40234. }
  40235. this.setIndices(tIndices);
  40236. }
  40237. // Negate position.z
  40238. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40239. if (tPositions != null && tPositions.length > 0) {
  40240. for (var i = 0; i < tPositions.length; i += 3) {
  40241. tPositions[i + 2] = -tPositions[i + 2];
  40242. }
  40243. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40244. }
  40245. // Negate normal.z
  40246. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40247. if (tNormals != null && tNormals.length > 0) {
  40248. for (var i = 0; i < tNormals.length; i += 3) {
  40249. tNormals[i + 2] = -tNormals[i + 2];
  40250. }
  40251. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40252. }
  40253. };
  40254. // Cache
  40255. /** @hidden */
  40256. Geometry.prototype._resetPointsArrayCache = function () {
  40257. this._positions = null;
  40258. };
  40259. /** @hidden */
  40260. Geometry.prototype._generatePointsArray = function () {
  40261. if (this._positions)
  40262. return true;
  40263. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40264. if (!data || data.length === 0) {
  40265. return false;
  40266. }
  40267. this._positions = [];
  40268. for (var index = 0; index < data.length; index += 3) {
  40269. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40270. }
  40271. return true;
  40272. };
  40273. /**
  40274. * Gets a value indicating if the geometry is disposed
  40275. * @returns true if the geometry was disposed
  40276. */
  40277. Geometry.prototype.isDisposed = function () {
  40278. return this._isDisposed;
  40279. };
  40280. Geometry.prototype._disposeVertexArrayObjects = function () {
  40281. if (this._vertexArrayObjects) {
  40282. for (var kind in this._vertexArrayObjects) {
  40283. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40284. }
  40285. this._vertexArrayObjects = {};
  40286. }
  40287. };
  40288. /**
  40289. * Free all associated resources
  40290. */
  40291. Geometry.prototype.dispose = function () {
  40292. var meshes = this._meshes;
  40293. var numOfMeshes = meshes.length;
  40294. var index;
  40295. for (index = 0; index < numOfMeshes; index++) {
  40296. this.releaseForMesh(meshes[index]);
  40297. }
  40298. this._meshes = [];
  40299. this._disposeVertexArrayObjects();
  40300. for (var kind in this._vertexBuffers) {
  40301. this._vertexBuffers[kind].dispose();
  40302. }
  40303. this._vertexBuffers = {};
  40304. this._totalVertices = 0;
  40305. if (this._indexBuffer) {
  40306. this._engine._releaseBuffer(this._indexBuffer);
  40307. }
  40308. this._indexBuffer = null;
  40309. this._indices = [];
  40310. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40311. this.delayLoadingFile = null;
  40312. this._delayLoadingFunction = null;
  40313. this._delayInfo = [];
  40314. this._boundingInfo = null;
  40315. this._scene.removeGeometry(this);
  40316. this._isDisposed = true;
  40317. };
  40318. /**
  40319. * Clone the current geometry into a new geometry
  40320. * @param id defines the unique ID of the new geometry
  40321. * @returns a new geometry object
  40322. */
  40323. Geometry.prototype.copy = function (id) {
  40324. var vertexData = new BABYLON.VertexData();
  40325. vertexData.indices = [];
  40326. var indices = this.getIndices();
  40327. if (indices) {
  40328. for (var index = 0; index < indices.length; index++) {
  40329. vertexData.indices.push(indices[index]);
  40330. }
  40331. }
  40332. var updatable = false;
  40333. var stopChecking = false;
  40334. var kind;
  40335. for (kind in this._vertexBuffers) {
  40336. // using slice() to make a copy of the array and not just reference it
  40337. var data = this.getVerticesData(kind);
  40338. if (data instanceof Float32Array) {
  40339. vertexData.set(new Float32Array(data), kind);
  40340. }
  40341. else {
  40342. vertexData.set(data.slice(0), kind);
  40343. }
  40344. if (!stopChecking) {
  40345. var vb = this.getVertexBuffer(kind);
  40346. if (vb) {
  40347. updatable = vb.isUpdatable();
  40348. stopChecking = !updatable;
  40349. }
  40350. }
  40351. }
  40352. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40353. geometry.delayLoadState = this.delayLoadState;
  40354. geometry.delayLoadingFile = this.delayLoadingFile;
  40355. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40356. for (kind in this._delayInfo) {
  40357. geometry._delayInfo = geometry._delayInfo || [];
  40358. geometry._delayInfo.push(kind);
  40359. }
  40360. // Bounding info
  40361. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40362. return geometry;
  40363. };
  40364. /**
  40365. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40366. * @return a JSON representation of the current geometry data (without the vertices data)
  40367. */
  40368. Geometry.prototype.serialize = function () {
  40369. var serializationObject = {};
  40370. serializationObject.id = this.id;
  40371. serializationObject.updatable = this._updatable;
  40372. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40373. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40374. }
  40375. return serializationObject;
  40376. };
  40377. Geometry.prototype.toNumberArray = function (origin) {
  40378. if (Array.isArray(origin)) {
  40379. return origin;
  40380. }
  40381. else {
  40382. return Array.prototype.slice.call(origin);
  40383. }
  40384. };
  40385. /**
  40386. * Serialize all vertices data into a JSON oject
  40387. * @returns a JSON representation of the current geometry data
  40388. */
  40389. Geometry.prototype.serializeVerticeData = function () {
  40390. var serializationObject = this.serialize();
  40391. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40392. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40393. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40394. serializationObject.positions._updatable = true;
  40395. }
  40396. }
  40397. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40398. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40399. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40400. serializationObject.normals._updatable = true;
  40401. }
  40402. }
  40403. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40404. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40405. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40406. serializationObject.tangets._updatable = true;
  40407. }
  40408. }
  40409. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40410. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40411. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40412. serializationObject.uvs._updatable = true;
  40413. }
  40414. }
  40415. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40416. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40417. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40418. serializationObject.uv2s._updatable = true;
  40419. }
  40420. }
  40421. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40422. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40423. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40424. serializationObject.uv3s._updatable = true;
  40425. }
  40426. }
  40427. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40428. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40429. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40430. serializationObject.uv4s._updatable = true;
  40431. }
  40432. }
  40433. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40434. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40435. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40436. serializationObject.uv5s._updatable = true;
  40437. }
  40438. }
  40439. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40440. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40441. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40442. serializationObject.uv6s._updatable = true;
  40443. }
  40444. }
  40445. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40446. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40447. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40448. serializationObject.colors._updatable = true;
  40449. }
  40450. }
  40451. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40452. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40453. serializationObject.matricesIndices._isExpanded = true;
  40454. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40455. serializationObject.matricesIndices._updatable = true;
  40456. }
  40457. }
  40458. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40459. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40460. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40461. serializationObject.matricesWeights._updatable = true;
  40462. }
  40463. }
  40464. serializationObject.indices = this.toNumberArray(this.getIndices());
  40465. return serializationObject;
  40466. };
  40467. // Statics
  40468. /**
  40469. * Extracts a clone of a mesh geometry
  40470. * @param mesh defines the source mesh
  40471. * @param id defines the unique ID of the new geometry object
  40472. * @returns the new geometry object
  40473. */
  40474. Geometry.ExtractFromMesh = function (mesh, id) {
  40475. var geometry = mesh._geometry;
  40476. if (!geometry) {
  40477. return null;
  40478. }
  40479. return geometry.copy(id);
  40480. };
  40481. /**
  40482. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40483. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40484. * Be aware Math.random() could cause collisions, but:
  40485. * "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"
  40486. * @returns a string containing a new GUID
  40487. */
  40488. Geometry.RandomId = function () {
  40489. return BABYLON.Tools.RandomId();
  40490. };
  40491. /** @hidden */
  40492. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40493. var scene = mesh.getScene();
  40494. // Geometry
  40495. var geometryId = parsedGeometry.geometryId;
  40496. if (geometryId) {
  40497. var geometry = scene.getGeometryByID(geometryId);
  40498. if (geometry) {
  40499. geometry.applyToMesh(mesh);
  40500. }
  40501. }
  40502. else if (parsedGeometry instanceof ArrayBuffer) {
  40503. var binaryInfo = mesh._binaryInfo;
  40504. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40505. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40506. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40507. }
  40508. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40509. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40510. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40511. }
  40512. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40513. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40514. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40515. }
  40516. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40517. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40518. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40519. }
  40520. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40521. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40522. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40523. }
  40524. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40525. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40526. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40527. }
  40528. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40529. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40530. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40531. }
  40532. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40533. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40534. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40535. }
  40536. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40537. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40538. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40539. }
  40540. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40541. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40542. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40543. }
  40544. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40545. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40546. var floatIndices = [];
  40547. for (var i = 0; i < matricesIndicesData.length; i++) {
  40548. var index = matricesIndicesData[i];
  40549. floatIndices.push(index & 0x000000FF);
  40550. floatIndices.push((index & 0x0000FF00) >> 8);
  40551. floatIndices.push((index & 0x00FF0000) >> 16);
  40552. floatIndices.push(index >> 24);
  40553. }
  40554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40555. }
  40556. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40557. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40558. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40559. }
  40560. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40561. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40562. mesh.setIndices(indicesData, null);
  40563. }
  40564. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40565. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40566. mesh.subMeshes = [];
  40567. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40568. var materialIndex = subMeshesData[(i * 5) + 0];
  40569. var verticesStart = subMeshesData[(i * 5) + 1];
  40570. var verticesCount = subMeshesData[(i * 5) + 2];
  40571. var indexStart = subMeshesData[(i * 5) + 3];
  40572. var indexCount = subMeshesData[(i * 5) + 4];
  40573. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40574. }
  40575. }
  40576. }
  40577. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40578. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40579. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40580. if (parsedGeometry.tangents) {
  40581. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40582. }
  40583. if (parsedGeometry.uvs) {
  40584. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40585. }
  40586. if (parsedGeometry.uvs2) {
  40587. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40588. }
  40589. if (parsedGeometry.uvs3) {
  40590. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40591. }
  40592. if (parsedGeometry.uvs4) {
  40593. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40594. }
  40595. if (parsedGeometry.uvs5) {
  40596. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40597. }
  40598. if (parsedGeometry.uvs6) {
  40599. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40600. }
  40601. if (parsedGeometry.colors) {
  40602. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40603. }
  40604. if (parsedGeometry.matricesIndices) {
  40605. if (!parsedGeometry.matricesIndices._isExpanded) {
  40606. var floatIndices = [];
  40607. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40608. var matricesIndex = parsedGeometry.matricesIndices[i];
  40609. floatIndices.push(matricesIndex & 0x000000FF);
  40610. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40611. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40612. floatIndices.push(matricesIndex >> 24);
  40613. }
  40614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40615. }
  40616. else {
  40617. delete parsedGeometry.matricesIndices._isExpanded;
  40618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40619. }
  40620. }
  40621. if (parsedGeometry.matricesIndicesExtra) {
  40622. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40623. var floatIndices = [];
  40624. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40625. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40626. floatIndices.push(matricesIndex & 0x000000FF);
  40627. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40628. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40629. floatIndices.push(matricesIndex >> 24);
  40630. }
  40631. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40632. }
  40633. else {
  40634. delete parsedGeometry.matricesIndices._isExpanded;
  40635. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40636. }
  40637. }
  40638. if (parsedGeometry.matricesWeights) {
  40639. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40640. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40641. }
  40642. if (parsedGeometry.matricesWeightsExtra) {
  40643. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40644. }
  40645. mesh.setIndices(parsedGeometry.indices, null);
  40646. }
  40647. // SubMeshes
  40648. if (parsedGeometry.subMeshes) {
  40649. mesh.subMeshes = [];
  40650. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40651. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40652. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40653. }
  40654. }
  40655. // Flat shading
  40656. if (mesh._shouldGenerateFlatShading) {
  40657. mesh.convertToFlatShadedMesh();
  40658. delete mesh._shouldGenerateFlatShading;
  40659. }
  40660. // Update
  40661. mesh.computeWorldMatrix(true);
  40662. scene.onMeshImportedObservable.notifyObservers(mesh);
  40663. };
  40664. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40665. var epsilon = 1e-3;
  40666. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40667. return;
  40668. }
  40669. var noInfluenceBoneIndex = 0.0;
  40670. if (parsedGeometry.skeletonId > -1) {
  40671. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40672. if (!skeleton) {
  40673. return;
  40674. }
  40675. noInfluenceBoneIndex = skeleton.bones.length;
  40676. }
  40677. else {
  40678. return;
  40679. }
  40680. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40681. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40682. var matricesWeights = parsedGeometry.matricesWeights;
  40683. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40684. var influencers = parsedGeometry.numBoneInfluencer;
  40685. var size = matricesWeights.length;
  40686. for (var i = 0; i < size; i += 4) {
  40687. var weight = 0.0;
  40688. var firstZeroWeight = -1;
  40689. for (var j = 0; j < 4; j++) {
  40690. var w = matricesWeights[i + j];
  40691. weight += w;
  40692. if (w < epsilon && firstZeroWeight < 0) {
  40693. firstZeroWeight = j;
  40694. }
  40695. }
  40696. if (matricesWeightsExtra) {
  40697. for (var j = 0; j < 4; j++) {
  40698. var w = matricesWeightsExtra[i + j];
  40699. weight += w;
  40700. if (w < epsilon && firstZeroWeight < 0) {
  40701. firstZeroWeight = j + 4;
  40702. }
  40703. }
  40704. }
  40705. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40706. firstZeroWeight = influencers - 1;
  40707. }
  40708. if (weight > epsilon) {
  40709. var mweight = 1.0 / weight;
  40710. for (var j = 0; j < 4; j++) {
  40711. matricesWeights[i + j] *= mweight;
  40712. }
  40713. if (matricesWeightsExtra) {
  40714. for (var j = 0; j < 4; j++) {
  40715. matricesWeightsExtra[i + j] *= mweight;
  40716. }
  40717. }
  40718. }
  40719. else {
  40720. if (firstZeroWeight >= 4) {
  40721. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40722. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40723. }
  40724. else {
  40725. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40726. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40727. }
  40728. }
  40729. }
  40730. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40731. if (parsedGeometry.matricesWeightsExtra) {
  40732. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40733. }
  40734. };
  40735. /**
  40736. * Create a new geometry from persisted data (Using .babylon file format)
  40737. * @param parsedVertexData defines the persisted data
  40738. * @param scene defines the hosting scene
  40739. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40740. * @returns the new geometry object
  40741. */
  40742. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40743. if (scene.getGeometryByID(parsedVertexData.id)) {
  40744. return null; // null since geometry could be something else than a box...
  40745. }
  40746. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40747. if (BABYLON.Tags) {
  40748. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40749. }
  40750. if (parsedVertexData.delayLoadingFile) {
  40751. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40752. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40753. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40754. geometry._delayInfo = [];
  40755. if (parsedVertexData.hasUVs) {
  40756. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40757. }
  40758. if (parsedVertexData.hasUVs2) {
  40759. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40760. }
  40761. if (parsedVertexData.hasUVs3) {
  40762. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40763. }
  40764. if (parsedVertexData.hasUVs4) {
  40765. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40766. }
  40767. if (parsedVertexData.hasUVs5) {
  40768. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40769. }
  40770. if (parsedVertexData.hasUVs6) {
  40771. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40772. }
  40773. if (parsedVertexData.hasColors) {
  40774. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40775. }
  40776. if (parsedVertexData.hasMatricesIndices) {
  40777. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40778. }
  40779. if (parsedVertexData.hasMatricesWeights) {
  40780. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40781. }
  40782. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40783. }
  40784. else {
  40785. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40786. }
  40787. scene.pushGeometry(geometry, true);
  40788. return geometry;
  40789. };
  40790. return Geometry;
  40791. }());
  40792. BABYLON.Geometry = Geometry;
  40793. // Primitives
  40794. /// Abstract class
  40795. /**
  40796. * Abstract class used to provide common services for all typed geometries
  40797. * @hidden
  40798. */
  40799. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40800. __extends(_PrimitiveGeometry, _super);
  40801. /**
  40802. * Creates a new typed geometry
  40803. * @param id defines the unique ID of the geometry
  40804. * @param scene defines the hosting scene
  40805. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40806. * @param mesh defines the hosting mesh (can be null)
  40807. */
  40808. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40809. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40810. if (mesh === void 0) { mesh = null; }
  40811. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40812. _this._canBeRegenerated = _canBeRegenerated;
  40813. _this._beingRegenerated = true;
  40814. _this.regenerate();
  40815. _this._beingRegenerated = false;
  40816. return _this;
  40817. }
  40818. /**
  40819. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40820. * @returns true if the geometry can be regenerated
  40821. */
  40822. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40823. return this._canBeRegenerated;
  40824. };
  40825. /**
  40826. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40827. */
  40828. _PrimitiveGeometry.prototype.regenerate = function () {
  40829. if (!this._canBeRegenerated) {
  40830. return;
  40831. }
  40832. this._beingRegenerated = true;
  40833. this.setAllVerticesData(this._regenerateVertexData(), false);
  40834. this._beingRegenerated = false;
  40835. };
  40836. /**
  40837. * Clone the geometry
  40838. * @param id defines the unique ID of the new geometry
  40839. * @returns the new geometry
  40840. */
  40841. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40842. return _super.prototype.copy.call(this, id);
  40843. };
  40844. // overrides
  40845. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40846. if (!this._beingRegenerated) {
  40847. return;
  40848. }
  40849. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40850. };
  40851. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40852. if (!this._beingRegenerated) {
  40853. return;
  40854. }
  40855. _super.prototype.setVerticesData.call(this, kind, data, false);
  40856. };
  40857. // to override
  40858. /** @hidden */
  40859. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40860. throw new Error("Abstract method");
  40861. };
  40862. _PrimitiveGeometry.prototype.copy = function (id) {
  40863. throw new Error("Must be overriden in sub-classes.");
  40864. };
  40865. _PrimitiveGeometry.prototype.serialize = function () {
  40866. var serializationObject = _super.prototype.serialize.call(this);
  40867. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40868. return serializationObject;
  40869. };
  40870. return _PrimitiveGeometry;
  40871. }(Geometry));
  40872. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40873. /**
  40874. * Creates a ribbon geometry
  40875. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40876. */
  40877. var RibbonGeometry = /** @class */ (function (_super) {
  40878. __extends(RibbonGeometry, _super);
  40879. /**
  40880. * Creates a ribbon geometry
  40881. * @param id defines the unique ID of the geometry
  40882. * @param scene defines the hosting scene
  40883. * @param pathArray defines the array of paths to use
  40884. * @param closeArray defines if the last path and the first path must be joined
  40885. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40886. * @param offset defines the offset between points
  40887. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40888. * @param mesh defines the hosting mesh (can be null)
  40889. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40890. */
  40891. function RibbonGeometry(id, scene,
  40892. /**
  40893. * Defines the array of paths to use
  40894. */
  40895. pathArray,
  40896. /**
  40897. * Defines if the last and first points of each path in your pathArray must be joined
  40898. */
  40899. closeArray,
  40900. /**
  40901. * Defines if the last and first points of each path in your pathArray must be joined
  40902. */
  40903. closePath,
  40904. /**
  40905. * Defines the offset between points
  40906. */
  40907. offset, canBeRegenerated, mesh,
  40908. /**
  40909. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40910. */
  40911. side) {
  40912. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40913. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40914. _this.pathArray = pathArray;
  40915. _this.closeArray = closeArray;
  40916. _this.closePath = closePath;
  40917. _this.offset = offset;
  40918. _this.side = side;
  40919. return _this;
  40920. }
  40921. /** @hidden */
  40922. RibbonGeometry.prototype._regenerateVertexData = function () {
  40923. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40924. };
  40925. RibbonGeometry.prototype.copy = function (id) {
  40926. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40927. };
  40928. return RibbonGeometry;
  40929. }(_PrimitiveGeometry));
  40930. BABYLON.RibbonGeometry = RibbonGeometry;
  40931. /**
  40932. * Creates a box geometry
  40933. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40934. */
  40935. var BoxGeometry = /** @class */ (function (_super) {
  40936. __extends(BoxGeometry, _super);
  40937. /**
  40938. * Creates a box geometry
  40939. * @param id defines the unique ID of the geometry
  40940. * @param scene defines the hosting scene
  40941. * @param size defines the zise of the box (width, height and depth are the same)
  40942. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40943. * @param mesh defines the hosting mesh (can be null)
  40944. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40945. */
  40946. function BoxGeometry(id, scene,
  40947. /**
  40948. * Defines the zise of the box (width, height and depth are the same)
  40949. */
  40950. size, canBeRegenerated, mesh,
  40951. /**
  40952. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40953. */
  40954. side) {
  40955. if (mesh === void 0) { mesh = null; }
  40956. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40957. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40958. _this.size = size;
  40959. _this.side = side;
  40960. return _this;
  40961. }
  40962. /** @hidden */
  40963. BoxGeometry.prototype._regenerateVertexData = function () {
  40964. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40965. };
  40966. BoxGeometry.prototype.copy = function (id) {
  40967. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40968. };
  40969. BoxGeometry.prototype.serialize = function () {
  40970. var serializationObject = _super.prototype.serialize.call(this);
  40971. serializationObject.size = this.size;
  40972. return serializationObject;
  40973. };
  40974. BoxGeometry.Parse = function (parsedBox, scene) {
  40975. if (scene.getGeometryByID(parsedBox.id)) {
  40976. return null; // null since geometry could be something else than a box...
  40977. }
  40978. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40979. if (BABYLON.Tags) {
  40980. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40981. }
  40982. scene.pushGeometry(box, true);
  40983. return box;
  40984. };
  40985. return BoxGeometry;
  40986. }(_PrimitiveGeometry));
  40987. BABYLON.BoxGeometry = BoxGeometry;
  40988. /**
  40989. * Creates a sphere geometry
  40990. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40991. */
  40992. var SphereGeometry = /** @class */ (function (_super) {
  40993. __extends(SphereGeometry, _super);
  40994. /**
  40995. * Create a new sphere geometry
  40996. * @param id defines the unique ID of the geometry
  40997. * @param scene defines the hosting scene
  40998. * @param segments defines the number of segments to use to create the sphere
  40999. * @param diameter defines the diameter of the sphere
  41000. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41001. * @param mesh defines the hosting mesh (can be null)
  41002. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41003. */
  41004. function SphereGeometry(id, scene,
  41005. /**
  41006. * Defines the number of segments to use to create the sphere
  41007. */
  41008. segments,
  41009. /**
  41010. * Defines the diameter of the sphere
  41011. */
  41012. diameter, canBeRegenerated, mesh,
  41013. /**
  41014. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41015. */
  41016. side) {
  41017. if (mesh === void 0) { mesh = null; }
  41018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41019. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41020. _this.segments = segments;
  41021. _this.diameter = diameter;
  41022. _this.side = side;
  41023. return _this;
  41024. }
  41025. /** @hidden */
  41026. SphereGeometry.prototype._regenerateVertexData = function () {
  41027. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41028. };
  41029. SphereGeometry.prototype.copy = function (id) {
  41030. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41031. };
  41032. SphereGeometry.prototype.serialize = function () {
  41033. var serializationObject = _super.prototype.serialize.call(this);
  41034. serializationObject.segments = this.segments;
  41035. serializationObject.diameter = this.diameter;
  41036. return serializationObject;
  41037. };
  41038. SphereGeometry.Parse = function (parsedSphere, scene) {
  41039. if (scene.getGeometryByID(parsedSphere.id)) {
  41040. return null; // null since geometry could be something else than a sphere...
  41041. }
  41042. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41043. if (BABYLON.Tags) {
  41044. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41045. }
  41046. scene.pushGeometry(sphere, true);
  41047. return sphere;
  41048. };
  41049. return SphereGeometry;
  41050. }(_PrimitiveGeometry));
  41051. BABYLON.SphereGeometry = SphereGeometry;
  41052. /**
  41053. * Creates a disc geometry
  41054. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41055. */
  41056. var DiscGeometry = /** @class */ (function (_super) {
  41057. __extends(DiscGeometry, _super);
  41058. /**
  41059. * Creates a new disc geometry
  41060. * @param id defines the unique ID of the geometry
  41061. * @param scene defines the hosting scene
  41062. * @param radius defines the radius of the disc
  41063. * @param tessellation defines the tesselation factor to apply to the disc
  41064. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41065. * @param mesh defines the hosting mesh (can be null)
  41066. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41067. */
  41068. function DiscGeometry(id, scene,
  41069. /**
  41070. * Defines the radius of the disc
  41071. */
  41072. radius,
  41073. /**
  41074. * Defines the tesselation factor to apply to the disc
  41075. */
  41076. tessellation, canBeRegenerated, mesh,
  41077. /**
  41078. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41079. */
  41080. side) {
  41081. if (mesh === void 0) { mesh = null; }
  41082. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41083. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41084. _this.radius = radius;
  41085. _this.tessellation = tessellation;
  41086. _this.side = side;
  41087. return _this;
  41088. }
  41089. /** @hidden */
  41090. DiscGeometry.prototype._regenerateVertexData = function () {
  41091. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41092. };
  41093. DiscGeometry.prototype.copy = function (id) {
  41094. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41095. };
  41096. return DiscGeometry;
  41097. }(_PrimitiveGeometry));
  41098. BABYLON.DiscGeometry = DiscGeometry;
  41099. /**
  41100. * Creates a new cylinder geometry
  41101. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41102. */
  41103. var CylinderGeometry = /** @class */ (function (_super) {
  41104. __extends(CylinderGeometry, _super);
  41105. /**
  41106. * Creates a new cylinder geometry
  41107. * @param id defines the unique ID of the geometry
  41108. * @param scene defines the hosting scene
  41109. * @param height defines the height of the cylinder
  41110. * @param diameterTop defines the diameter of the cylinder's top cap
  41111. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41112. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41113. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41114. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41115. * @param mesh defines the hosting mesh (can be null)
  41116. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41117. */
  41118. function CylinderGeometry(id, scene,
  41119. /**
  41120. * Defines the height of the cylinder
  41121. */
  41122. height,
  41123. /**
  41124. * Defines the diameter of the cylinder's top cap
  41125. */
  41126. diameterTop,
  41127. /**
  41128. * Defines the diameter of the cylinder's bottom cap
  41129. */
  41130. diameterBottom,
  41131. /**
  41132. * Defines the tessellation factor to apply to the cylinder
  41133. */
  41134. tessellation,
  41135. /**
  41136. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41137. */
  41138. subdivisions, canBeRegenerated, mesh,
  41139. /**
  41140. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41141. */
  41142. side) {
  41143. if (subdivisions === void 0) { subdivisions = 1; }
  41144. if (mesh === void 0) { mesh = null; }
  41145. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41146. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41147. _this.height = height;
  41148. _this.diameterTop = diameterTop;
  41149. _this.diameterBottom = diameterBottom;
  41150. _this.tessellation = tessellation;
  41151. _this.subdivisions = subdivisions;
  41152. _this.side = side;
  41153. return _this;
  41154. }
  41155. /** @hidden */
  41156. CylinderGeometry.prototype._regenerateVertexData = function () {
  41157. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41158. };
  41159. CylinderGeometry.prototype.copy = function (id) {
  41160. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41161. };
  41162. CylinderGeometry.prototype.serialize = function () {
  41163. var serializationObject = _super.prototype.serialize.call(this);
  41164. serializationObject.height = this.height;
  41165. serializationObject.diameterTop = this.diameterTop;
  41166. serializationObject.diameterBottom = this.diameterBottom;
  41167. serializationObject.tessellation = this.tessellation;
  41168. return serializationObject;
  41169. };
  41170. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41171. if (scene.getGeometryByID(parsedCylinder.id)) {
  41172. return null; // null since geometry could be something else than a cylinder...
  41173. }
  41174. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41175. if (BABYLON.Tags) {
  41176. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41177. }
  41178. scene.pushGeometry(cylinder, true);
  41179. return cylinder;
  41180. };
  41181. return CylinderGeometry;
  41182. }(_PrimitiveGeometry));
  41183. BABYLON.CylinderGeometry = CylinderGeometry;
  41184. /**
  41185. * Creates a new torus geometry
  41186. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41187. */
  41188. var TorusGeometry = /** @class */ (function (_super) {
  41189. __extends(TorusGeometry, _super);
  41190. /**
  41191. * Creates a new torus geometry
  41192. * @param id defines the unique ID of the geometry
  41193. * @param scene defines the hosting scene
  41194. * @param diameter defines the diameter of the torus
  41195. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41196. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41197. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41198. * @param mesh defines the hosting mesh (can be null)
  41199. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41200. */
  41201. function TorusGeometry(id, scene,
  41202. /**
  41203. * Defines the diameter of the torus
  41204. */
  41205. diameter,
  41206. /**
  41207. * Defines the thickness of the torus (ie. internal diameter)
  41208. */
  41209. thickness,
  41210. /**
  41211. * Defines the tesselation factor to apply to the torus
  41212. */
  41213. tessellation, canBeRegenerated, mesh,
  41214. /**
  41215. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41216. */
  41217. side) {
  41218. if (mesh === void 0) { mesh = null; }
  41219. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41220. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41221. _this.diameter = diameter;
  41222. _this.thickness = thickness;
  41223. _this.tessellation = tessellation;
  41224. _this.side = side;
  41225. return _this;
  41226. }
  41227. /** @hidden */
  41228. TorusGeometry.prototype._regenerateVertexData = function () {
  41229. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41230. };
  41231. TorusGeometry.prototype.copy = function (id) {
  41232. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41233. };
  41234. TorusGeometry.prototype.serialize = function () {
  41235. var serializationObject = _super.prototype.serialize.call(this);
  41236. serializationObject.diameter = this.diameter;
  41237. serializationObject.thickness = this.thickness;
  41238. serializationObject.tessellation = this.tessellation;
  41239. return serializationObject;
  41240. };
  41241. TorusGeometry.Parse = function (parsedTorus, scene) {
  41242. if (scene.getGeometryByID(parsedTorus.id)) {
  41243. return null; // null since geometry could be something else than a torus...
  41244. }
  41245. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41246. if (BABYLON.Tags) {
  41247. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41248. }
  41249. scene.pushGeometry(torus, true);
  41250. return torus;
  41251. };
  41252. return TorusGeometry;
  41253. }(_PrimitiveGeometry));
  41254. BABYLON.TorusGeometry = TorusGeometry;
  41255. /**
  41256. * Creates a new ground geometry
  41257. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41258. */
  41259. var GroundGeometry = /** @class */ (function (_super) {
  41260. __extends(GroundGeometry, _super);
  41261. /**
  41262. * Creates a new ground geometry
  41263. * @param id defines the unique ID of the geometry
  41264. * @param scene defines the hosting scene
  41265. * @param width defines the width of the ground
  41266. * @param height defines the height of the ground
  41267. * @param subdivisions defines the subdivisions to apply to the ground
  41268. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41269. * @param mesh defines the hosting mesh (can be null)
  41270. */
  41271. function GroundGeometry(id, scene,
  41272. /**
  41273. * Defines the width of the ground
  41274. */
  41275. width,
  41276. /**
  41277. * Defines the height of the ground
  41278. */
  41279. height,
  41280. /**
  41281. * Defines the subdivisions to apply to the ground
  41282. */
  41283. subdivisions, canBeRegenerated, mesh) {
  41284. if (mesh === void 0) { mesh = null; }
  41285. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41286. _this.width = width;
  41287. _this.height = height;
  41288. _this.subdivisions = subdivisions;
  41289. return _this;
  41290. }
  41291. /** @hidden */
  41292. GroundGeometry.prototype._regenerateVertexData = function () {
  41293. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41294. };
  41295. GroundGeometry.prototype.copy = function (id) {
  41296. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41297. };
  41298. GroundGeometry.prototype.serialize = function () {
  41299. var serializationObject = _super.prototype.serialize.call(this);
  41300. serializationObject.width = this.width;
  41301. serializationObject.height = this.height;
  41302. serializationObject.subdivisions = this.subdivisions;
  41303. return serializationObject;
  41304. };
  41305. GroundGeometry.Parse = function (parsedGround, scene) {
  41306. if (scene.getGeometryByID(parsedGround.id)) {
  41307. return null; // null since geometry could be something else than a ground...
  41308. }
  41309. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41310. if (BABYLON.Tags) {
  41311. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41312. }
  41313. scene.pushGeometry(ground, true);
  41314. return ground;
  41315. };
  41316. return GroundGeometry;
  41317. }(_PrimitiveGeometry));
  41318. BABYLON.GroundGeometry = GroundGeometry;
  41319. /**
  41320. * Creates a tiled ground geometry
  41321. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41322. */
  41323. var TiledGroundGeometry = /** @class */ (function (_super) {
  41324. __extends(TiledGroundGeometry, _super);
  41325. /**
  41326. * Creates a tiled ground geometry
  41327. * @param id defines the unique ID of the geometry
  41328. * @param scene defines the hosting scene
  41329. * @param xmin defines the minimum value on X axis
  41330. * @param zmin defines the minimum value on Z axis
  41331. * @param xmax defines the maximum value on X axis
  41332. * @param zmax defines the maximum value on Z axis
  41333. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41334. * @param precision defines the precision to use when computing the tiles
  41335. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41336. * @param mesh defines the hosting mesh (can be null)
  41337. */
  41338. function TiledGroundGeometry(id, scene,
  41339. /**
  41340. * Defines the minimum value on X axis
  41341. */
  41342. xmin,
  41343. /**
  41344. * Defines the minimum value on Z axis
  41345. */
  41346. zmin,
  41347. /**
  41348. * Defines the maximum value on X axis
  41349. */
  41350. xmax,
  41351. /**
  41352. * Defines the maximum value on Z axis
  41353. */
  41354. zmax,
  41355. /**
  41356. * Defines the subdivisions to apply to the ground
  41357. */
  41358. subdivisions,
  41359. /**
  41360. * Defines the precision to use when computing the tiles
  41361. */
  41362. precision, canBeRegenerated, mesh) {
  41363. if (mesh === void 0) { mesh = null; }
  41364. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41365. _this.xmin = xmin;
  41366. _this.zmin = zmin;
  41367. _this.xmax = xmax;
  41368. _this.zmax = zmax;
  41369. _this.subdivisions = subdivisions;
  41370. _this.precision = precision;
  41371. return _this;
  41372. }
  41373. /** @hidden */
  41374. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41375. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41376. };
  41377. TiledGroundGeometry.prototype.copy = function (id) {
  41378. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41379. };
  41380. return TiledGroundGeometry;
  41381. }(_PrimitiveGeometry));
  41382. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41383. /**
  41384. * Creates a plane geometry
  41385. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41386. */
  41387. var PlaneGeometry = /** @class */ (function (_super) {
  41388. __extends(PlaneGeometry, _super);
  41389. /**
  41390. * Creates a plane geometry
  41391. * @param id defines the unique ID of the geometry
  41392. * @param scene defines the hosting scene
  41393. * @param size defines the size of the plane (width === height)
  41394. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41395. * @param mesh defines the hosting mesh (can be null)
  41396. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41397. */
  41398. function PlaneGeometry(id, scene,
  41399. /**
  41400. * Defines the size of the plane (width === height)
  41401. */
  41402. size, canBeRegenerated, mesh,
  41403. /**
  41404. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41405. */
  41406. side) {
  41407. if (mesh === void 0) { mesh = null; }
  41408. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41409. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41410. _this.size = size;
  41411. _this.side = side;
  41412. return _this;
  41413. }
  41414. /** @hidden */
  41415. PlaneGeometry.prototype._regenerateVertexData = function () {
  41416. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41417. };
  41418. PlaneGeometry.prototype.copy = function (id) {
  41419. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41420. };
  41421. PlaneGeometry.prototype.serialize = function () {
  41422. var serializationObject = _super.prototype.serialize.call(this);
  41423. serializationObject.size = this.size;
  41424. return serializationObject;
  41425. };
  41426. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41427. if (scene.getGeometryByID(parsedPlane.id)) {
  41428. return null; // null since geometry could be something else than a ground...
  41429. }
  41430. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41431. if (BABYLON.Tags) {
  41432. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41433. }
  41434. scene.pushGeometry(plane, true);
  41435. return plane;
  41436. };
  41437. return PlaneGeometry;
  41438. }(_PrimitiveGeometry));
  41439. BABYLON.PlaneGeometry = PlaneGeometry;
  41440. /**
  41441. * Creates a torus knot geometry
  41442. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41443. */
  41444. var TorusKnotGeometry = /** @class */ (function (_super) {
  41445. __extends(TorusKnotGeometry, _super);
  41446. /**
  41447. * Creates a torus knot geometry
  41448. * @param id defines the unique ID of the geometry
  41449. * @param scene defines the hosting scene
  41450. * @param radius defines the radius of the torus knot
  41451. * @param tube defines the thickness of the torus knot tube
  41452. * @param radialSegments defines the number of radial segments
  41453. * @param tubularSegments defines the number of tubular segments
  41454. * @param p defines the first number of windings
  41455. * @param q defines the second number of windings
  41456. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41457. * @param mesh defines the hosting mesh (can be null)
  41458. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41459. */
  41460. function TorusKnotGeometry(id, scene,
  41461. /**
  41462. * Defines the radius of the torus knot
  41463. */
  41464. radius,
  41465. /**
  41466. * Defines the thickness of the torus knot tube
  41467. */
  41468. tube,
  41469. /**
  41470. * Defines the number of radial segments
  41471. */
  41472. radialSegments,
  41473. /**
  41474. * Defines the number of tubular segments
  41475. */
  41476. tubularSegments,
  41477. /**
  41478. * Defines the first number of windings
  41479. */
  41480. p,
  41481. /**
  41482. * Defines the second number of windings
  41483. */
  41484. q, canBeRegenerated, mesh,
  41485. /**
  41486. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41487. */
  41488. side) {
  41489. if (mesh === void 0) { mesh = null; }
  41490. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41491. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41492. _this.radius = radius;
  41493. _this.tube = tube;
  41494. _this.radialSegments = radialSegments;
  41495. _this.tubularSegments = tubularSegments;
  41496. _this.p = p;
  41497. _this.q = q;
  41498. _this.side = side;
  41499. return _this;
  41500. }
  41501. /** @hidden */
  41502. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41503. 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 });
  41504. };
  41505. TorusKnotGeometry.prototype.copy = function (id) {
  41506. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41507. };
  41508. TorusKnotGeometry.prototype.serialize = function () {
  41509. var serializationObject = _super.prototype.serialize.call(this);
  41510. serializationObject.radius = this.radius;
  41511. serializationObject.tube = this.tube;
  41512. serializationObject.radialSegments = this.radialSegments;
  41513. serializationObject.tubularSegments = this.tubularSegments;
  41514. serializationObject.p = this.p;
  41515. serializationObject.q = this.q;
  41516. return serializationObject;
  41517. };
  41518. ;
  41519. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41520. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41521. return null; // null since geometry could be something else than a ground...
  41522. }
  41523. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41524. if (BABYLON.Tags) {
  41525. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41526. }
  41527. scene.pushGeometry(torusKnot, true);
  41528. return torusKnot;
  41529. };
  41530. return TorusKnotGeometry;
  41531. }(_PrimitiveGeometry));
  41532. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41533. //}
  41534. })(BABYLON || (BABYLON = {}));
  41535. //# sourceMappingURL=babylon.geometry.js.map
  41536. var BABYLON;
  41537. (function (BABYLON) {
  41538. /**
  41539. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41540. */
  41541. var PerformanceMonitor = /** @class */ (function () {
  41542. /**
  41543. * constructor
  41544. * @param frameSampleSize The number of samples required to saturate the sliding window
  41545. */
  41546. function PerformanceMonitor(frameSampleSize) {
  41547. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41548. this._enabled = true;
  41549. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41550. }
  41551. /**
  41552. * Samples current frame
  41553. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41554. */
  41555. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41556. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41557. if (!this._enabled)
  41558. return;
  41559. if (this._lastFrameTimeMs != null) {
  41560. var dt = timeMs - this._lastFrameTimeMs;
  41561. this._rollingFrameTime.add(dt);
  41562. }
  41563. this._lastFrameTimeMs = timeMs;
  41564. };
  41565. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41566. /**
  41567. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41568. */
  41569. get: function () {
  41570. return this._rollingFrameTime.average;
  41571. },
  41572. enumerable: true,
  41573. configurable: true
  41574. });
  41575. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41576. /**
  41577. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41578. */
  41579. get: function () {
  41580. return this._rollingFrameTime.variance;
  41581. },
  41582. enumerable: true,
  41583. configurable: true
  41584. });
  41585. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41586. /**
  41587. * Returns the frame time of the most recent frame
  41588. */
  41589. get: function () {
  41590. return this._rollingFrameTime.history(0);
  41591. },
  41592. enumerable: true,
  41593. configurable: true
  41594. });
  41595. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41596. /**
  41597. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41598. */
  41599. get: function () {
  41600. return 1000.0 / this._rollingFrameTime.average;
  41601. },
  41602. enumerable: true,
  41603. configurable: true
  41604. });
  41605. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41606. /**
  41607. * Returns the average framerate in frames per second using the most recent frame time
  41608. */
  41609. get: function () {
  41610. var history = this._rollingFrameTime.history(0);
  41611. if (history === 0) {
  41612. return 0;
  41613. }
  41614. return 1000.0 / history;
  41615. },
  41616. enumerable: true,
  41617. configurable: true
  41618. });
  41619. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41620. /**
  41621. * Returns true if enough samples have been taken to completely fill the sliding window
  41622. */
  41623. get: function () {
  41624. return this._rollingFrameTime.isSaturated();
  41625. },
  41626. enumerable: true,
  41627. configurable: true
  41628. });
  41629. /**
  41630. * Enables contributions to the sliding window sample set
  41631. */
  41632. PerformanceMonitor.prototype.enable = function () {
  41633. this._enabled = true;
  41634. };
  41635. /**
  41636. * Disables contributions to the sliding window sample set
  41637. * Samples will not be interpolated over the disabled period
  41638. */
  41639. PerformanceMonitor.prototype.disable = function () {
  41640. this._enabled = false;
  41641. //clear last sample to avoid interpolating over the disabled period when next enabled
  41642. this._lastFrameTimeMs = null;
  41643. };
  41644. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41645. /**
  41646. * Returns true if sampling is enabled
  41647. */
  41648. get: function () {
  41649. return this._enabled;
  41650. },
  41651. enumerable: true,
  41652. configurable: true
  41653. });
  41654. /**
  41655. * Resets performance monitor
  41656. */
  41657. PerformanceMonitor.prototype.reset = function () {
  41658. //clear last sample to avoid interpolating over the disabled period when next enabled
  41659. this._lastFrameTimeMs = null;
  41660. //wipe record
  41661. this._rollingFrameTime.reset();
  41662. };
  41663. return PerformanceMonitor;
  41664. }());
  41665. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41666. /**
  41667. * RollingAverage
  41668. *
  41669. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41670. */
  41671. var RollingAverage = /** @class */ (function () {
  41672. /**
  41673. * constructor
  41674. * @param length The number of samples required to saturate the sliding window
  41675. */
  41676. function RollingAverage(length) {
  41677. this._samples = new Array(length);
  41678. this.reset();
  41679. }
  41680. /**
  41681. * Adds a sample to the sample set
  41682. * @param v The sample value
  41683. */
  41684. RollingAverage.prototype.add = function (v) {
  41685. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41686. var delta;
  41687. //we need to check if we've already wrapped round
  41688. if (this.isSaturated()) {
  41689. //remove bottom of stack from mean
  41690. var bottomValue = this._samples[this._pos];
  41691. delta = bottomValue - this.average;
  41692. this.average -= delta / (this._sampleCount - 1);
  41693. this._m2 -= delta * (bottomValue - this.average);
  41694. }
  41695. else {
  41696. this._sampleCount++;
  41697. }
  41698. //add new value to mean
  41699. delta = v - this.average;
  41700. this.average += delta / (this._sampleCount);
  41701. this._m2 += delta * (v - this.average);
  41702. //set the new variance
  41703. this.variance = this._m2 / (this._sampleCount - 1);
  41704. this._samples[this._pos] = v;
  41705. this._pos++;
  41706. this._pos %= this._samples.length; //positive wrap around
  41707. };
  41708. /**
  41709. * Returns previously added values or null if outside of history or outside the sliding window domain
  41710. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41711. * @return Value previously recorded with add() or null if outside of range
  41712. */
  41713. RollingAverage.prototype.history = function (i) {
  41714. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41715. return 0;
  41716. }
  41717. var i0 = this._wrapPosition(this._pos - 1.0);
  41718. return this._samples[this._wrapPosition(i0 - i)];
  41719. };
  41720. /**
  41721. * Returns true if enough samples have been taken to completely fill the sliding window
  41722. * @return true if sample-set saturated
  41723. */
  41724. RollingAverage.prototype.isSaturated = function () {
  41725. return this._sampleCount >= this._samples.length;
  41726. };
  41727. /**
  41728. * Resets the rolling average (equivalent to 0 samples taken so far)
  41729. */
  41730. RollingAverage.prototype.reset = function () {
  41731. this.average = 0;
  41732. this.variance = 0;
  41733. this._sampleCount = 0;
  41734. this._pos = 0;
  41735. this._m2 = 0;
  41736. };
  41737. /**
  41738. * Wraps a value around the sample range boundaries
  41739. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41740. * @return Wrapped position in sample range
  41741. */
  41742. RollingAverage.prototype._wrapPosition = function (i) {
  41743. var max = this._samples.length;
  41744. return ((i % max) + max) % max;
  41745. };
  41746. return RollingAverage;
  41747. }());
  41748. BABYLON.RollingAverage = RollingAverage;
  41749. })(BABYLON || (BABYLON = {}));
  41750. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41751. var BABYLON;
  41752. (function (BABYLON) {
  41753. /**
  41754. * "Static Class" containing the most commonly used helper while dealing with material for
  41755. * rendering purpose.
  41756. *
  41757. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41758. *
  41759. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41760. */
  41761. var MaterialHelper = /** @class */ (function () {
  41762. function MaterialHelper() {
  41763. }
  41764. /**
  41765. * Bind the current view position to an effect.
  41766. * @param effect The effect to be bound
  41767. * @param scene The scene the eyes position is used from
  41768. */
  41769. MaterialHelper.BindEyePosition = function (effect, scene) {
  41770. if (scene._forcedViewPosition) {
  41771. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41772. return;
  41773. }
  41774. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41775. };
  41776. /**
  41777. * Helps preparing the defines values about the UVs in used in the effect.
  41778. * UVs are shared as much as we can accross channels in the shaders.
  41779. * @param texture The texture we are preparing the UVs for
  41780. * @param defines The defines to update
  41781. * @param key The channel key "diffuse", "specular"... used in the shader
  41782. */
  41783. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41784. defines._needUVs = true;
  41785. defines[key] = true;
  41786. if (texture.getTextureMatrix().isIdentity(true)) {
  41787. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41788. if (texture.coordinatesIndex === 0) {
  41789. defines["MAINUV1"] = true;
  41790. }
  41791. else {
  41792. defines["MAINUV2"] = true;
  41793. }
  41794. }
  41795. else {
  41796. defines[key + "DIRECTUV"] = 0;
  41797. }
  41798. };
  41799. /**
  41800. * Binds a texture matrix value to its corrsponding uniform
  41801. * @param texture The texture to bind the matrix for
  41802. * @param uniformBuffer The uniform buffer receivin the data
  41803. * @param key The channel key "diffuse", "specular"... used in the shader
  41804. */
  41805. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41806. var matrix = texture.getTextureMatrix();
  41807. if (!matrix.isIdentity(true)) {
  41808. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41809. }
  41810. };
  41811. /**
  41812. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41813. * @param mesh defines the current mesh
  41814. * @param scene defines the current scene
  41815. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41816. * @param pointsCloud defines if point cloud rendering has to be turned on
  41817. * @param fogEnabled defines if fog has to be turned on
  41818. * @param alphaTest defines if alpha testing has to be turned on
  41819. * @param defines defines the current list of defines
  41820. */
  41821. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41822. if (defines._areMiscDirty) {
  41823. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41824. defines["POINTSIZE"] = pointsCloud;
  41825. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41826. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41827. defines["ALPHATEST"] = alphaTest;
  41828. }
  41829. };
  41830. /**
  41831. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41832. * @param scene defines the current scene
  41833. * @param engine defines the current engine
  41834. * @param defines specifies the list of active defines
  41835. * @param useInstances defines if instances have to be turned on
  41836. * @param useClipPlane defines if clip plane have to be turned on
  41837. */
  41838. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41839. if (useClipPlane === void 0) { useClipPlane = null; }
  41840. var changed = false;
  41841. var useClipPlane1 = false;
  41842. var useClipPlane2 = false;
  41843. var useClipPlane3 = false;
  41844. var useClipPlane4 = false;
  41845. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41846. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41847. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41848. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41849. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41850. defines["CLIPPLANE"] = useClipPlane1;
  41851. changed = true;
  41852. }
  41853. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41854. defines["CLIPPLANE2"] = useClipPlane2;
  41855. changed = true;
  41856. }
  41857. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41858. defines["CLIPPLANE3"] = useClipPlane3;
  41859. changed = true;
  41860. }
  41861. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41862. defines["CLIPPLANE4"] = useClipPlane4;
  41863. changed = true;
  41864. }
  41865. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41866. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41867. changed = true;
  41868. }
  41869. if (defines["INSTANCES"] !== useInstances) {
  41870. defines["INSTANCES"] = useInstances;
  41871. changed = true;
  41872. }
  41873. if (changed) {
  41874. defines.markAsUnprocessed();
  41875. }
  41876. };
  41877. /**
  41878. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41879. * @param mesh The mesh containing the geometry data we will draw
  41880. * @param defines The defines to update
  41881. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41882. * @param useBones Precise whether bones should be used or not (override mesh info)
  41883. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41884. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41885. * @returns false if defines are considered not dirty and have not been checked
  41886. */
  41887. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41888. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41889. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41890. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41891. return false;
  41892. }
  41893. defines._normals = defines._needNormals;
  41894. defines._uvs = defines._needUVs;
  41895. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41896. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41897. defines["TANGENT"] = true;
  41898. }
  41899. if (defines._needUVs) {
  41900. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41901. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41902. }
  41903. else {
  41904. defines["UV1"] = false;
  41905. defines["UV2"] = false;
  41906. }
  41907. if (useVertexColor) {
  41908. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41909. defines["VERTEXCOLOR"] = hasVertexColors;
  41910. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41911. }
  41912. if (useBones) {
  41913. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41914. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41915. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41916. }
  41917. else {
  41918. defines["NUM_BONE_INFLUENCERS"] = 0;
  41919. defines["BonesPerMesh"] = 0;
  41920. }
  41921. }
  41922. if (useMorphTargets) {
  41923. var manager = mesh.morphTargetManager;
  41924. if (manager) {
  41925. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41926. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41927. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41928. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41929. }
  41930. else {
  41931. defines["MORPHTARGETS_TANGENT"] = false;
  41932. defines["MORPHTARGETS_NORMAL"] = false;
  41933. defines["MORPHTARGETS"] = false;
  41934. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41935. }
  41936. }
  41937. return true;
  41938. };
  41939. /**
  41940. * Prepares the defines related to the light information passed in parameter
  41941. * @param scene The scene we are intending to draw
  41942. * @param mesh The mesh the effect is compiling for
  41943. * @param defines The defines to update
  41944. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41945. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41946. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41947. * @returns true if normals will be required for the rest of the effect
  41948. */
  41949. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41950. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41951. if (disableLighting === void 0) { disableLighting = false; }
  41952. if (!defines._areLightsDirty) {
  41953. return defines._needNormals;
  41954. }
  41955. var lightIndex = 0;
  41956. var needNormals = false;
  41957. var needRebuild = false;
  41958. var lightmapMode = false;
  41959. var shadowEnabled = false;
  41960. var specularEnabled = false;
  41961. if (scene.lightsEnabled && !disableLighting) {
  41962. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41963. var light = _a[_i];
  41964. needNormals = true;
  41965. if (defines["LIGHT" + lightIndex] === undefined) {
  41966. needRebuild = true;
  41967. }
  41968. defines["LIGHT" + lightIndex] = true;
  41969. defines["SPOTLIGHT" + lightIndex] = false;
  41970. defines["HEMILIGHT" + lightIndex] = false;
  41971. defines["POINTLIGHT" + lightIndex] = false;
  41972. defines["DIRLIGHT" + lightIndex] = false;
  41973. light.prepareLightSpecificDefines(defines, lightIndex);
  41974. // FallOff.
  41975. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41976. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41977. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41978. switch (light.falloffType) {
  41979. case BABYLON.Light.FALLOFF_GLTF:
  41980. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41981. break;
  41982. case BABYLON.Light.FALLOFF_PHYSICAL:
  41983. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41984. break;
  41985. case BABYLON.Light.FALLOFF_STANDARD:
  41986. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41987. break;
  41988. }
  41989. // Specular
  41990. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41991. specularEnabled = true;
  41992. }
  41993. // Shadows
  41994. defines["SHADOW" + lightIndex] = false;
  41995. defines["SHADOWPCF" + lightIndex] = false;
  41996. defines["SHADOWPCSS" + lightIndex] = false;
  41997. defines["SHADOWPOISSON" + lightIndex] = false;
  41998. defines["SHADOWESM" + lightIndex] = false;
  41999. defines["SHADOWCUBE" + lightIndex] = false;
  42000. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42001. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42002. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42003. var shadowGenerator = light.getShadowGenerator();
  42004. if (shadowGenerator) {
  42005. var shadowMap = shadowGenerator.getShadowMap();
  42006. if (shadowMap) {
  42007. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42008. shadowEnabled = true;
  42009. shadowGenerator.prepareDefines(defines, lightIndex);
  42010. }
  42011. }
  42012. }
  42013. }
  42014. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42015. lightmapMode = true;
  42016. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42017. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42018. }
  42019. else {
  42020. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42021. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42022. }
  42023. lightIndex++;
  42024. if (lightIndex === maxSimultaneousLights)
  42025. break;
  42026. }
  42027. }
  42028. defines["SPECULARTERM"] = specularEnabled;
  42029. defines["SHADOWS"] = shadowEnabled;
  42030. // Resetting all other lights if any
  42031. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42032. if (defines["LIGHT" + index] !== undefined) {
  42033. defines["LIGHT" + index] = false;
  42034. defines["HEMILIGHT" + lightIndex] = false;
  42035. defines["POINTLIGHT" + lightIndex] = false;
  42036. defines["DIRLIGHT" + lightIndex] = false;
  42037. defines["SPOTLIGHT" + lightIndex] = false;
  42038. defines["SHADOW" + lightIndex] = false;
  42039. }
  42040. }
  42041. var caps = scene.getEngine().getCaps();
  42042. if (defines["SHADOWFLOAT"] === undefined) {
  42043. needRebuild = true;
  42044. }
  42045. defines["SHADOWFLOAT"] = shadowEnabled &&
  42046. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42047. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42048. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42049. if (needRebuild) {
  42050. defines.rebuild();
  42051. }
  42052. return needNormals;
  42053. };
  42054. /**
  42055. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42056. * that won t be acctive due to defines being turned off.
  42057. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42058. * @param samplersList The samplers list
  42059. * @param defines The defines helping in the list generation
  42060. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42061. */
  42062. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42063. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42064. var uniformsList;
  42065. var uniformBuffersList = null;
  42066. if (uniformsListOrOptions.uniformsNames) {
  42067. var options = uniformsListOrOptions;
  42068. uniformsList = options.uniformsNames;
  42069. uniformBuffersList = options.uniformBuffersNames;
  42070. samplersList = options.samplers;
  42071. defines = options.defines;
  42072. maxSimultaneousLights = options.maxSimultaneousLights;
  42073. }
  42074. else {
  42075. uniformsList = uniformsListOrOptions;
  42076. if (!samplersList) {
  42077. samplersList = [];
  42078. }
  42079. }
  42080. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42081. if (!defines["LIGHT" + lightIndex]) {
  42082. break;
  42083. }
  42084. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42085. if (uniformBuffersList) {
  42086. uniformBuffersList.push("Light" + lightIndex);
  42087. }
  42088. samplersList.push("shadowSampler" + lightIndex);
  42089. samplersList.push("depthSampler" + lightIndex);
  42090. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42091. samplersList.push("projectionLightSampler" + lightIndex);
  42092. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42093. }
  42094. }
  42095. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42096. uniformsList.push("morphTargetInfluences");
  42097. }
  42098. };
  42099. /**
  42100. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42101. * @param defines The defines to update while falling back
  42102. * @param fallbacks The authorized effect fallbacks
  42103. * @param maxSimultaneousLights The maximum number of lights allowed
  42104. * @param rank the current rank of the Effect
  42105. * @returns The newly affected rank
  42106. */
  42107. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42108. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42109. if (rank === void 0) { rank = 0; }
  42110. var lightFallbackRank = 0;
  42111. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42112. if (!defines["LIGHT" + lightIndex]) {
  42113. break;
  42114. }
  42115. if (lightIndex > 0) {
  42116. lightFallbackRank = rank + lightIndex;
  42117. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42118. }
  42119. if (!defines["SHADOWS"]) {
  42120. if (defines["SHADOW" + lightIndex]) {
  42121. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42122. }
  42123. if (defines["SHADOWPCF" + lightIndex]) {
  42124. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42125. }
  42126. if (defines["SHADOWPCSS" + lightIndex]) {
  42127. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42128. }
  42129. if (defines["SHADOWPOISSON" + lightIndex]) {
  42130. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42131. }
  42132. if (defines["SHADOWESM" + lightIndex]) {
  42133. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42134. }
  42135. }
  42136. }
  42137. return lightFallbackRank++;
  42138. };
  42139. /**
  42140. * Prepares the list of attributes required for morph targets according to the effect defines.
  42141. * @param attribs The current list of supported attribs
  42142. * @param mesh The mesh to prepare the morph targets attributes for
  42143. * @param defines The current Defines of the effect
  42144. */
  42145. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42146. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42147. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42148. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42149. var manager = mesh.morphTargetManager;
  42150. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42151. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42152. for (var index = 0; index < influencers; index++) {
  42153. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42154. if (normal) {
  42155. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42156. }
  42157. if (tangent) {
  42158. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42159. }
  42160. if (attribs.length > maxAttributesCount) {
  42161. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42162. }
  42163. }
  42164. }
  42165. };
  42166. /**
  42167. * Prepares the list of attributes required for bones according to the effect defines.
  42168. * @param attribs The current list of supported attribs
  42169. * @param mesh The mesh to prepare the bones attributes for
  42170. * @param defines The current Defines of the effect
  42171. * @param fallbacks The current efffect fallback strategy
  42172. */
  42173. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42174. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42175. fallbacks.addCPUSkinningFallback(0, mesh);
  42176. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42177. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42178. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42179. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42180. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42181. }
  42182. }
  42183. };
  42184. /**
  42185. * Prepares the list of attributes required for instances according to the effect defines.
  42186. * @param attribs The current list of supported attribs
  42187. * @param defines The current Defines of the effect
  42188. */
  42189. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42190. if (defines["INSTANCES"]) {
  42191. attribs.push("world0");
  42192. attribs.push("world1");
  42193. attribs.push("world2");
  42194. attribs.push("world3");
  42195. }
  42196. };
  42197. /**
  42198. * Binds the light shadow information to the effect for the given mesh.
  42199. * @param light The light containing the generator
  42200. * @param scene The scene the lights belongs to
  42201. * @param mesh The mesh we are binding the information to render
  42202. * @param lightIndex The light index in the effect used to render the mesh
  42203. * @param effect The effect we are binding the data to
  42204. */
  42205. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42206. if (light.shadowEnabled && mesh.receiveShadows) {
  42207. var shadowGenerator = light.getShadowGenerator();
  42208. if (shadowGenerator) {
  42209. shadowGenerator.bindShadowLight(lightIndex, effect);
  42210. }
  42211. }
  42212. };
  42213. /**
  42214. * Binds the light information to the effect.
  42215. * @param light The light containing the generator
  42216. * @param effect The effect we are binding the data to
  42217. * @param lightIndex The light index in the effect used to render
  42218. */
  42219. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42220. light.transferToEffect(effect, lightIndex + "");
  42221. };
  42222. /**
  42223. * Binds the lights information from the scene to the effect for the given mesh.
  42224. * @param scene The scene the lights belongs to
  42225. * @param mesh The mesh we are binding the information to render
  42226. * @param effect The effect we are binding the data to
  42227. * @param defines The generated defines for the effect
  42228. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42229. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42230. */
  42231. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42232. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42233. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42234. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42235. for (var i = 0; i < len; i++) {
  42236. var light = mesh._lightSources[i];
  42237. var iAsString = i.toString();
  42238. var scaledIntensity = light.getScaledIntensity();
  42239. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42240. MaterialHelper.BindLightProperties(light, effect, i);
  42241. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42242. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42243. if (defines["SPECULARTERM"]) {
  42244. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42245. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42246. }
  42247. // Shadows
  42248. if (scene.shadowsEnabled) {
  42249. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42250. }
  42251. light._uniformBuffer.update();
  42252. }
  42253. };
  42254. /**
  42255. * Binds the fog information from the scene to the effect for the given mesh.
  42256. * @param scene The scene the lights belongs to
  42257. * @param mesh The mesh we are binding the information to render
  42258. * @param effect The effect we are binding the data to
  42259. * @param linearSpace Defines if the fog effect is applied in linear space
  42260. */
  42261. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42262. if (linearSpace === void 0) { linearSpace = false; }
  42263. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42264. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42265. // Convert fog color to linear space if used in a linear space computed shader.
  42266. if (linearSpace) {
  42267. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42268. effect.setColor3("vFogColor", this._tempFogColor);
  42269. }
  42270. else {
  42271. effect.setColor3("vFogColor", scene.fogColor);
  42272. }
  42273. }
  42274. };
  42275. /**
  42276. * Binds the bones information from the mesh to the effect.
  42277. * @param mesh The mesh we are binding the information to render
  42278. * @param effect The effect we are binding the data to
  42279. */
  42280. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42281. if (!effect || !mesh) {
  42282. return;
  42283. }
  42284. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42285. mesh.computeBonesUsingShaders = false;
  42286. }
  42287. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42288. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42289. if (matrices) {
  42290. effect.setMatrices("mBones", matrices);
  42291. }
  42292. }
  42293. };
  42294. /**
  42295. * Binds the morph targets information from the mesh to the effect.
  42296. * @param abstractMesh The mesh we are binding the information to render
  42297. * @param effect The effect we are binding the data to
  42298. */
  42299. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42300. var manager = abstractMesh.morphTargetManager;
  42301. if (!abstractMesh || !manager) {
  42302. return;
  42303. }
  42304. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42305. };
  42306. /**
  42307. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42308. * @param defines The generated defines used in the effect
  42309. * @param effect The effect we are binding the data to
  42310. * @param scene The scene we are willing to render with logarithmic scale for
  42311. */
  42312. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42313. if (defines["LOGARITHMICDEPTH"]) {
  42314. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42315. }
  42316. };
  42317. /**
  42318. * Binds the clip plane information from the scene to the effect.
  42319. * @param scene The scene the clip plane information are extracted from
  42320. * @param effect The effect we are binding the data to
  42321. */
  42322. MaterialHelper.BindClipPlane = function (effect, scene) {
  42323. if (scene.clipPlane) {
  42324. var clipPlane = scene.clipPlane;
  42325. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42326. }
  42327. if (scene.clipPlane2) {
  42328. var clipPlane = scene.clipPlane2;
  42329. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42330. }
  42331. if (scene.clipPlane3) {
  42332. var clipPlane = scene.clipPlane3;
  42333. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42334. }
  42335. if (scene.clipPlane4) {
  42336. var clipPlane = scene.clipPlane4;
  42337. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42338. }
  42339. };
  42340. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42341. return MaterialHelper;
  42342. }());
  42343. BABYLON.MaterialHelper = MaterialHelper;
  42344. })(BABYLON || (BABYLON = {}));
  42345. //# sourceMappingURL=babylon.materialHelper.js.map
  42346. var BABYLON;
  42347. (function (BABYLON) {
  42348. /**
  42349. * Base class of materials working in push mode in babylon JS
  42350. * @hidden
  42351. */
  42352. var PushMaterial = /** @class */ (function (_super) {
  42353. __extends(PushMaterial, _super);
  42354. function PushMaterial(name, scene) {
  42355. var _this = _super.call(this, name, scene) || this;
  42356. _this._normalMatrix = new BABYLON.Matrix();
  42357. _this.storeEffectOnSubMeshes = true;
  42358. return _this;
  42359. }
  42360. PushMaterial.prototype.getEffect = function () {
  42361. return this._activeEffect;
  42362. };
  42363. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42364. if (!mesh) {
  42365. return false;
  42366. }
  42367. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42368. return true;
  42369. }
  42370. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42371. };
  42372. /**
  42373. * Binds the given world matrix to the active effect
  42374. *
  42375. * @param world the matrix to bind
  42376. */
  42377. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42378. this._activeEffect.setMatrix("world", world);
  42379. };
  42380. /**
  42381. * Binds the given normal matrix to the active effect
  42382. *
  42383. * @param normalMatrix the matrix to bind
  42384. */
  42385. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42386. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42387. };
  42388. PushMaterial.prototype.bind = function (world, mesh) {
  42389. if (!mesh) {
  42390. return;
  42391. }
  42392. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42393. };
  42394. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42395. if (effect === void 0) { effect = null; }
  42396. _super.prototype._afterBind.call(this, mesh);
  42397. this.getScene()._cachedEffect = effect;
  42398. };
  42399. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42400. if (visibility === void 0) { visibility = 1; }
  42401. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42402. };
  42403. return PushMaterial;
  42404. }(BABYLON.Material));
  42405. BABYLON.PushMaterial = PushMaterial;
  42406. })(BABYLON || (BABYLON = {}));
  42407. //# sourceMappingURL=babylon.pushMaterial.js.map
  42408. var BABYLON;
  42409. (function (BABYLON) {
  42410. /** @hidden */
  42411. var StandardMaterialDefines = /** @class */ (function (_super) {
  42412. __extends(StandardMaterialDefines, _super);
  42413. function StandardMaterialDefines() {
  42414. var _this = _super.call(this) || this;
  42415. _this.MAINUV1 = false;
  42416. _this.MAINUV2 = false;
  42417. _this.DIFFUSE = false;
  42418. _this.DIFFUSEDIRECTUV = 0;
  42419. _this.AMBIENT = false;
  42420. _this.AMBIENTDIRECTUV = 0;
  42421. _this.OPACITY = false;
  42422. _this.OPACITYDIRECTUV = 0;
  42423. _this.OPACITYRGB = false;
  42424. _this.REFLECTION = false;
  42425. _this.EMISSIVE = false;
  42426. _this.EMISSIVEDIRECTUV = 0;
  42427. _this.SPECULAR = false;
  42428. _this.SPECULARDIRECTUV = 0;
  42429. _this.BUMP = false;
  42430. _this.BUMPDIRECTUV = 0;
  42431. _this.PARALLAX = false;
  42432. _this.PARALLAXOCCLUSION = false;
  42433. _this.SPECULAROVERALPHA = false;
  42434. _this.CLIPPLANE = false;
  42435. _this.CLIPPLANE2 = false;
  42436. _this.CLIPPLANE3 = false;
  42437. _this.CLIPPLANE4 = false;
  42438. _this.ALPHATEST = false;
  42439. _this.DEPTHPREPASS = false;
  42440. _this.ALPHAFROMDIFFUSE = false;
  42441. _this.POINTSIZE = false;
  42442. _this.FOG = false;
  42443. _this.SPECULARTERM = false;
  42444. _this.DIFFUSEFRESNEL = false;
  42445. _this.OPACITYFRESNEL = false;
  42446. _this.REFLECTIONFRESNEL = false;
  42447. _this.REFRACTIONFRESNEL = false;
  42448. _this.EMISSIVEFRESNEL = false;
  42449. _this.FRESNEL = false;
  42450. _this.NORMAL = false;
  42451. _this.UV1 = false;
  42452. _this.UV2 = false;
  42453. _this.VERTEXCOLOR = false;
  42454. _this.VERTEXALPHA = false;
  42455. _this.NUM_BONE_INFLUENCERS = 0;
  42456. _this.BonesPerMesh = 0;
  42457. _this.INSTANCES = false;
  42458. _this.GLOSSINESS = false;
  42459. _this.ROUGHNESS = false;
  42460. _this.EMISSIVEASILLUMINATION = false;
  42461. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42462. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42463. _this.LIGHTMAP = false;
  42464. _this.LIGHTMAPDIRECTUV = 0;
  42465. _this.OBJECTSPACE_NORMALMAP = false;
  42466. _this.USELIGHTMAPASSHADOWMAP = false;
  42467. _this.REFLECTIONMAP_3D = false;
  42468. _this.REFLECTIONMAP_SPHERICAL = false;
  42469. _this.REFLECTIONMAP_PLANAR = false;
  42470. _this.REFLECTIONMAP_CUBIC = false;
  42471. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42472. _this.REFLECTIONMAP_PROJECTION = false;
  42473. _this.REFLECTIONMAP_SKYBOX = false;
  42474. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42475. _this.REFLECTIONMAP_EXPLICIT = false;
  42476. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42477. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42478. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42479. _this.INVERTCUBICMAP = false;
  42480. _this.LOGARITHMICDEPTH = false;
  42481. _this.REFRACTION = false;
  42482. _this.REFRACTIONMAP_3D = false;
  42483. _this.REFLECTIONOVERALPHA = false;
  42484. _this.TWOSIDEDLIGHTING = false;
  42485. _this.SHADOWFLOAT = false;
  42486. _this.MORPHTARGETS = false;
  42487. _this.MORPHTARGETS_NORMAL = false;
  42488. _this.MORPHTARGETS_TANGENT = false;
  42489. _this.NUM_MORPH_INFLUENCERS = 0;
  42490. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42491. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42492. _this.IMAGEPROCESSING = false;
  42493. _this.VIGNETTE = false;
  42494. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42495. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42496. _this.TONEMAPPING = false;
  42497. _this.TONEMAPPING_ACES = false;
  42498. _this.CONTRAST = false;
  42499. _this.COLORCURVES = false;
  42500. _this.COLORGRADING = false;
  42501. _this.COLORGRADING3D = false;
  42502. _this.SAMPLER3DGREENDEPTH = false;
  42503. _this.SAMPLER3DBGRMAP = false;
  42504. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42505. /**
  42506. * If the reflection texture on this material is in linear color space
  42507. * @hidden
  42508. */
  42509. _this.IS_REFLECTION_LINEAR = false;
  42510. /**
  42511. * If the refraction texture on this material is in linear color space
  42512. * @hidden
  42513. */
  42514. _this.IS_REFRACTION_LINEAR = false;
  42515. _this.EXPOSURE = false;
  42516. _this.rebuild();
  42517. return _this;
  42518. }
  42519. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42520. var modes = [
  42521. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42522. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42523. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42524. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42525. ];
  42526. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42527. var mode = modes_1[_i];
  42528. this[mode] = (mode === modeToEnable);
  42529. }
  42530. };
  42531. return StandardMaterialDefines;
  42532. }(BABYLON.MaterialDefines));
  42533. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42534. /**
  42535. * This is the default material used in Babylon. It is the best trade off between quality
  42536. * and performances.
  42537. * @see http://doc.babylonjs.com/babylon101/materials
  42538. */
  42539. var StandardMaterial = /** @class */ (function (_super) {
  42540. __extends(StandardMaterial, _super);
  42541. /**
  42542. * Instantiates a new standard material.
  42543. * This is the default material used in Babylon. It is the best trade off between quality
  42544. * and performances.
  42545. * @see http://doc.babylonjs.com/babylon101/materials
  42546. * @param name Define the name of the material in the scene
  42547. * @param scene Define the scene the material belong to
  42548. */
  42549. function StandardMaterial(name, scene) {
  42550. var _this = _super.call(this, name, scene) || this;
  42551. /**
  42552. * The color of the material lit by the environmental background lighting.
  42553. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  42554. */
  42555. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42556. /**
  42557. * The basic color of the material as viewed under a light.
  42558. */
  42559. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42560. /**
  42561. * Define how the color and intensity of the highlight given by the light in the material.
  42562. */
  42563. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42564. /**
  42565. * Define the color of the material as if self lit.
  42566. * This will be mixed in the final result even in the absence of light.
  42567. */
  42568. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42569. /**
  42570. * Defines how sharp are the highlights in the material.
  42571. * The bigger the value the sharper giving a more glossy feeling to the result.
  42572. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  42573. */
  42574. _this.specularPower = 64;
  42575. _this._useAlphaFromDiffuseTexture = false;
  42576. _this._useEmissiveAsIllumination = false;
  42577. _this._linkEmissiveWithDiffuse = false;
  42578. _this._useSpecularOverAlpha = false;
  42579. _this._useReflectionOverAlpha = false;
  42580. _this._disableLighting = false;
  42581. _this._useObjectSpaceNormalMap = false;
  42582. _this._useParallax = false;
  42583. _this._useParallaxOcclusion = false;
  42584. /**
  42585. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  42586. */
  42587. _this.parallaxScaleBias = 0.05;
  42588. _this._roughness = 0;
  42589. /**
  42590. * In case of refraction, define the value of the indice of refraction.
  42591. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42592. */
  42593. _this.indexOfRefraction = 0.98;
  42594. /**
  42595. * Invert the refraction texture alongside the y axis.
  42596. * It can be usefull with procedural textures or probe for instance.
  42597. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42598. */
  42599. _this.invertRefractionY = true;
  42600. /**
  42601. * Defines the alpha limits in alpha test mode.
  42602. */
  42603. _this.alphaCutOff = 0.4;
  42604. _this._useLightmapAsShadowmap = false;
  42605. _this._useReflectionFresnelFromSpecular = false;
  42606. _this._useGlossinessFromSpecularMapAlpha = false;
  42607. _this._maxSimultaneousLights = 4;
  42608. _this._invertNormalMapX = false;
  42609. _this._invertNormalMapY = false;
  42610. _this._twoSidedLighting = false;
  42611. _this._renderTargets = new BABYLON.SmartArray(16);
  42612. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42613. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42614. // Setup the default processing configuration to the scene.
  42615. _this._attachImageProcessingConfiguration(null);
  42616. _this.getRenderTargetTextures = function () {
  42617. _this._renderTargets.reset();
  42618. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42619. _this._renderTargets.push(_this._reflectionTexture);
  42620. }
  42621. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42622. _this._renderTargets.push(_this._refractionTexture);
  42623. }
  42624. return _this._renderTargets;
  42625. };
  42626. return _this;
  42627. }
  42628. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42629. /**
  42630. * Gets the image processing configuration used either in this material.
  42631. */
  42632. get: function () {
  42633. return this._imageProcessingConfiguration;
  42634. },
  42635. /**
  42636. * Sets the Default image processing configuration used either in the this material.
  42637. *
  42638. * If sets to null, the scene one is in use.
  42639. */
  42640. set: function (value) {
  42641. this._attachImageProcessingConfiguration(value);
  42642. // Ensure the effect will be rebuilt.
  42643. this._markAllSubMeshesAsTexturesDirty();
  42644. },
  42645. enumerable: true,
  42646. configurable: true
  42647. });
  42648. /**
  42649. * Attaches a new image processing configuration to the Standard Material.
  42650. * @param configuration
  42651. */
  42652. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42653. var _this = this;
  42654. if (configuration === this._imageProcessingConfiguration) {
  42655. return;
  42656. }
  42657. // Detaches observer.
  42658. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42659. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42660. }
  42661. // Pick the scene configuration if needed.
  42662. if (!configuration) {
  42663. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42664. }
  42665. else {
  42666. this._imageProcessingConfiguration = configuration;
  42667. }
  42668. // Attaches observer.
  42669. if (this._imageProcessingConfiguration) {
  42670. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42671. _this._markAllSubMeshesAsImageProcessingDirty();
  42672. });
  42673. }
  42674. };
  42675. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42676. /**
  42677. * Gets wether the color curves effect is enabled.
  42678. */
  42679. get: function () {
  42680. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42681. },
  42682. /**
  42683. * Sets wether the color curves effect is enabled.
  42684. */
  42685. set: function (value) {
  42686. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42687. },
  42688. enumerable: true,
  42689. configurable: true
  42690. });
  42691. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42692. /**
  42693. * Gets wether the color grading effect is enabled.
  42694. */
  42695. get: function () {
  42696. return this.imageProcessingConfiguration.colorGradingEnabled;
  42697. },
  42698. /**
  42699. * Gets wether the color grading effect is enabled.
  42700. */
  42701. set: function (value) {
  42702. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42703. },
  42704. enumerable: true,
  42705. configurable: true
  42706. });
  42707. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42708. /**
  42709. * Gets wether tonemapping is enabled or not.
  42710. */
  42711. get: function () {
  42712. return this._imageProcessingConfiguration.toneMappingEnabled;
  42713. },
  42714. /**
  42715. * Sets wether tonemapping is enabled or not
  42716. */
  42717. set: function (value) {
  42718. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42719. },
  42720. enumerable: true,
  42721. configurable: true
  42722. });
  42723. ;
  42724. ;
  42725. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42726. /**
  42727. * The camera exposure used on this material.
  42728. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42729. * This corresponds to a photographic exposure.
  42730. */
  42731. get: function () {
  42732. return this._imageProcessingConfiguration.exposure;
  42733. },
  42734. /**
  42735. * The camera exposure used on this material.
  42736. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42737. * This corresponds to a photographic exposure.
  42738. */
  42739. set: function (value) {
  42740. this._imageProcessingConfiguration.exposure = value;
  42741. },
  42742. enumerable: true,
  42743. configurable: true
  42744. });
  42745. ;
  42746. ;
  42747. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42748. /**
  42749. * Gets The camera contrast used on this material.
  42750. */
  42751. get: function () {
  42752. return this._imageProcessingConfiguration.contrast;
  42753. },
  42754. /**
  42755. * Sets The camera contrast used on this material.
  42756. */
  42757. set: function (value) {
  42758. this._imageProcessingConfiguration.contrast = value;
  42759. },
  42760. enumerable: true,
  42761. configurable: true
  42762. });
  42763. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42764. /**
  42765. * Gets the Color Grading 2D Lookup Texture.
  42766. */
  42767. get: function () {
  42768. return this._imageProcessingConfiguration.colorGradingTexture;
  42769. },
  42770. /**
  42771. * Sets the Color Grading 2D Lookup Texture.
  42772. */
  42773. set: function (value) {
  42774. this._imageProcessingConfiguration.colorGradingTexture = value;
  42775. },
  42776. enumerable: true,
  42777. configurable: true
  42778. });
  42779. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42780. /**
  42781. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42782. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42783. * 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;
  42784. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42785. */
  42786. get: function () {
  42787. return this._imageProcessingConfiguration.colorCurves;
  42788. },
  42789. /**
  42790. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42791. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42792. * 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;
  42793. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42794. */
  42795. set: function (value) {
  42796. this._imageProcessingConfiguration.colorCurves = value;
  42797. },
  42798. enumerable: true,
  42799. configurable: true
  42800. });
  42801. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  42802. /**
  42803. * Gets a boolean indicating that current material needs to register RTT
  42804. */
  42805. get: function () {
  42806. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42807. return true;
  42808. }
  42809. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42810. return true;
  42811. }
  42812. return false;
  42813. },
  42814. enumerable: true,
  42815. configurable: true
  42816. });
  42817. /**
  42818. * Gets the current class name of the material e.g. "StandardMaterial"
  42819. * Mainly use in serialization.
  42820. * @returns the class name
  42821. */
  42822. StandardMaterial.prototype.getClassName = function () {
  42823. return "StandardMaterial";
  42824. };
  42825. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42826. /**
  42827. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  42828. * You can try switching to logarithmic depth.
  42829. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  42830. */
  42831. get: function () {
  42832. return this._useLogarithmicDepth;
  42833. },
  42834. set: function (value) {
  42835. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42836. this._markAllSubMeshesAsMiscDirty();
  42837. },
  42838. enumerable: true,
  42839. configurable: true
  42840. });
  42841. /**
  42842. * Specifies if the material will require alpha blending
  42843. * @returns a boolean specifying if alpha blending is needed
  42844. */
  42845. StandardMaterial.prototype.needAlphaBlending = function () {
  42846. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42847. };
  42848. /**
  42849. * Specifies if this material should be rendered in alpha test mode
  42850. * @returns a boolean specifying if an alpha test is needed.
  42851. */
  42852. StandardMaterial.prototype.needAlphaTesting = function () {
  42853. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42854. };
  42855. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42856. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42857. };
  42858. /**
  42859. * Get the texture used for alpha test purpose.
  42860. * @returns the diffuse texture in case of the standard material.
  42861. */
  42862. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42863. return this._diffuseTexture;
  42864. };
  42865. /**
  42866. * Get if the submesh is ready to be used and all its information available.
  42867. * Child classes can use it to update shaders
  42868. * @param mesh defines the mesh to check
  42869. * @param subMesh defines which submesh to check
  42870. * @param useInstances specifies that instances should be used
  42871. * @returns a boolean indicating that the submesh is ready or not
  42872. */
  42873. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42874. if (useInstances === void 0) { useInstances = false; }
  42875. if (subMesh.effect && this.isFrozen) {
  42876. if (this._wasPreviouslyReady) {
  42877. return true;
  42878. }
  42879. }
  42880. if (!subMesh._materialDefines) {
  42881. subMesh._materialDefines = new StandardMaterialDefines();
  42882. }
  42883. var scene = this.getScene();
  42884. var defines = subMesh._materialDefines;
  42885. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42886. if (defines._renderId === scene.getRenderId()) {
  42887. return true;
  42888. }
  42889. }
  42890. var engine = scene.getEngine();
  42891. // Lights
  42892. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42893. // Textures
  42894. if (defines._areTexturesDirty) {
  42895. defines._needUVs = false;
  42896. defines.MAINUV1 = false;
  42897. defines.MAINUV2 = false;
  42898. if (scene.texturesEnabled) {
  42899. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42900. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42901. return false;
  42902. }
  42903. else {
  42904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42905. }
  42906. }
  42907. else {
  42908. defines.DIFFUSE = false;
  42909. }
  42910. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42911. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42912. return false;
  42913. }
  42914. else {
  42915. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42916. }
  42917. }
  42918. else {
  42919. defines.AMBIENT = false;
  42920. }
  42921. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42922. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42923. return false;
  42924. }
  42925. else {
  42926. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42927. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42928. }
  42929. }
  42930. else {
  42931. defines.OPACITY = false;
  42932. }
  42933. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42934. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42935. return false;
  42936. }
  42937. else {
  42938. defines._needNormals = true;
  42939. defines.REFLECTION = true;
  42940. defines.ROUGHNESS = (this._roughness > 0);
  42941. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42942. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42943. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42944. switch (this._reflectionTexture.coordinatesMode) {
  42945. case BABYLON.Texture.EXPLICIT_MODE:
  42946. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42947. break;
  42948. case BABYLON.Texture.PLANAR_MODE:
  42949. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42950. break;
  42951. case BABYLON.Texture.PROJECTION_MODE:
  42952. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42953. break;
  42954. case BABYLON.Texture.SKYBOX_MODE:
  42955. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42956. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42957. break;
  42958. case BABYLON.Texture.SPHERICAL_MODE:
  42959. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42960. break;
  42961. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42962. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42963. break;
  42964. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42965. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42966. break;
  42967. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42968. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42969. break;
  42970. case BABYLON.Texture.CUBIC_MODE:
  42971. case BABYLON.Texture.INVCUBIC_MODE:
  42972. default:
  42973. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42974. break;
  42975. }
  42976. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42977. }
  42978. }
  42979. else {
  42980. defines.REFLECTION = false;
  42981. }
  42982. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42983. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42984. return false;
  42985. }
  42986. else {
  42987. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42988. }
  42989. }
  42990. else {
  42991. defines.EMISSIVE = false;
  42992. }
  42993. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42994. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42995. return false;
  42996. }
  42997. else {
  42998. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42999. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43000. }
  43001. }
  43002. else {
  43003. defines.LIGHTMAP = false;
  43004. }
  43005. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43006. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43007. return false;
  43008. }
  43009. else {
  43010. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43011. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43012. }
  43013. }
  43014. else {
  43015. defines.SPECULAR = false;
  43016. }
  43017. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43018. // Bump texure can not be not blocking.
  43019. if (!this._bumpTexture.isReady()) {
  43020. return false;
  43021. }
  43022. else {
  43023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43024. defines.PARALLAX = this._useParallax;
  43025. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43026. }
  43027. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43028. }
  43029. else {
  43030. defines.BUMP = false;
  43031. }
  43032. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43033. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43034. return false;
  43035. }
  43036. else {
  43037. defines._needUVs = true;
  43038. defines.REFRACTION = true;
  43039. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43040. }
  43041. }
  43042. else {
  43043. defines.REFRACTION = false;
  43044. }
  43045. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43046. }
  43047. else {
  43048. defines.DIFFUSE = false;
  43049. defines.AMBIENT = false;
  43050. defines.OPACITY = false;
  43051. defines.REFLECTION = false;
  43052. defines.EMISSIVE = false;
  43053. defines.LIGHTMAP = false;
  43054. defines.BUMP = false;
  43055. defines.REFRACTION = false;
  43056. }
  43057. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43058. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43059. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43060. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43061. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43062. }
  43063. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43064. if (!this._imageProcessingConfiguration.isReady()) {
  43065. return false;
  43066. }
  43067. this._imageProcessingConfiguration.prepareDefines(defines);
  43068. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43069. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43070. }
  43071. if (defines._areFresnelDirty) {
  43072. if (StandardMaterial.FresnelEnabled) {
  43073. // Fresnel
  43074. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43075. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43076. this._reflectionFresnelParameters) {
  43077. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43078. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43079. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43080. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43081. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43082. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43083. defines._needNormals = true;
  43084. defines.FRESNEL = true;
  43085. }
  43086. }
  43087. else {
  43088. defines.FRESNEL = false;
  43089. }
  43090. }
  43091. // Misc.
  43092. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43093. // Attribs
  43094. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43095. // Values that need to be evaluated on every frame
  43096. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43097. // Get correct effect
  43098. if (defines.isDirty) {
  43099. defines.markAsProcessed();
  43100. scene.resetCachedMaterial();
  43101. // Fallbacks
  43102. var fallbacks = new BABYLON.EffectFallbacks();
  43103. if (defines.REFLECTION) {
  43104. fallbacks.addFallback(0, "REFLECTION");
  43105. }
  43106. if (defines.SPECULAR) {
  43107. fallbacks.addFallback(0, "SPECULAR");
  43108. }
  43109. if (defines.BUMP) {
  43110. fallbacks.addFallback(0, "BUMP");
  43111. }
  43112. if (defines.PARALLAX) {
  43113. fallbacks.addFallback(1, "PARALLAX");
  43114. }
  43115. if (defines.PARALLAXOCCLUSION) {
  43116. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43117. }
  43118. if (defines.SPECULAROVERALPHA) {
  43119. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43120. }
  43121. if (defines.FOG) {
  43122. fallbacks.addFallback(1, "FOG");
  43123. }
  43124. if (defines.POINTSIZE) {
  43125. fallbacks.addFallback(0, "POINTSIZE");
  43126. }
  43127. if (defines.LOGARITHMICDEPTH) {
  43128. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43129. }
  43130. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43131. if (defines.SPECULARTERM) {
  43132. fallbacks.addFallback(0, "SPECULARTERM");
  43133. }
  43134. if (defines.DIFFUSEFRESNEL) {
  43135. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43136. }
  43137. if (defines.OPACITYFRESNEL) {
  43138. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43139. }
  43140. if (defines.REFLECTIONFRESNEL) {
  43141. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43142. }
  43143. if (defines.EMISSIVEFRESNEL) {
  43144. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43145. }
  43146. if (defines.FRESNEL) {
  43147. fallbacks.addFallback(4, "FRESNEL");
  43148. }
  43149. //Attributes
  43150. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43151. if (defines.NORMAL) {
  43152. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43153. }
  43154. if (defines.UV1) {
  43155. attribs.push(BABYLON.VertexBuffer.UVKind);
  43156. }
  43157. if (defines.UV2) {
  43158. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43159. }
  43160. if (defines.VERTEXCOLOR) {
  43161. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43162. }
  43163. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43164. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43165. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43166. var shaderName = "default";
  43167. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43168. "vFogInfos", "vFogColor", "pointSize",
  43169. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43170. "mBones",
  43171. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43172. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43173. "vReflectionPosition", "vReflectionSize",
  43174. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43175. ];
  43176. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43177. var uniformBuffers = ["Material", "Scene"];
  43178. if (BABYLON.ImageProcessingConfiguration) {
  43179. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43180. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43181. }
  43182. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43183. uniformsNames: uniforms,
  43184. uniformBuffersNames: uniformBuffers,
  43185. samplers: samplers,
  43186. defines: defines,
  43187. maxSimultaneousLights: this._maxSimultaneousLights
  43188. });
  43189. if (this.customShaderNameResolve) {
  43190. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43191. }
  43192. var join = defines.toString();
  43193. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43194. attributes: attribs,
  43195. uniformsNames: uniforms,
  43196. uniformBuffersNames: uniformBuffers,
  43197. samplers: samplers,
  43198. defines: join,
  43199. fallbacks: fallbacks,
  43200. onCompiled: this.onCompiled,
  43201. onError: this.onError,
  43202. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43203. }, engine), defines);
  43204. this.buildUniformLayout();
  43205. }
  43206. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43207. return false;
  43208. }
  43209. defines._renderId = scene.getRenderId();
  43210. this._wasPreviouslyReady = true;
  43211. return true;
  43212. };
  43213. /**
  43214. * Builds the material UBO layouts.
  43215. * Used internally during the effect preparation.
  43216. */
  43217. StandardMaterial.prototype.buildUniformLayout = function () {
  43218. // Order is important !
  43219. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43220. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43221. this._uniformBuffer.addUniform("opacityParts", 4);
  43222. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43223. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43224. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43225. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43226. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43227. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43228. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43229. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43230. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43231. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43232. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43233. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43234. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43235. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43236. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43237. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43238. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43239. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43240. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43241. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43242. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43243. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43244. this._uniformBuffer.addUniform("specularMatrix", 16);
  43245. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43246. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43247. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43248. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43249. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43250. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43251. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43252. this._uniformBuffer.addUniform("pointSize", 1);
  43253. this._uniformBuffer.create();
  43254. };
  43255. /**
  43256. * Unbinds the material from the mesh
  43257. */
  43258. StandardMaterial.prototype.unbind = function () {
  43259. if (this._activeEffect) {
  43260. var needFlag = false;
  43261. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43262. this._activeEffect.setTexture("reflection2DSampler", null);
  43263. needFlag = true;
  43264. }
  43265. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43266. this._activeEffect.setTexture("refraction2DSampler", null);
  43267. needFlag = true;
  43268. }
  43269. if (needFlag) {
  43270. this._markAllSubMeshesAsTexturesDirty();
  43271. }
  43272. }
  43273. _super.prototype.unbind.call(this);
  43274. };
  43275. /**
  43276. * Binds the submesh to this material by preparing the effect and shader to draw
  43277. * @param world defines the world transformation matrix
  43278. * @param mesh defines the mesh containing the submesh
  43279. * @param subMesh defines the submesh to bind the material to
  43280. */
  43281. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43282. var scene = this.getScene();
  43283. var defines = subMesh._materialDefines;
  43284. if (!defines) {
  43285. return;
  43286. }
  43287. var effect = subMesh.effect;
  43288. if (!effect) {
  43289. return;
  43290. }
  43291. this._activeEffect = effect;
  43292. // Matrices
  43293. this.bindOnlyWorldMatrix(world);
  43294. // Normal Matrix
  43295. if (defines.OBJECTSPACE_NORMALMAP) {
  43296. world.toNormalMatrix(this._normalMatrix);
  43297. this.bindOnlyNormalMatrix(this._normalMatrix);
  43298. }
  43299. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43300. // Bones
  43301. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43302. if (mustRebind) {
  43303. this._uniformBuffer.bindToEffect(effect, "Material");
  43304. this.bindViewProjection(effect);
  43305. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43306. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43307. // Fresnel
  43308. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43309. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43310. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43311. }
  43312. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43313. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43314. }
  43315. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43316. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43317. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43318. }
  43319. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43320. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43321. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43322. }
  43323. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43324. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43325. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43326. }
  43327. }
  43328. // Textures
  43329. if (scene.texturesEnabled) {
  43330. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43331. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43332. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43333. if (this._diffuseTexture.hasAlpha) {
  43334. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43335. }
  43336. }
  43337. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43338. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43339. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43340. }
  43341. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43342. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43343. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43344. }
  43345. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43346. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43347. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43348. if (this._reflectionTexture.boundingBoxSize) {
  43349. var cubeTexture = this._reflectionTexture;
  43350. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43351. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43352. }
  43353. }
  43354. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43355. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43356. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43357. }
  43358. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43359. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43360. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43361. }
  43362. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43363. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43364. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43365. }
  43366. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43367. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43368. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43369. if (scene._mirroredCameraPosition) {
  43370. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43371. }
  43372. else {
  43373. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43374. }
  43375. }
  43376. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43377. var depth = 1.0;
  43378. if (!this._refractionTexture.isCube) {
  43379. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43380. if (this._refractionTexture.depth) {
  43381. depth = this._refractionTexture.depth;
  43382. }
  43383. }
  43384. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43385. }
  43386. }
  43387. // Point size
  43388. if (this.pointsCloud) {
  43389. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43390. }
  43391. if (defines.SPECULARTERM) {
  43392. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43393. }
  43394. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43395. // Diffuse
  43396. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43397. }
  43398. // Textures
  43399. if (scene.texturesEnabled) {
  43400. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43401. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43402. }
  43403. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43404. effect.setTexture("ambientSampler", this._ambientTexture);
  43405. }
  43406. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43407. effect.setTexture("opacitySampler", this._opacityTexture);
  43408. }
  43409. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43410. if (this._reflectionTexture.isCube) {
  43411. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43412. }
  43413. else {
  43414. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43415. }
  43416. }
  43417. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43418. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43419. }
  43420. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43421. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43422. }
  43423. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43424. effect.setTexture("specularSampler", this._specularTexture);
  43425. }
  43426. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43427. effect.setTexture("bumpSampler", this._bumpTexture);
  43428. }
  43429. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43430. var depth = 1.0;
  43431. if (this._refractionTexture.isCube) {
  43432. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43433. }
  43434. else {
  43435. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43436. }
  43437. }
  43438. }
  43439. // Clip plane
  43440. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43441. // Colors
  43442. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43443. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43444. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43445. }
  43446. if (mustRebind || !this.isFrozen) {
  43447. // Lights
  43448. if (scene.lightsEnabled && !this._disableLighting) {
  43449. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43450. }
  43451. // View
  43452. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43453. this.bindView(effect);
  43454. }
  43455. // Fog
  43456. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43457. // Morph targets
  43458. if (defines.NUM_MORPH_INFLUENCERS) {
  43459. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43460. }
  43461. // Log. depth
  43462. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43463. // image processing
  43464. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43465. this._imageProcessingConfiguration.bind(this._activeEffect);
  43466. }
  43467. }
  43468. this._uniformBuffer.update();
  43469. this._afterBind(mesh, this._activeEffect);
  43470. };
  43471. /**
  43472. * Get the list of animatables in the material.
  43473. * @returns the list of animatables object used in the material
  43474. */
  43475. StandardMaterial.prototype.getAnimatables = function () {
  43476. var results = [];
  43477. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43478. results.push(this._diffuseTexture);
  43479. }
  43480. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43481. results.push(this._ambientTexture);
  43482. }
  43483. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43484. results.push(this._opacityTexture);
  43485. }
  43486. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43487. results.push(this._reflectionTexture);
  43488. }
  43489. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43490. results.push(this._emissiveTexture);
  43491. }
  43492. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43493. results.push(this._specularTexture);
  43494. }
  43495. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43496. results.push(this._bumpTexture);
  43497. }
  43498. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43499. results.push(this._lightmapTexture);
  43500. }
  43501. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43502. results.push(this._refractionTexture);
  43503. }
  43504. return results;
  43505. };
  43506. /**
  43507. * Gets the active textures from the material
  43508. * @returns an array of textures
  43509. */
  43510. StandardMaterial.prototype.getActiveTextures = function () {
  43511. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43512. if (this._diffuseTexture) {
  43513. activeTextures.push(this._diffuseTexture);
  43514. }
  43515. if (this._ambientTexture) {
  43516. activeTextures.push(this._ambientTexture);
  43517. }
  43518. if (this._opacityTexture) {
  43519. activeTextures.push(this._opacityTexture);
  43520. }
  43521. if (this._reflectionTexture) {
  43522. activeTextures.push(this._reflectionTexture);
  43523. }
  43524. if (this._emissiveTexture) {
  43525. activeTextures.push(this._emissiveTexture);
  43526. }
  43527. if (this._specularTexture) {
  43528. activeTextures.push(this._specularTexture);
  43529. }
  43530. if (this._bumpTexture) {
  43531. activeTextures.push(this._bumpTexture);
  43532. }
  43533. if (this._lightmapTexture) {
  43534. activeTextures.push(this._lightmapTexture);
  43535. }
  43536. if (this._refractionTexture) {
  43537. activeTextures.push(this._refractionTexture);
  43538. }
  43539. return activeTextures;
  43540. };
  43541. /**
  43542. * Specifies if the material uses a texture
  43543. * @param texture defines the texture to check against the material
  43544. * @returns a boolean specifying if the material uses the texture
  43545. */
  43546. StandardMaterial.prototype.hasTexture = function (texture) {
  43547. if (_super.prototype.hasTexture.call(this, texture)) {
  43548. return true;
  43549. }
  43550. if (this._diffuseTexture === texture) {
  43551. return true;
  43552. }
  43553. if (this._ambientTexture === texture) {
  43554. return true;
  43555. }
  43556. if (this._opacityTexture === texture) {
  43557. return true;
  43558. }
  43559. if (this._reflectionTexture === texture) {
  43560. return true;
  43561. }
  43562. if (this._emissiveTexture === texture) {
  43563. return true;
  43564. }
  43565. if (this._specularTexture === texture) {
  43566. return true;
  43567. }
  43568. if (this._bumpTexture === texture) {
  43569. return true;
  43570. }
  43571. if (this._lightmapTexture === texture) {
  43572. return true;
  43573. }
  43574. if (this._refractionTexture === texture) {
  43575. return true;
  43576. }
  43577. return false;
  43578. };
  43579. /**
  43580. * Disposes the material
  43581. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  43582. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  43583. */
  43584. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43585. if (forceDisposeTextures) {
  43586. if (this._diffuseTexture) {
  43587. this._diffuseTexture.dispose();
  43588. }
  43589. if (this._ambientTexture) {
  43590. this._ambientTexture.dispose();
  43591. }
  43592. if (this._opacityTexture) {
  43593. this._opacityTexture.dispose();
  43594. }
  43595. if (this._reflectionTexture) {
  43596. this._reflectionTexture.dispose();
  43597. }
  43598. if (this._emissiveTexture) {
  43599. this._emissiveTexture.dispose();
  43600. }
  43601. if (this._specularTexture) {
  43602. this._specularTexture.dispose();
  43603. }
  43604. if (this._bumpTexture) {
  43605. this._bumpTexture.dispose();
  43606. }
  43607. if (this._lightmapTexture) {
  43608. this._lightmapTexture.dispose();
  43609. }
  43610. if (this._refractionTexture) {
  43611. this._refractionTexture.dispose();
  43612. }
  43613. }
  43614. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43615. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43616. }
  43617. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43618. };
  43619. /**
  43620. * Makes a duplicate of the material, and gives it a new name
  43621. * @param name defines the new name for the duplicated material
  43622. * @returns the cloned material
  43623. */
  43624. StandardMaterial.prototype.clone = function (name) {
  43625. var _this = this;
  43626. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43627. result.name = name;
  43628. result.id = name;
  43629. return result;
  43630. };
  43631. /**
  43632. * Serializes this material in a JSON representation
  43633. * @returns the serialized material object
  43634. */
  43635. StandardMaterial.prototype.serialize = function () {
  43636. return BABYLON.SerializationHelper.Serialize(this);
  43637. };
  43638. /**
  43639. * Creates a standard material from parsed material data
  43640. * @param source defines the JSON represnetation of the material
  43641. * @param scene defines the hosting scene
  43642. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  43643. * @returns a new material
  43644. */
  43645. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43646. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43647. };
  43648. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43649. /**
  43650. * Are diffuse textures enabled in the application.
  43651. */
  43652. get: function () {
  43653. return StandardMaterial._DiffuseTextureEnabled;
  43654. },
  43655. set: function (value) {
  43656. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43657. return;
  43658. }
  43659. StandardMaterial._DiffuseTextureEnabled = value;
  43660. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43661. },
  43662. enumerable: true,
  43663. configurable: true
  43664. });
  43665. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43666. /**
  43667. * Are ambient textures enabled in the application.
  43668. */
  43669. get: function () {
  43670. return StandardMaterial._AmbientTextureEnabled;
  43671. },
  43672. set: function (value) {
  43673. if (StandardMaterial._AmbientTextureEnabled === value) {
  43674. return;
  43675. }
  43676. StandardMaterial._AmbientTextureEnabled = value;
  43677. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43678. },
  43679. enumerable: true,
  43680. configurable: true
  43681. });
  43682. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43683. /**
  43684. * Are opacity textures enabled in the application.
  43685. */
  43686. get: function () {
  43687. return StandardMaterial._OpacityTextureEnabled;
  43688. },
  43689. set: function (value) {
  43690. if (StandardMaterial._OpacityTextureEnabled === value) {
  43691. return;
  43692. }
  43693. StandardMaterial._OpacityTextureEnabled = value;
  43694. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43695. },
  43696. enumerable: true,
  43697. configurable: true
  43698. });
  43699. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43700. /**
  43701. * Are reflection textures enabled in the application.
  43702. */
  43703. get: function () {
  43704. return StandardMaterial._ReflectionTextureEnabled;
  43705. },
  43706. set: function (value) {
  43707. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43708. return;
  43709. }
  43710. StandardMaterial._ReflectionTextureEnabled = value;
  43711. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43712. },
  43713. enumerable: true,
  43714. configurable: true
  43715. });
  43716. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43717. /**
  43718. * Are emissive textures enabled in the application.
  43719. */
  43720. get: function () {
  43721. return StandardMaterial._EmissiveTextureEnabled;
  43722. },
  43723. set: function (value) {
  43724. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43725. return;
  43726. }
  43727. StandardMaterial._EmissiveTextureEnabled = value;
  43728. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43729. },
  43730. enumerable: true,
  43731. configurable: true
  43732. });
  43733. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43734. /**
  43735. * Are specular textures enabled in the application.
  43736. */
  43737. get: function () {
  43738. return StandardMaterial._SpecularTextureEnabled;
  43739. },
  43740. set: function (value) {
  43741. if (StandardMaterial._SpecularTextureEnabled === value) {
  43742. return;
  43743. }
  43744. StandardMaterial._SpecularTextureEnabled = value;
  43745. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43746. },
  43747. enumerable: true,
  43748. configurable: true
  43749. });
  43750. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43751. /**
  43752. * Are bump textures enabled in the application.
  43753. */
  43754. get: function () {
  43755. return StandardMaterial._BumpTextureEnabled;
  43756. },
  43757. set: function (value) {
  43758. if (StandardMaterial._BumpTextureEnabled === value) {
  43759. return;
  43760. }
  43761. StandardMaterial._BumpTextureEnabled = value;
  43762. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43763. },
  43764. enumerable: true,
  43765. configurable: true
  43766. });
  43767. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43768. /**
  43769. * Are lightmap textures enabled in the application.
  43770. */
  43771. get: function () {
  43772. return StandardMaterial._LightmapTextureEnabled;
  43773. },
  43774. set: function (value) {
  43775. if (StandardMaterial._LightmapTextureEnabled === value) {
  43776. return;
  43777. }
  43778. StandardMaterial._LightmapTextureEnabled = value;
  43779. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43780. },
  43781. enumerable: true,
  43782. configurable: true
  43783. });
  43784. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43785. /**
  43786. * Are refraction textures enabled in the application.
  43787. */
  43788. get: function () {
  43789. return StandardMaterial._RefractionTextureEnabled;
  43790. },
  43791. set: function (value) {
  43792. if (StandardMaterial._RefractionTextureEnabled === value) {
  43793. return;
  43794. }
  43795. StandardMaterial._RefractionTextureEnabled = value;
  43796. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43797. },
  43798. enumerable: true,
  43799. configurable: true
  43800. });
  43801. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43802. /**
  43803. * Are color grading textures enabled in the application.
  43804. */
  43805. get: function () {
  43806. return StandardMaterial._ColorGradingTextureEnabled;
  43807. },
  43808. set: function (value) {
  43809. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43810. return;
  43811. }
  43812. StandardMaterial._ColorGradingTextureEnabled = value;
  43813. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43814. },
  43815. enumerable: true,
  43816. configurable: true
  43817. });
  43818. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43819. /**
  43820. * Are fresnels enabled in the application.
  43821. */
  43822. get: function () {
  43823. return StandardMaterial._FresnelEnabled;
  43824. },
  43825. set: function (value) {
  43826. if (StandardMaterial._FresnelEnabled === value) {
  43827. return;
  43828. }
  43829. StandardMaterial._FresnelEnabled = value;
  43830. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43831. },
  43832. enumerable: true,
  43833. configurable: true
  43834. });
  43835. // Flags used to enable or disable a type of texture for all Standard Materials
  43836. StandardMaterial._DiffuseTextureEnabled = true;
  43837. StandardMaterial._AmbientTextureEnabled = true;
  43838. StandardMaterial._OpacityTextureEnabled = true;
  43839. StandardMaterial._ReflectionTextureEnabled = true;
  43840. StandardMaterial._EmissiveTextureEnabled = true;
  43841. StandardMaterial._SpecularTextureEnabled = true;
  43842. StandardMaterial._BumpTextureEnabled = true;
  43843. StandardMaterial._LightmapTextureEnabled = true;
  43844. StandardMaterial._RefractionTextureEnabled = true;
  43845. StandardMaterial._ColorGradingTextureEnabled = true;
  43846. StandardMaterial._FresnelEnabled = true;
  43847. __decorate([
  43848. BABYLON.serializeAsTexture("diffuseTexture")
  43849. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43850. __decorate([
  43851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43852. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43853. __decorate([
  43854. BABYLON.serializeAsTexture("ambientTexture")
  43855. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43856. __decorate([
  43857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43858. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43859. __decorate([
  43860. BABYLON.serializeAsTexture("opacityTexture")
  43861. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43862. __decorate([
  43863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43864. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43865. __decorate([
  43866. BABYLON.serializeAsTexture("reflectionTexture")
  43867. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43868. __decorate([
  43869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43870. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43871. __decorate([
  43872. BABYLON.serializeAsTexture("emissiveTexture")
  43873. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43874. __decorate([
  43875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43876. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43877. __decorate([
  43878. BABYLON.serializeAsTexture("specularTexture")
  43879. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43880. __decorate([
  43881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43882. ], StandardMaterial.prototype, "specularTexture", void 0);
  43883. __decorate([
  43884. BABYLON.serializeAsTexture("bumpTexture")
  43885. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43886. __decorate([
  43887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43888. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43889. __decorate([
  43890. BABYLON.serializeAsTexture("lightmapTexture")
  43891. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43892. __decorate([
  43893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43894. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43895. __decorate([
  43896. BABYLON.serializeAsTexture("refractionTexture")
  43897. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43898. __decorate([
  43899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43900. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43901. __decorate([
  43902. BABYLON.serializeAsColor3("ambient")
  43903. ], StandardMaterial.prototype, "ambientColor", void 0);
  43904. __decorate([
  43905. BABYLON.serializeAsColor3("diffuse")
  43906. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43907. __decorate([
  43908. BABYLON.serializeAsColor3("specular")
  43909. ], StandardMaterial.prototype, "specularColor", void 0);
  43910. __decorate([
  43911. BABYLON.serializeAsColor3("emissive")
  43912. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43913. __decorate([
  43914. BABYLON.serialize()
  43915. ], StandardMaterial.prototype, "specularPower", void 0);
  43916. __decorate([
  43917. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43918. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43919. __decorate([
  43920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43921. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43922. __decorate([
  43923. BABYLON.serialize("useEmissiveAsIllumination")
  43924. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43925. __decorate([
  43926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43927. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43928. __decorate([
  43929. BABYLON.serialize("linkEmissiveWithDiffuse")
  43930. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43931. __decorate([
  43932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43933. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43934. __decorate([
  43935. BABYLON.serialize("useSpecularOverAlpha")
  43936. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43937. __decorate([
  43938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43939. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43940. __decorate([
  43941. BABYLON.serialize("useReflectionOverAlpha")
  43942. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43943. __decorate([
  43944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43945. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43946. __decorate([
  43947. BABYLON.serialize("disableLighting")
  43948. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43949. __decorate([
  43950. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43951. ], StandardMaterial.prototype, "disableLighting", void 0);
  43952. __decorate([
  43953. BABYLON.serialize("useObjectSpaceNormalMap")
  43954. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43955. __decorate([
  43956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43957. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43958. __decorate([
  43959. BABYLON.serialize("useParallax")
  43960. ], StandardMaterial.prototype, "_useParallax", void 0);
  43961. __decorate([
  43962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43963. ], StandardMaterial.prototype, "useParallax", void 0);
  43964. __decorate([
  43965. BABYLON.serialize("useParallaxOcclusion")
  43966. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43967. __decorate([
  43968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43969. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43970. __decorate([
  43971. BABYLON.serialize()
  43972. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43973. __decorate([
  43974. BABYLON.serialize("roughness")
  43975. ], StandardMaterial.prototype, "_roughness", void 0);
  43976. __decorate([
  43977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43978. ], StandardMaterial.prototype, "roughness", void 0);
  43979. __decorate([
  43980. BABYLON.serialize()
  43981. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43982. __decorate([
  43983. BABYLON.serialize()
  43984. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43985. __decorate([
  43986. BABYLON.serialize()
  43987. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43988. __decorate([
  43989. BABYLON.serialize("useLightmapAsShadowmap")
  43990. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43991. __decorate([
  43992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43993. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43994. __decorate([
  43995. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43996. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43997. __decorate([
  43998. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43999. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44000. __decorate([
  44001. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44002. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44003. __decorate([
  44004. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44005. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44006. __decorate([
  44007. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44008. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44009. __decorate([
  44010. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44011. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44012. __decorate([
  44013. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44014. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44015. __decorate([
  44016. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44017. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44018. __decorate([
  44019. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44020. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44021. __decorate([
  44022. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44023. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44024. __decorate([
  44025. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44026. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44027. __decorate([
  44028. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44029. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44030. __decorate([
  44031. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44032. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44033. __decorate([
  44034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44035. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44036. __decorate([
  44037. BABYLON.serialize("maxSimultaneousLights")
  44038. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44039. __decorate([
  44040. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44041. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44042. __decorate([
  44043. BABYLON.serialize("invertNormalMapX")
  44044. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44045. __decorate([
  44046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44047. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44048. __decorate([
  44049. BABYLON.serialize("invertNormalMapY")
  44050. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44051. __decorate([
  44052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44053. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44054. __decorate([
  44055. BABYLON.serialize("twoSidedLighting")
  44056. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44057. __decorate([
  44058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44059. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44060. __decorate([
  44061. BABYLON.serialize()
  44062. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44063. return StandardMaterial;
  44064. }(BABYLON.PushMaterial));
  44065. BABYLON.StandardMaterial = StandardMaterial;
  44066. })(BABYLON || (BABYLON = {}));
  44067. //# sourceMappingURL=babylon.standardMaterial.js.map
  44068. var BABYLON;
  44069. (function (BABYLON) {
  44070. /**
  44071. * Class representing spherical polynomial coefficients to the 3rd degree
  44072. */
  44073. var SphericalPolynomial = /** @class */ (function () {
  44074. function SphericalPolynomial() {
  44075. /**
  44076. * The x coefficients of the spherical polynomial
  44077. */
  44078. this.x = BABYLON.Vector3.Zero();
  44079. /**
  44080. * The y coefficients of the spherical polynomial
  44081. */
  44082. this.y = BABYLON.Vector3.Zero();
  44083. /**
  44084. * The z coefficients of the spherical polynomial
  44085. */
  44086. this.z = BABYLON.Vector3.Zero();
  44087. /**
  44088. * The xx coefficients of the spherical polynomial
  44089. */
  44090. this.xx = BABYLON.Vector3.Zero();
  44091. /**
  44092. * The yy coefficients of the spherical polynomial
  44093. */
  44094. this.yy = BABYLON.Vector3.Zero();
  44095. /**
  44096. * The zz coefficients of the spherical polynomial
  44097. */
  44098. this.zz = BABYLON.Vector3.Zero();
  44099. /**
  44100. * The xy coefficients of the spherical polynomial
  44101. */
  44102. this.xy = BABYLON.Vector3.Zero();
  44103. /**
  44104. * The yz coefficients of the spherical polynomial
  44105. */
  44106. this.yz = BABYLON.Vector3.Zero();
  44107. /**
  44108. * The zx coefficients of the spherical polynomial
  44109. */
  44110. this.zx = BABYLON.Vector3.Zero();
  44111. }
  44112. /**
  44113. * Adds an ambient color to the spherical polynomial
  44114. * @param color the color to add
  44115. */
  44116. SphericalPolynomial.prototype.addAmbient = function (color) {
  44117. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44118. this.xx = this.xx.add(colorVector);
  44119. this.yy = this.yy.add(colorVector);
  44120. this.zz = this.zz.add(colorVector);
  44121. };
  44122. /**
  44123. * Scales the spherical polynomial by the given amount
  44124. * @param scale the amount to scale
  44125. */
  44126. SphericalPolynomial.prototype.scale = function (scale) {
  44127. this.x = this.x.scale(scale);
  44128. this.y = this.y.scale(scale);
  44129. this.z = this.z.scale(scale);
  44130. this.xx = this.xx.scale(scale);
  44131. this.yy = this.yy.scale(scale);
  44132. this.zz = this.zz.scale(scale);
  44133. this.yz = this.yz.scale(scale);
  44134. this.zx = this.zx.scale(scale);
  44135. this.xy = this.xy.scale(scale);
  44136. };
  44137. /**
  44138. * Gets the spherical polynomial from harmonics
  44139. * @param harmonics the spherical harmonics
  44140. * @returns the spherical polynomial
  44141. */
  44142. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44143. var result = new SphericalPolynomial();
  44144. result.x = harmonics.l11.scale(1.02333);
  44145. result.y = harmonics.l1_1.scale(1.02333);
  44146. result.z = harmonics.l10.scale(1.02333);
  44147. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44148. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44149. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44150. result.yz = harmonics.l2_1.scale(0.858086);
  44151. result.zx = harmonics.l21.scale(0.858086);
  44152. result.xy = harmonics.l2_2.scale(0.858086);
  44153. result.scale(1.0 / Math.PI);
  44154. return result;
  44155. };
  44156. /**
  44157. * Constructs a spherical polynomial from an array.
  44158. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44159. * @returns the spherical polynomial
  44160. */
  44161. SphericalPolynomial.FromArray = function (data) {
  44162. var sp = new SphericalPolynomial();
  44163. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44164. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44165. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44166. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44167. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44168. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44169. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44170. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44171. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44172. return sp;
  44173. };
  44174. return SphericalPolynomial;
  44175. }());
  44176. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44177. /**
  44178. * Class representing spherical harmonics coefficients to the 3rd degree
  44179. */
  44180. var SphericalHarmonics = /** @class */ (function () {
  44181. function SphericalHarmonics() {
  44182. /**
  44183. * The l0,0 coefficients of the spherical harmonics
  44184. */
  44185. this.l00 = BABYLON.Vector3.Zero();
  44186. /**
  44187. * The l1,-1 coefficients of the spherical harmonics
  44188. */
  44189. this.l1_1 = BABYLON.Vector3.Zero();
  44190. /**
  44191. * The l1,0 coefficients of the spherical harmonics
  44192. */
  44193. this.l10 = BABYLON.Vector3.Zero();
  44194. /**
  44195. * The l1,1 coefficients of the spherical harmonics
  44196. */
  44197. this.l11 = BABYLON.Vector3.Zero();
  44198. /**
  44199. * The l2,-2 coefficients of the spherical harmonics
  44200. */
  44201. this.l2_2 = BABYLON.Vector3.Zero();
  44202. /**
  44203. * The l2,-1 coefficients of the spherical harmonics
  44204. */
  44205. this.l2_1 = BABYLON.Vector3.Zero();
  44206. /**
  44207. * The l2,0 coefficients of the spherical harmonics
  44208. */
  44209. this.l20 = BABYLON.Vector3.Zero();
  44210. /**
  44211. * The l2,1 coefficients of the spherical harmonics
  44212. */
  44213. this.l21 = BABYLON.Vector3.Zero();
  44214. /**
  44215. * The l2,2 coefficients of the spherical harmonics
  44216. */
  44217. this.lL22 = BABYLON.Vector3.Zero();
  44218. }
  44219. /**
  44220. * Adds a light to the spherical harmonics
  44221. * @param direction the direction of the light
  44222. * @param color the color of the light
  44223. * @param deltaSolidAngle the delta solid angle of the light
  44224. */
  44225. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44226. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44227. var c = colorVector.scale(deltaSolidAngle);
  44228. this.l00 = this.l00.add(c.scale(0.282095));
  44229. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44230. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44231. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44232. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44233. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44234. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44235. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44236. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44237. };
  44238. /**
  44239. * Scales the spherical harmonics by the given amount
  44240. * @param scale the amount to scale
  44241. */
  44242. SphericalHarmonics.prototype.scale = function (scale) {
  44243. this.l00 = this.l00.scale(scale);
  44244. this.l1_1 = this.l1_1.scale(scale);
  44245. this.l10 = this.l10.scale(scale);
  44246. this.l11 = this.l11.scale(scale);
  44247. this.l2_2 = this.l2_2.scale(scale);
  44248. this.l2_1 = this.l2_1.scale(scale);
  44249. this.l20 = this.l20.scale(scale);
  44250. this.l21 = this.l21.scale(scale);
  44251. this.lL22 = this.lL22.scale(scale);
  44252. };
  44253. /**
  44254. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44255. *
  44256. * ```
  44257. * E_lm = A_l * L_lm
  44258. * ```
  44259. *
  44260. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44261. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44262. * the scaling factors are given in equation 9.
  44263. */
  44264. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44265. // Constant (Band 0)
  44266. this.l00 = this.l00.scale(3.141593);
  44267. // Linear (Band 1)
  44268. this.l1_1 = this.l1_1.scale(2.094395);
  44269. this.l10 = this.l10.scale(2.094395);
  44270. this.l11 = this.l11.scale(2.094395);
  44271. // Quadratic (Band 2)
  44272. this.l2_2 = this.l2_2.scale(0.785398);
  44273. this.l2_1 = this.l2_1.scale(0.785398);
  44274. this.l20 = this.l20.scale(0.785398);
  44275. this.l21 = this.l21.scale(0.785398);
  44276. this.lL22 = this.lL22.scale(0.785398);
  44277. };
  44278. /**
  44279. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44280. *
  44281. * ```
  44282. * L = (1/pi) * E * rho
  44283. * ```
  44284. *
  44285. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44286. */
  44287. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44288. this.scale(1.0 / Math.PI);
  44289. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44290. // (The pixel shader must apply albedo after texture fetches, etc).
  44291. };
  44292. /**
  44293. * Gets the spherical harmonics from polynomial
  44294. * @param polynomial the spherical polynomial
  44295. * @returns the spherical harmonics
  44296. */
  44297. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44298. var result = new SphericalHarmonics();
  44299. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44300. result.l1_1 = polynomial.y.scale(0.977204);
  44301. result.l10 = polynomial.z.scale(0.977204);
  44302. result.l11 = polynomial.x.scale(0.977204);
  44303. result.l2_2 = polynomial.xy.scale(1.16538);
  44304. result.l2_1 = polynomial.yz.scale(1.16538);
  44305. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44306. result.l21 = polynomial.zx.scale(1.16538);
  44307. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44308. result.scale(Math.PI);
  44309. return result;
  44310. };
  44311. /**
  44312. * Constructs a spherical harmonics from an array.
  44313. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44314. * @returns the spherical harmonics
  44315. */
  44316. SphericalHarmonics.FromArray = function (data) {
  44317. var sh = new SphericalHarmonics();
  44318. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44319. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44320. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44321. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44322. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44323. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44324. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44325. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44326. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44327. return sh;
  44328. };
  44329. return SphericalHarmonics;
  44330. }());
  44331. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44332. })(BABYLON || (BABYLON = {}));
  44333. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44334. var BABYLON;
  44335. (function (BABYLON) {
  44336. var FileFaceOrientation = /** @class */ (function () {
  44337. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44338. this.name = name;
  44339. this.worldAxisForNormal = worldAxisForNormal;
  44340. this.worldAxisForFileX = worldAxisForFileX;
  44341. this.worldAxisForFileY = worldAxisForFileY;
  44342. }
  44343. return FileFaceOrientation;
  44344. }());
  44345. ;
  44346. /**
  44347. * Helper class dealing with the extraction of spherical polynomial dataArray
  44348. * from a cube map.
  44349. */
  44350. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44351. function CubeMapToSphericalPolynomialTools() {
  44352. }
  44353. /**
  44354. * Converts a texture to the according Spherical Polynomial data.
  44355. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44356. *
  44357. * @param texture The texture to extract the information from.
  44358. * @return The Spherical Polynomial data.
  44359. */
  44360. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44361. if (!texture.isCube) {
  44362. // Only supports cube Textures currently.
  44363. return null;
  44364. }
  44365. var size = texture.getSize().width;
  44366. var right = texture.readPixels(0);
  44367. var left = texture.readPixels(1);
  44368. var up;
  44369. var down;
  44370. if (texture.isRenderTarget) {
  44371. up = texture.readPixels(3);
  44372. down = texture.readPixels(2);
  44373. }
  44374. else {
  44375. up = texture.readPixels(2);
  44376. down = texture.readPixels(3);
  44377. }
  44378. var front = texture.readPixels(4);
  44379. var back = texture.readPixels(5);
  44380. var gammaSpace = texture.gammaSpace;
  44381. // Always read as RGBA.
  44382. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44383. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44384. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44385. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44386. }
  44387. var cubeInfo = {
  44388. size: size,
  44389. right: right,
  44390. left: left,
  44391. up: up,
  44392. down: down,
  44393. front: front,
  44394. back: back,
  44395. format: format,
  44396. type: type,
  44397. gammaSpace: gammaSpace,
  44398. };
  44399. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44400. };
  44401. /**
  44402. * Converts a cubemap to the according Spherical Polynomial data.
  44403. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44404. *
  44405. * @param cubeInfo The Cube map to extract the information from.
  44406. * @return The Spherical Polynomial data.
  44407. */
  44408. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44409. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44410. var totalSolidAngle = 0.0;
  44411. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44412. var du = 2.0 / cubeInfo.size;
  44413. var dv = du;
  44414. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44415. var minUV = du * 0.5 - 1.0;
  44416. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44417. var fileFace = this.FileFaces[faceIndex];
  44418. var dataArray = cubeInfo[fileFace.name];
  44419. var v = minUV;
  44420. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44421. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44422. // Because SP is still linear, so summation is fine in that basis.
  44423. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44424. for (var y = 0; y < cubeInfo.size; y++) {
  44425. var u = minUV;
  44426. for (var x = 0; x < cubeInfo.size; x++) {
  44427. // World direction (not normalised)
  44428. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44429. worldDirection.normalize();
  44430. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44431. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44432. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44433. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44434. // Handle Integer types.
  44435. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44436. r /= 255;
  44437. g /= 255;
  44438. b /= 255;
  44439. }
  44440. // Handle Gamma space textures.
  44441. if (cubeInfo.gammaSpace) {
  44442. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44443. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44444. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44445. }
  44446. var color = new BABYLON.Color3(r, g, b);
  44447. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44448. totalSolidAngle += deltaSolidAngle;
  44449. u += du;
  44450. }
  44451. v += dv;
  44452. }
  44453. }
  44454. // Solid angle for entire sphere is 4*pi
  44455. var sphereSolidAngle = 4.0 * Math.PI;
  44456. // Adjust the solid angle to allow for how many faces we processed.
  44457. var facesProcessed = 6.0;
  44458. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44459. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44460. // This is needed because the numerical integration over the cube uses a
  44461. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44462. // and also to compensate for accumulative error due to float precision in the summation.
  44463. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44464. sphericalHarmonics.scale(correctionFactor);
  44465. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44466. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44467. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44468. };
  44469. CubeMapToSphericalPolynomialTools.FileFaces = [
  44470. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44471. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44472. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44473. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44474. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44475. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44476. ];
  44477. return CubeMapToSphericalPolynomialTools;
  44478. }());
  44479. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44480. })(BABYLON || (BABYLON = {}));
  44481. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44482. var BABYLON;
  44483. (function (BABYLON) {
  44484. /**
  44485. * Manages the defines for the PBR Material.
  44486. * @hiddenChildren
  44487. */
  44488. var PBRMaterialDefines = /** @class */ (function (_super) {
  44489. __extends(PBRMaterialDefines, _super);
  44490. /**
  44491. * Initializes the PBR Material defines.
  44492. */
  44493. function PBRMaterialDefines() {
  44494. var _this = _super.call(this) || this;
  44495. _this.PBR = true;
  44496. _this.MAINUV1 = false;
  44497. _this.MAINUV2 = false;
  44498. _this.UV1 = false;
  44499. _this.UV2 = false;
  44500. _this.ALBEDO = false;
  44501. _this.ALBEDODIRECTUV = 0;
  44502. _this.VERTEXCOLOR = false;
  44503. _this.AMBIENT = false;
  44504. _this.AMBIENTDIRECTUV = 0;
  44505. _this.AMBIENTINGRAYSCALE = false;
  44506. _this.OPACITY = false;
  44507. _this.VERTEXALPHA = false;
  44508. _this.OPACITYDIRECTUV = 0;
  44509. _this.OPACITYRGB = false;
  44510. _this.ALPHATEST = false;
  44511. _this.DEPTHPREPASS = false;
  44512. _this.ALPHABLEND = false;
  44513. _this.ALPHAFROMALBEDO = false;
  44514. _this.ALPHATESTVALUE = "0.5";
  44515. _this.SPECULAROVERALPHA = false;
  44516. _this.RADIANCEOVERALPHA = false;
  44517. _this.ALPHAFRESNEL = false;
  44518. _this.LINEARALPHAFRESNEL = false;
  44519. _this.PREMULTIPLYALPHA = false;
  44520. _this.EMISSIVE = false;
  44521. _this.EMISSIVEDIRECTUV = 0;
  44522. _this.REFLECTIVITY = false;
  44523. _this.REFLECTIVITYDIRECTUV = 0;
  44524. _this.SPECULARTERM = false;
  44525. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44526. _this.MICROSURFACEAUTOMATIC = false;
  44527. _this.LODBASEDMICROSFURACE = false;
  44528. _this.MICROSURFACEMAP = false;
  44529. _this.MICROSURFACEMAPDIRECTUV = 0;
  44530. _this.METALLICWORKFLOW = false;
  44531. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44532. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44533. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44534. _this.AOSTOREINMETALMAPRED = false;
  44535. _this.ENVIRONMENTBRDF = false;
  44536. _this.NORMAL = false;
  44537. _this.TANGENT = false;
  44538. _this.BUMP = false;
  44539. _this.BUMPDIRECTUV = 0;
  44540. _this.OBJECTSPACE_NORMALMAP = false;
  44541. _this.PARALLAX = false;
  44542. _this.PARALLAXOCCLUSION = false;
  44543. _this.NORMALXYSCALE = true;
  44544. _this.LIGHTMAP = false;
  44545. _this.LIGHTMAPDIRECTUV = 0;
  44546. _this.USELIGHTMAPASSHADOWMAP = false;
  44547. _this.GAMMALIGHTMAP = false;
  44548. _this.REFLECTION = false;
  44549. _this.REFLECTIONMAP_3D = false;
  44550. _this.REFLECTIONMAP_SPHERICAL = false;
  44551. _this.REFLECTIONMAP_PLANAR = false;
  44552. _this.REFLECTIONMAP_CUBIC = false;
  44553. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44554. _this.REFLECTIONMAP_PROJECTION = false;
  44555. _this.REFLECTIONMAP_SKYBOX = false;
  44556. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44557. _this.REFLECTIONMAP_EXPLICIT = false;
  44558. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44559. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44560. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44561. _this.INVERTCUBICMAP = false;
  44562. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44563. _this.USESPHERICALINVERTEX = false;
  44564. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44565. _this.LODINREFLECTIONALPHA = false;
  44566. _this.GAMMAREFLECTION = false;
  44567. _this.RGBDREFLECTION = false;
  44568. _this.RADIANCEOCCLUSION = false;
  44569. _this.HORIZONOCCLUSION = false;
  44570. _this.REFRACTION = false;
  44571. _this.REFRACTIONMAP_3D = false;
  44572. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44573. _this.LODINREFRACTIONALPHA = false;
  44574. _this.GAMMAREFRACTION = false;
  44575. _this.RGBDREFRACTION = false;
  44576. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44577. _this.INSTANCES = false;
  44578. _this.NUM_BONE_INFLUENCERS = 0;
  44579. _this.BonesPerMesh = 0;
  44580. _this.NONUNIFORMSCALING = false;
  44581. _this.MORPHTARGETS = false;
  44582. _this.MORPHTARGETS_NORMAL = false;
  44583. _this.MORPHTARGETS_TANGENT = false;
  44584. _this.NUM_MORPH_INFLUENCERS = 0;
  44585. _this.IMAGEPROCESSING = false;
  44586. _this.VIGNETTE = false;
  44587. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44588. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44589. _this.TONEMAPPING = false;
  44590. _this.TONEMAPPING_ACES = false;
  44591. _this.CONTRAST = false;
  44592. _this.COLORCURVES = false;
  44593. _this.COLORGRADING = false;
  44594. _this.COLORGRADING3D = false;
  44595. _this.SAMPLER3DGREENDEPTH = false;
  44596. _this.SAMPLER3DBGRMAP = false;
  44597. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44598. _this.EXPOSURE = false;
  44599. _this.USEPHYSICALLIGHTFALLOFF = false;
  44600. _this.USEGLTFLIGHTFALLOFF = false;
  44601. _this.TWOSIDEDLIGHTING = false;
  44602. _this.SHADOWFLOAT = false;
  44603. _this.CLIPPLANE = false;
  44604. _this.CLIPPLANE2 = false;
  44605. _this.CLIPPLANE3 = false;
  44606. _this.CLIPPLANE4 = false;
  44607. _this.POINTSIZE = false;
  44608. _this.FOG = false;
  44609. _this.LOGARITHMICDEPTH = false;
  44610. _this.FORCENORMALFORWARD = false;
  44611. _this.SPECULARAA = false;
  44612. _this.UNLIT = false;
  44613. _this.rebuild();
  44614. return _this;
  44615. }
  44616. /**
  44617. * Resets the PBR Material defines.
  44618. */
  44619. PBRMaterialDefines.prototype.reset = function () {
  44620. _super.prototype.reset.call(this);
  44621. this.ALPHATESTVALUE = "0.5";
  44622. this.PBR = true;
  44623. };
  44624. return PBRMaterialDefines;
  44625. }(BABYLON.MaterialDefines));
  44626. /**
  44627. * The Physically based material base class of BJS.
  44628. *
  44629. * This offers the main features of a standard PBR material.
  44630. * For more information, please refer to the documentation :
  44631. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44632. */
  44633. var PBRBaseMaterial = /** @class */ (function (_super) {
  44634. __extends(PBRBaseMaterial, _super);
  44635. /**
  44636. * Instantiates a new PBRMaterial instance.
  44637. *
  44638. * @param name The material name
  44639. * @param scene The scene the material will be use in.
  44640. */
  44641. function PBRBaseMaterial(name, scene) {
  44642. var _this = _super.call(this, name, scene) || this;
  44643. /**
  44644. * Intensity of the direct lights e.g. the four lights available in your scene.
  44645. * This impacts both the direct diffuse and specular highlights.
  44646. */
  44647. _this._directIntensity = 1.0;
  44648. /**
  44649. * Intensity of the emissive part of the material.
  44650. * This helps controlling the emissive effect without modifying the emissive color.
  44651. */
  44652. _this._emissiveIntensity = 1.0;
  44653. /**
  44654. * Intensity of the environment e.g. how much the environment will light the object
  44655. * either through harmonics for rough material or through the refelction for shiny ones.
  44656. */
  44657. _this._environmentIntensity = 1.0;
  44658. /**
  44659. * This is a special control allowing the reduction of the specular highlights coming from the
  44660. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44661. */
  44662. _this._specularIntensity = 1.0;
  44663. /**
  44664. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44665. */
  44666. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44667. /**
  44668. * Debug Control allowing disabling the bump map on this material.
  44669. */
  44670. _this._disableBumpMap = false;
  44671. /**
  44672. * AKA Occlusion Texture Intensity in other nomenclature.
  44673. */
  44674. _this._ambientTextureStrength = 1.0;
  44675. /**
  44676. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44677. * 1 means it completely occludes it
  44678. * 0 mean it has no impact
  44679. */
  44680. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44681. /**
  44682. * The color of a material in ambient lighting.
  44683. */
  44684. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44685. /**
  44686. * AKA Diffuse Color in other nomenclature.
  44687. */
  44688. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44689. /**
  44690. * AKA Specular Color in other nomenclature.
  44691. */
  44692. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44693. /**
  44694. * The color applied when light is reflected from a material.
  44695. */
  44696. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44697. /**
  44698. * The color applied when light is emitted from a material.
  44699. */
  44700. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44701. /**
  44702. * AKA Glossiness in other nomenclature.
  44703. */
  44704. _this._microSurface = 0.9;
  44705. /**
  44706. * source material index of refraction (IOR)' / 'destination material IOR.
  44707. */
  44708. _this._indexOfRefraction = 0.66;
  44709. /**
  44710. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44711. */
  44712. _this._invertRefractionY = false;
  44713. /**
  44714. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44715. * Materials half opaque for instance using refraction could benefit from this control.
  44716. */
  44717. _this._linkRefractionWithTransparency = false;
  44718. /**
  44719. * Specifies that the material will use the light map as a show map.
  44720. */
  44721. _this._useLightmapAsShadowmap = false;
  44722. /**
  44723. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44724. * makes the reflect vector face the model (under horizon).
  44725. */
  44726. _this._useHorizonOcclusion = true;
  44727. /**
  44728. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44729. * too much the area relying on ambient texture to define their ambient occlusion.
  44730. */
  44731. _this._useRadianceOcclusion = true;
  44732. /**
  44733. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44734. */
  44735. _this._useAlphaFromAlbedoTexture = false;
  44736. /**
  44737. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44738. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44739. */
  44740. _this._useSpecularOverAlpha = true;
  44741. /**
  44742. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44743. */
  44744. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44745. /**
  44746. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44747. */
  44748. _this._useRoughnessFromMetallicTextureAlpha = true;
  44749. /**
  44750. * Specifies if the metallic texture contains the roughness information in its green channel.
  44751. */
  44752. _this._useRoughnessFromMetallicTextureGreen = false;
  44753. /**
  44754. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44755. */
  44756. _this._useMetallnessFromMetallicTextureBlue = false;
  44757. /**
  44758. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44759. */
  44760. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44761. /**
  44762. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44763. */
  44764. _this._useAmbientInGrayScale = false;
  44765. /**
  44766. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44767. * The material will try to infer what glossiness each pixel should be.
  44768. */
  44769. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44770. /**
  44771. * Defines the falloff type used in this material.
  44772. * It by default is Physical.
  44773. */
  44774. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44775. /**
  44776. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44777. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44778. */
  44779. _this._useRadianceOverAlpha = true;
  44780. /**
  44781. * Allows using an object space normal map (instead of tangent space).
  44782. */
  44783. _this._useObjectSpaceNormalMap = false;
  44784. /**
  44785. * Allows using the bump map in parallax mode.
  44786. */
  44787. _this._useParallax = false;
  44788. /**
  44789. * Allows using the bump map in parallax occlusion mode.
  44790. */
  44791. _this._useParallaxOcclusion = false;
  44792. /**
  44793. * Controls the scale bias of the parallax mode.
  44794. */
  44795. _this._parallaxScaleBias = 0.05;
  44796. /**
  44797. * If sets to true, disables all the lights affecting the material.
  44798. */
  44799. _this._disableLighting = false;
  44800. /**
  44801. * Number of Simultaneous lights allowed on the material.
  44802. */
  44803. _this._maxSimultaneousLights = 4;
  44804. /**
  44805. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44806. */
  44807. _this._invertNormalMapX = false;
  44808. /**
  44809. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44810. */
  44811. _this._invertNormalMapY = false;
  44812. /**
  44813. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44814. */
  44815. _this._twoSidedLighting = false;
  44816. /**
  44817. * Defines the alpha limits in alpha test mode.
  44818. */
  44819. _this._alphaCutOff = 0.4;
  44820. /**
  44821. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44822. */
  44823. _this._forceAlphaTest = false;
  44824. /**
  44825. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44826. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44827. */
  44828. _this._useAlphaFresnel = false;
  44829. /**
  44830. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44831. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44832. */
  44833. _this._useLinearAlphaFresnel = false;
  44834. /**
  44835. * The transparency mode of the material.
  44836. */
  44837. _this._transparencyMode = null;
  44838. /**
  44839. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44840. * from cos thetav and roughness:
  44841. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44842. */
  44843. _this._environmentBRDFTexture = null;
  44844. /**
  44845. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44846. */
  44847. _this._forceIrradianceInFragment = false;
  44848. /**
  44849. * Force normal to face away from face.
  44850. */
  44851. _this._forceNormalForward = false;
  44852. /**
  44853. * Enables specular anti aliasing in the PBR shader.
  44854. * It will both interacts on the Geometry for analytical and IBL lighting.
  44855. * It also prefilter the roughness map based on the bump values.
  44856. */
  44857. _this._enableSpecularAntiAliasing = false;
  44858. /**
  44859. * Stores the available render targets.
  44860. */
  44861. _this._renderTargets = new BABYLON.SmartArray(16);
  44862. /**
  44863. * Sets the global ambient color for the material used in lighting calculations.
  44864. */
  44865. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44866. /**
  44867. * If set to true, no lighting calculations will be applied.
  44868. */
  44869. _this._unlit = false;
  44870. // Setup the default processing configuration to the scene.
  44871. _this._attachImageProcessingConfiguration(null);
  44872. _this.getRenderTargetTextures = function () {
  44873. _this._renderTargets.reset();
  44874. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44875. _this._renderTargets.push(_this._reflectionTexture);
  44876. }
  44877. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44878. _this._renderTargets.push(_this._refractionTexture);
  44879. }
  44880. return _this._renderTargets;
  44881. };
  44882. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44883. return _this;
  44884. }
  44885. /**
  44886. * Attaches a new image processing configuration to the PBR Material.
  44887. * @param configuration
  44888. */
  44889. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44890. var _this = this;
  44891. if (configuration === this._imageProcessingConfiguration) {
  44892. return;
  44893. }
  44894. // Detaches observer.
  44895. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44896. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44897. }
  44898. // Pick the scene configuration if needed.
  44899. if (!configuration) {
  44900. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44901. }
  44902. else {
  44903. this._imageProcessingConfiguration = configuration;
  44904. }
  44905. // Attaches observer.
  44906. if (this._imageProcessingConfiguration) {
  44907. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44908. _this._markAllSubMeshesAsImageProcessingDirty();
  44909. });
  44910. }
  44911. };
  44912. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  44913. /**
  44914. * Gets a boolean indicating that current material needs to register RTT
  44915. */
  44916. get: function () {
  44917. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44918. return true;
  44919. }
  44920. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44921. return true;
  44922. }
  44923. return false;
  44924. },
  44925. enumerable: true,
  44926. configurable: true
  44927. });
  44928. /**
  44929. * Gets the name of the material class.
  44930. */
  44931. PBRBaseMaterial.prototype.getClassName = function () {
  44932. return "PBRBaseMaterial";
  44933. };
  44934. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44935. /**
  44936. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44937. */
  44938. get: function () {
  44939. return this._useLogarithmicDepth;
  44940. },
  44941. /**
  44942. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44943. */
  44944. set: function (value) {
  44945. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44946. },
  44947. enumerable: true,
  44948. configurable: true
  44949. });
  44950. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44951. /**
  44952. * Gets the current transparency mode.
  44953. */
  44954. get: function () {
  44955. return this._transparencyMode;
  44956. },
  44957. /**
  44958. * Sets the transparency mode of the material.
  44959. *
  44960. * | Value | Type | Description |
  44961. * | ----- | ----------------------------------- | ----------- |
  44962. * | 0 | OPAQUE | |
  44963. * | 1 | ALPHATEST | |
  44964. * | 2 | ALPHABLEND | |
  44965. * | 3 | ALPHATESTANDBLEND | |
  44966. *
  44967. */
  44968. set: function (value) {
  44969. if (this._transparencyMode === value) {
  44970. return;
  44971. }
  44972. this._transparencyMode = value;
  44973. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44974. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44975. },
  44976. enumerable: true,
  44977. configurable: true
  44978. });
  44979. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44980. /**
  44981. * Returns true if alpha blending should be disabled.
  44982. */
  44983. get: function () {
  44984. return (this._linkRefractionWithTransparency ||
  44985. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44986. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44987. },
  44988. enumerable: true,
  44989. configurable: true
  44990. });
  44991. /**
  44992. * Specifies whether or not this material should be rendered in alpha blend mode.
  44993. */
  44994. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44995. if (this._disableAlphaBlending) {
  44996. return false;
  44997. }
  44998. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44999. };
  45000. /**
  45001. * Specifies if the mesh will require alpha blending.
  45002. * @param mesh - BJS mesh.
  45003. */
  45004. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45005. if (this._disableAlphaBlending) {
  45006. return false;
  45007. }
  45008. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45009. };
  45010. /**
  45011. * Specifies whether or not this material should be rendered in alpha test mode.
  45012. */
  45013. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45014. if (this._forceAlphaTest) {
  45015. return true;
  45016. }
  45017. if (this._linkRefractionWithTransparency) {
  45018. return false;
  45019. }
  45020. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45021. };
  45022. /**
  45023. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45024. */
  45025. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45026. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45027. };
  45028. /**
  45029. * Gets the texture used for the alpha test.
  45030. */
  45031. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45032. return this._albedoTexture;
  45033. };
  45034. /**
  45035. * Specifies that the submesh is ready to be used.
  45036. * @param mesh - BJS mesh.
  45037. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45038. * @param useInstances - Specifies that instances should be used.
  45039. * @returns - boolean indicating that the submesh is ready or not.
  45040. */
  45041. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45042. if (subMesh.effect && this.isFrozen) {
  45043. if (this._wasPreviouslyReady) {
  45044. return true;
  45045. }
  45046. }
  45047. if (!subMesh._materialDefines) {
  45048. subMesh._materialDefines = new PBRMaterialDefines();
  45049. }
  45050. var defines = subMesh._materialDefines;
  45051. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45052. if (defines._renderId === this.getScene().getRenderId()) {
  45053. return true;
  45054. }
  45055. }
  45056. var scene = this.getScene();
  45057. var engine = scene.getEngine();
  45058. if (defines._areTexturesDirty) {
  45059. if (scene.texturesEnabled) {
  45060. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45061. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45062. return false;
  45063. }
  45064. }
  45065. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45066. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45067. return false;
  45068. }
  45069. }
  45070. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45071. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45072. return false;
  45073. }
  45074. }
  45075. var reflectionTexture = this._getReflectionTexture();
  45076. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45077. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45078. return false;
  45079. }
  45080. }
  45081. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45082. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45083. return false;
  45084. }
  45085. }
  45086. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45087. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45088. return false;
  45089. }
  45090. }
  45091. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45092. if (this._metallicTexture) {
  45093. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45094. return false;
  45095. }
  45096. }
  45097. else if (this._reflectivityTexture) {
  45098. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45099. return false;
  45100. }
  45101. }
  45102. if (this._microSurfaceTexture) {
  45103. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45104. return false;
  45105. }
  45106. }
  45107. }
  45108. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45109. // Bump texture cannot be not blocking.
  45110. if (!this._bumpTexture.isReady()) {
  45111. return false;
  45112. }
  45113. }
  45114. var refractionTexture = this._getRefractionTexture();
  45115. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45116. if (!refractionTexture.isReadyOrNotBlocking()) {
  45117. return false;
  45118. }
  45119. }
  45120. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45121. // This is blocking.
  45122. if (!this._environmentBRDFTexture.isReady()) {
  45123. return false;
  45124. }
  45125. }
  45126. }
  45127. }
  45128. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45129. if (!this._imageProcessingConfiguration.isReady()) {
  45130. return false;
  45131. }
  45132. }
  45133. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45134. mesh.createNormals(true);
  45135. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45136. }
  45137. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45138. if (effect) {
  45139. scene.resetCachedMaterial();
  45140. subMesh.setEffect(effect, defines);
  45141. this.buildUniformLayout();
  45142. }
  45143. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45144. return false;
  45145. }
  45146. defines._renderId = scene.getRenderId();
  45147. this._wasPreviouslyReady = true;
  45148. return true;
  45149. };
  45150. /**
  45151. * Specifies if the material uses metallic roughness workflow.
  45152. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45153. */
  45154. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45155. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45156. return true;
  45157. }
  45158. return false;
  45159. };
  45160. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45161. if (onCompiled === void 0) { onCompiled = null; }
  45162. if (onError === void 0) { onError = null; }
  45163. if (useInstances === void 0) { useInstances = null; }
  45164. if (useClipPlane === void 0) { useClipPlane = null; }
  45165. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45166. if (!defines.isDirty) {
  45167. return null;
  45168. }
  45169. defines.markAsProcessed();
  45170. var scene = this.getScene();
  45171. var engine = scene.getEngine();
  45172. // Fallbacks
  45173. var fallbacks = new BABYLON.EffectFallbacks();
  45174. var fallbackRank = 0;
  45175. if (defines.USESPHERICALINVERTEX) {
  45176. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45177. }
  45178. if (defines.FOG) {
  45179. fallbacks.addFallback(fallbackRank, "FOG");
  45180. }
  45181. if (defines.SPECULARAA) {
  45182. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45183. }
  45184. if (defines.POINTSIZE) {
  45185. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45186. }
  45187. if (defines.LOGARITHMICDEPTH) {
  45188. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45189. }
  45190. if (defines.PARALLAX) {
  45191. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45192. }
  45193. if (defines.PARALLAXOCCLUSION) {
  45194. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45195. }
  45196. if (defines.ENVIRONMENTBRDF) {
  45197. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45198. }
  45199. if (defines.TANGENT) {
  45200. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45201. }
  45202. if (defines.BUMP) {
  45203. fallbacks.addFallback(fallbackRank++, "BUMP");
  45204. }
  45205. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45206. if (defines.SPECULARTERM) {
  45207. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45208. }
  45209. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45210. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45211. }
  45212. if (defines.LIGHTMAP) {
  45213. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45214. }
  45215. if (defines.NORMAL) {
  45216. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45217. }
  45218. if (defines.AMBIENT) {
  45219. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45220. }
  45221. if (defines.EMISSIVE) {
  45222. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45223. }
  45224. if (defines.VERTEXCOLOR) {
  45225. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45226. }
  45227. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45228. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45229. }
  45230. if (defines.MORPHTARGETS) {
  45231. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45232. }
  45233. //Attributes
  45234. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45235. if (defines.NORMAL) {
  45236. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45237. }
  45238. if (defines.TANGENT) {
  45239. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45240. }
  45241. if (defines.UV1) {
  45242. attribs.push(BABYLON.VertexBuffer.UVKind);
  45243. }
  45244. if (defines.UV2) {
  45245. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45246. }
  45247. if (defines.VERTEXCOLOR) {
  45248. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45249. }
  45250. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45251. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45252. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45253. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45254. "vFogInfos", "vFogColor", "pointSize",
  45255. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45256. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45257. "mBones",
  45258. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45259. "vLightingIntensity",
  45260. "logarithmicDepthConstant",
  45261. "vSphericalX", "vSphericalY", "vSphericalZ",
  45262. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45263. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45264. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45265. "vTangentSpaceParams"
  45266. ];
  45267. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45268. "bumpSampler", "lightmapSampler", "opacitySampler",
  45269. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45270. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45271. "microSurfaceSampler", "environmentBrdfSampler"];
  45272. var uniformBuffers = ["Material", "Scene"];
  45273. if (BABYLON.ImageProcessingConfiguration) {
  45274. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45275. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45276. }
  45277. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45278. uniformsNames: uniforms,
  45279. uniformBuffersNames: uniformBuffers,
  45280. samplers: samplers,
  45281. defines: defines,
  45282. maxSimultaneousLights: this._maxSimultaneousLights
  45283. });
  45284. var join = defines.toString();
  45285. return engine.createEffect("pbr", {
  45286. attributes: attribs,
  45287. uniformsNames: uniforms,
  45288. uniformBuffersNames: uniformBuffers,
  45289. samplers: samplers,
  45290. defines: join,
  45291. fallbacks: fallbacks,
  45292. onCompiled: onCompiled,
  45293. onError: onError,
  45294. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45295. }, engine);
  45296. };
  45297. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45298. if (useInstances === void 0) { useInstances = null; }
  45299. if (useClipPlane === void 0) { useClipPlane = null; }
  45300. var scene = this.getScene();
  45301. var engine = scene.getEngine();
  45302. // Lights
  45303. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45304. defines._needNormals = true;
  45305. // Textures
  45306. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45307. if (defines._areTexturesDirty) {
  45308. defines._needUVs = false;
  45309. if (scene.texturesEnabled) {
  45310. if (scene.getEngine().getCaps().textureLOD) {
  45311. defines.LODBASEDMICROSFURACE = true;
  45312. }
  45313. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45314. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45315. }
  45316. else {
  45317. defines.ALBEDO = false;
  45318. }
  45319. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45320. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45321. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45322. }
  45323. else {
  45324. defines.AMBIENT = false;
  45325. }
  45326. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45327. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45328. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45329. }
  45330. else {
  45331. defines.OPACITY = false;
  45332. }
  45333. var reflectionTexture = this._getReflectionTexture();
  45334. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45335. defines.REFLECTION = true;
  45336. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45337. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45338. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45339. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45340. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45341. defines.INVERTCUBICMAP = true;
  45342. }
  45343. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45344. switch (reflectionTexture.coordinatesMode) {
  45345. case BABYLON.Texture.EXPLICIT_MODE:
  45346. defines.REFLECTIONMAP_EXPLICIT = true;
  45347. break;
  45348. case BABYLON.Texture.PLANAR_MODE:
  45349. defines.REFLECTIONMAP_PLANAR = true;
  45350. break;
  45351. case BABYLON.Texture.PROJECTION_MODE:
  45352. defines.REFLECTIONMAP_PROJECTION = true;
  45353. break;
  45354. case BABYLON.Texture.SKYBOX_MODE:
  45355. defines.REFLECTIONMAP_SKYBOX = true;
  45356. break;
  45357. case BABYLON.Texture.SPHERICAL_MODE:
  45358. defines.REFLECTIONMAP_SPHERICAL = true;
  45359. break;
  45360. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45361. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45362. break;
  45363. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45364. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45365. break;
  45366. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45367. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45368. break;
  45369. case BABYLON.Texture.CUBIC_MODE:
  45370. case BABYLON.Texture.INVCUBIC_MODE:
  45371. default:
  45372. defines.REFLECTIONMAP_CUBIC = true;
  45373. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45374. break;
  45375. }
  45376. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45377. if (reflectionTexture.sphericalPolynomial) {
  45378. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45379. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45380. defines.USESPHERICALINVERTEX = false;
  45381. }
  45382. else {
  45383. defines.USESPHERICALINVERTEX = true;
  45384. }
  45385. }
  45386. }
  45387. else {
  45388. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45389. }
  45390. }
  45391. else {
  45392. defines.REFLECTION = false;
  45393. defines.REFLECTIONMAP_3D = false;
  45394. defines.REFLECTIONMAP_SPHERICAL = false;
  45395. defines.REFLECTIONMAP_PLANAR = false;
  45396. defines.REFLECTIONMAP_CUBIC = false;
  45397. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45398. defines.REFLECTIONMAP_PROJECTION = false;
  45399. defines.REFLECTIONMAP_SKYBOX = false;
  45400. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45401. defines.REFLECTIONMAP_EXPLICIT = false;
  45402. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45403. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45404. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45405. defines.INVERTCUBICMAP = false;
  45406. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45407. defines.USESPHERICALINVERTEX = false;
  45408. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45409. defines.LODINREFLECTIONALPHA = false;
  45410. defines.GAMMAREFLECTION = false;
  45411. defines.RGBDREFLECTION = false;
  45412. }
  45413. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45414. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45415. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45416. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45417. }
  45418. else {
  45419. defines.LIGHTMAP = false;
  45420. }
  45421. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45422. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45423. }
  45424. else {
  45425. defines.EMISSIVE = false;
  45426. }
  45427. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45428. if (this._metallicTexture) {
  45429. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45430. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45431. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45432. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45433. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45434. }
  45435. else if (this._reflectivityTexture) {
  45436. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45437. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45438. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45439. }
  45440. else {
  45441. defines.REFLECTIVITY = false;
  45442. }
  45443. if (this._microSurfaceTexture) {
  45444. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45445. }
  45446. else {
  45447. defines.MICROSURFACEMAP = false;
  45448. }
  45449. }
  45450. else {
  45451. defines.REFLECTIVITY = false;
  45452. defines.MICROSURFACEMAP = false;
  45453. }
  45454. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45455. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45456. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45457. defines.PARALLAX = true;
  45458. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45459. }
  45460. else {
  45461. defines.PARALLAX = false;
  45462. }
  45463. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45464. }
  45465. else {
  45466. defines.BUMP = false;
  45467. }
  45468. var refractionTexture = this._getRefractionTexture();
  45469. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45470. defines.REFRACTION = true;
  45471. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45472. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45473. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45474. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45475. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45476. if (this._linkRefractionWithTransparency) {
  45477. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45478. }
  45479. }
  45480. else {
  45481. defines.REFRACTION = false;
  45482. }
  45483. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45484. defines.ENVIRONMENTBRDF = true;
  45485. }
  45486. else {
  45487. defines.ENVIRONMENTBRDF = false;
  45488. }
  45489. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45490. defines.ALPHAFROMALBEDO = true;
  45491. }
  45492. else {
  45493. defines.ALPHAFROMALBEDO = false;
  45494. }
  45495. }
  45496. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45497. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45498. defines.USEPHYSICALLIGHTFALLOFF = false;
  45499. defines.USEGLTFLIGHTFALLOFF = false;
  45500. }
  45501. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45502. defines.USEPHYSICALLIGHTFALLOFF = false;
  45503. defines.USEGLTFLIGHTFALLOFF = true;
  45504. }
  45505. else {
  45506. defines.USEPHYSICALLIGHTFALLOFF = true;
  45507. defines.USEGLTFLIGHTFALLOFF = false;
  45508. }
  45509. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45510. if (!this.backFaceCulling && this._twoSidedLighting) {
  45511. defines.TWOSIDEDLIGHTING = true;
  45512. }
  45513. else {
  45514. defines.TWOSIDEDLIGHTING = false;
  45515. }
  45516. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45517. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45518. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45519. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45520. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45521. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45522. }
  45523. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45524. this._imageProcessingConfiguration.prepareDefines(defines);
  45525. }
  45526. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45527. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45528. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45529. // Misc.
  45530. if (defines._areMiscDirty) {
  45531. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45532. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45533. }
  45534. // Values that need to be evaluated on every frame
  45535. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45536. // Attribs
  45537. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45538. };
  45539. /**
  45540. * Force shader compilation
  45541. */
  45542. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45543. var _this = this;
  45544. var localOptions = __assign({ clipPlane: false }, options);
  45545. var defines = new PBRMaterialDefines();
  45546. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45547. if (effect.isReady()) {
  45548. if (onCompiled) {
  45549. onCompiled(this);
  45550. }
  45551. }
  45552. else {
  45553. effect.onCompileObservable.add(function () {
  45554. if (onCompiled) {
  45555. onCompiled(_this);
  45556. }
  45557. });
  45558. }
  45559. };
  45560. /**
  45561. * Initializes the uniform buffer layout for the shader.
  45562. */
  45563. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45564. // Order is important !
  45565. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45566. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  45567. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45568. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45569. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45570. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45571. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45572. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45573. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45574. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45575. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45576. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45577. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45578. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45579. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45580. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45581. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45582. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45583. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45584. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45585. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45586. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45587. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45588. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45589. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45590. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45591. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45592. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45593. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45594. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45595. this._uniformBuffer.addUniform("pointSize", 1);
  45596. this._uniformBuffer.create();
  45597. };
  45598. /**
  45599. * Unbinds the textures.
  45600. */
  45601. PBRBaseMaterial.prototype.unbind = function () {
  45602. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45603. this._uniformBuffer.setTexture("reflectionSampler", null);
  45604. }
  45605. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45606. this._uniformBuffer.setTexture("refractionSampler", null);
  45607. }
  45608. _super.prototype.unbind.call(this);
  45609. };
  45610. /**
  45611. * Binds the submesh data.
  45612. * @param world - The world matrix.
  45613. * @param mesh - The BJS mesh.
  45614. * @param subMesh - A submesh of the BJS mesh.
  45615. */
  45616. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45617. var scene = this.getScene();
  45618. var defines = subMesh._materialDefines;
  45619. if (!defines) {
  45620. return;
  45621. }
  45622. var effect = subMesh.effect;
  45623. if (!effect) {
  45624. return;
  45625. }
  45626. this._activeEffect = effect;
  45627. // Matrices
  45628. this.bindOnlyWorldMatrix(world);
  45629. // Normal Matrix
  45630. if (defines.OBJECTSPACE_NORMALMAP) {
  45631. world.toNormalMatrix(this._normalMatrix);
  45632. this.bindOnlyNormalMatrix(this._normalMatrix);
  45633. }
  45634. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45635. // Bones
  45636. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45637. var reflectionTexture = null;
  45638. if (mustRebind) {
  45639. this._uniformBuffer.bindToEffect(effect, "Material");
  45640. this.bindViewProjection(effect);
  45641. reflectionTexture = this._getReflectionTexture();
  45642. var refractionTexture = this._getRefractionTexture();
  45643. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45644. // Texture uniforms
  45645. if (scene.texturesEnabled) {
  45646. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45647. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45648. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45649. }
  45650. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45651. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  45652. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45653. }
  45654. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45655. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45656. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45657. }
  45658. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45659. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45660. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45661. if (reflectionTexture.boundingBoxSize) {
  45662. var cubeTexture = reflectionTexture;
  45663. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45664. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45665. }
  45666. var polynomials = reflectionTexture.sphericalPolynomial;
  45667. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45668. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45669. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45670. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45671. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45672. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45673. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45674. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45675. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45676. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45677. }
  45678. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45679. }
  45680. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45681. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45682. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45683. }
  45684. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45685. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45686. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45687. }
  45688. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45689. if (this._metallicTexture) {
  45690. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45691. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45692. }
  45693. else if (this._reflectivityTexture) {
  45694. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45695. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45696. }
  45697. if (this._microSurfaceTexture) {
  45698. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45699. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45700. }
  45701. }
  45702. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45703. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45704. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45705. if (scene._mirroredCameraPosition) {
  45706. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45707. }
  45708. else {
  45709. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45710. }
  45711. }
  45712. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45713. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45714. var depth = 1.0;
  45715. if (!refractionTexture.isCube) {
  45716. if (refractionTexture.depth) {
  45717. depth = refractionTexture.depth;
  45718. }
  45719. }
  45720. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45721. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45722. }
  45723. }
  45724. // Point size
  45725. if (this.pointsCloud) {
  45726. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45727. }
  45728. // Colors
  45729. if (defines.METALLICWORKFLOW) {
  45730. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45731. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45732. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45733. }
  45734. else {
  45735. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45736. }
  45737. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45738. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45739. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45740. // Misc
  45741. this._lightingInfos.x = this._directIntensity;
  45742. this._lightingInfos.y = this._emissiveIntensity;
  45743. this._lightingInfos.z = this._environmentIntensity;
  45744. this._lightingInfos.w = this._specularIntensity;
  45745. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45746. }
  45747. // Textures
  45748. if (scene.texturesEnabled) {
  45749. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45750. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45751. }
  45752. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45753. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45754. }
  45755. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45756. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45757. }
  45758. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45759. if (defines.LODBASEDMICROSFURACE) {
  45760. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45761. }
  45762. else {
  45763. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45764. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45765. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45766. }
  45767. }
  45768. if (defines.ENVIRONMENTBRDF) {
  45769. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45770. }
  45771. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45772. if (defines.LODBASEDMICROSFURACE) {
  45773. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45774. }
  45775. else {
  45776. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45777. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45778. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45779. }
  45780. }
  45781. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45782. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45783. }
  45784. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45785. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45786. }
  45787. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45788. if (this._metallicTexture) {
  45789. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45790. }
  45791. else if (this._reflectivityTexture) {
  45792. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45793. }
  45794. if (this._microSurfaceTexture) {
  45795. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45796. }
  45797. }
  45798. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45799. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45800. }
  45801. }
  45802. // Clip plane
  45803. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45804. // Colors
  45805. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45806. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45807. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45808. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45809. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45810. }
  45811. if (mustRebind || !this.isFrozen) {
  45812. // Lights
  45813. if (scene.lightsEnabled && !this._disableLighting) {
  45814. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  45815. }
  45816. // View
  45817. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45818. this.bindView(effect);
  45819. }
  45820. // Fog
  45821. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  45822. // Morph targets
  45823. if (defines.NUM_MORPH_INFLUENCERS) {
  45824. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45825. }
  45826. // image processing
  45827. this._imageProcessingConfiguration.bind(this._activeEffect);
  45828. // Log. depth
  45829. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45830. }
  45831. this._uniformBuffer.update();
  45832. this._afterBind(mesh, this._activeEffect);
  45833. };
  45834. /**
  45835. * Returns the animatable textures.
  45836. * @returns - Array of animatable textures.
  45837. */
  45838. PBRBaseMaterial.prototype.getAnimatables = function () {
  45839. var results = [];
  45840. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45841. results.push(this._albedoTexture);
  45842. }
  45843. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45844. results.push(this._ambientTexture);
  45845. }
  45846. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45847. results.push(this._opacityTexture);
  45848. }
  45849. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45850. results.push(this._reflectionTexture);
  45851. }
  45852. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45853. results.push(this._emissiveTexture);
  45854. }
  45855. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45856. results.push(this._metallicTexture);
  45857. }
  45858. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45859. results.push(this._reflectivityTexture);
  45860. }
  45861. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45862. results.push(this._bumpTexture);
  45863. }
  45864. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45865. results.push(this._lightmapTexture);
  45866. }
  45867. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45868. results.push(this._refractionTexture);
  45869. }
  45870. return results;
  45871. };
  45872. /**
  45873. * Returns the texture used for reflections.
  45874. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45875. */
  45876. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45877. if (this._reflectionTexture) {
  45878. return this._reflectionTexture;
  45879. }
  45880. return this.getScene().environmentTexture;
  45881. };
  45882. /**
  45883. * Returns the texture used for refraction or null if none is used.
  45884. * @returns - Refection texture if present. If no refraction texture and refraction
  45885. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45886. */
  45887. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45888. if (this._refractionTexture) {
  45889. return this._refractionTexture;
  45890. }
  45891. if (this._linkRefractionWithTransparency) {
  45892. return this.getScene().environmentTexture;
  45893. }
  45894. return null;
  45895. };
  45896. /**
  45897. * Disposes the resources of the material.
  45898. * @param forceDisposeEffect - Forces the disposal of effects.
  45899. * @param forceDisposeTextures - Forces the disposal of all textures.
  45900. */
  45901. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45902. if (forceDisposeTextures) {
  45903. if (this._albedoTexture) {
  45904. this._albedoTexture.dispose();
  45905. }
  45906. if (this._ambientTexture) {
  45907. this._ambientTexture.dispose();
  45908. }
  45909. if (this._opacityTexture) {
  45910. this._opacityTexture.dispose();
  45911. }
  45912. if (this._reflectionTexture) {
  45913. this._reflectionTexture.dispose();
  45914. }
  45915. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45916. this._environmentBRDFTexture.dispose();
  45917. }
  45918. if (this._emissiveTexture) {
  45919. this._emissiveTexture.dispose();
  45920. }
  45921. if (this._metallicTexture) {
  45922. this._metallicTexture.dispose();
  45923. }
  45924. if (this._reflectivityTexture) {
  45925. this._reflectivityTexture.dispose();
  45926. }
  45927. if (this._bumpTexture) {
  45928. this._bumpTexture.dispose();
  45929. }
  45930. if (this._lightmapTexture) {
  45931. this._lightmapTexture.dispose();
  45932. }
  45933. if (this._refractionTexture) {
  45934. this._refractionTexture.dispose();
  45935. }
  45936. }
  45937. this._renderTargets.dispose();
  45938. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45939. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45940. }
  45941. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45942. };
  45943. /**
  45944. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45945. */
  45946. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45947. /**
  45948. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45949. * to enhance interoperability with other engines.
  45950. */
  45951. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45952. /**
  45953. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45954. * to enhance interoperability with other materials.
  45955. */
  45956. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45957. /**
  45958. * Stores the reflectivity values based on metallic roughness workflow.
  45959. */
  45960. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45961. __decorate([
  45962. BABYLON.serializeAsImageProcessingConfiguration()
  45963. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45964. __decorate([
  45965. BABYLON.serialize()
  45966. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45967. __decorate([
  45968. BABYLON.serialize()
  45969. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45970. return PBRBaseMaterial;
  45971. }(BABYLON.PushMaterial));
  45972. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45973. })(BABYLON || (BABYLON = {}));
  45974. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45975. var BABYLON;
  45976. (function (BABYLON) {
  45977. /**
  45978. * The Physically based simple base material of BJS.
  45979. *
  45980. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45981. * It is used as the base class for both the specGloss and metalRough conventions.
  45982. */
  45983. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45984. __extends(PBRBaseSimpleMaterial, _super);
  45985. /**
  45986. * Instantiates a new PBRMaterial instance.
  45987. *
  45988. * @param name The material name
  45989. * @param scene The scene the material will be use in.
  45990. */
  45991. function PBRBaseSimpleMaterial(name, scene) {
  45992. var _this = _super.call(this, name, scene) || this;
  45993. /**
  45994. * Number of Simultaneous lights allowed on the material.
  45995. */
  45996. _this.maxSimultaneousLights = 4;
  45997. /**
  45998. * If sets to true, disables all the lights affecting the material.
  45999. */
  46000. _this.disableLighting = false;
  46001. /**
  46002. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46003. */
  46004. _this.invertNormalMapX = false;
  46005. /**
  46006. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46007. */
  46008. _this.invertNormalMapY = false;
  46009. /**
  46010. * Emissivie color used to self-illuminate the model.
  46011. */
  46012. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46013. /**
  46014. * Occlusion Channel Strenght.
  46015. */
  46016. _this.occlusionStrength = 1.0;
  46017. /**
  46018. * If true, the light map contains occlusion information instead of lighting info.
  46019. */
  46020. _this.useLightmapAsShadowmap = false;
  46021. _this._useAlphaFromAlbedoTexture = true;
  46022. _this._useAmbientInGrayScale = true;
  46023. return _this;
  46024. }
  46025. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46026. /**
  46027. * Gets the current double sided mode.
  46028. */
  46029. get: function () {
  46030. return this._twoSidedLighting;
  46031. },
  46032. /**
  46033. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46034. */
  46035. set: function (value) {
  46036. if (this._twoSidedLighting === value) {
  46037. return;
  46038. }
  46039. this._twoSidedLighting = value;
  46040. this.backFaceCulling = !value;
  46041. this._markAllSubMeshesAsTexturesDirty();
  46042. },
  46043. enumerable: true,
  46044. configurable: true
  46045. });
  46046. /**
  46047. * Return the active textures of the material.
  46048. */
  46049. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46050. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46051. if (this.environmentTexture) {
  46052. activeTextures.push(this.environmentTexture);
  46053. }
  46054. if (this.normalTexture) {
  46055. activeTextures.push(this.normalTexture);
  46056. }
  46057. if (this.emissiveTexture) {
  46058. activeTextures.push(this.emissiveTexture);
  46059. }
  46060. if (this.occlusionTexture) {
  46061. activeTextures.push(this.occlusionTexture);
  46062. }
  46063. if (this.lightmapTexture) {
  46064. activeTextures.push(this.lightmapTexture);
  46065. }
  46066. return activeTextures;
  46067. };
  46068. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46069. if (_super.prototype.hasTexture.call(this, texture)) {
  46070. return true;
  46071. }
  46072. if (this.lightmapTexture === texture) {
  46073. return true;
  46074. }
  46075. return false;
  46076. };
  46077. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46078. return "PBRBaseSimpleMaterial";
  46079. };
  46080. __decorate([
  46081. BABYLON.serialize(),
  46082. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46083. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46084. __decorate([
  46085. BABYLON.serialize(),
  46086. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46087. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46088. __decorate([
  46089. BABYLON.serializeAsTexture(),
  46090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46091. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46092. __decorate([
  46093. BABYLON.serialize(),
  46094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46095. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46096. __decorate([
  46097. BABYLON.serialize(),
  46098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46099. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46100. __decorate([
  46101. BABYLON.serializeAsTexture(),
  46102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46103. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46104. __decorate([
  46105. BABYLON.serializeAsColor3("emissive"),
  46106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46107. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46108. __decorate([
  46109. BABYLON.serializeAsTexture(),
  46110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46111. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46112. __decorate([
  46113. BABYLON.serialize(),
  46114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46115. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46116. __decorate([
  46117. BABYLON.serializeAsTexture(),
  46118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46119. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46120. __decorate([
  46121. BABYLON.serialize(),
  46122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46123. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46124. __decorate([
  46125. BABYLON.serialize()
  46126. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46127. __decorate([
  46128. BABYLON.serializeAsTexture(),
  46129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46130. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46131. __decorate([
  46132. BABYLON.serialize(),
  46133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46134. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46135. return PBRBaseSimpleMaterial;
  46136. }(BABYLON.PBRBaseMaterial));
  46137. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46138. })(BABYLON || (BABYLON = {}));
  46139. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46140. var BABYLON;
  46141. (function (BABYLON) {
  46142. /**
  46143. * The Physically based material of BJS.
  46144. *
  46145. * This offers the main features of a standard PBR material.
  46146. * For more information, please refer to the documentation :
  46147. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46148. */
  46149. var PBRMaterial = /** @class */ (function (_super) {
  46150. __extends(PBRMaterial, _super);
  46151. /**
  46152. * Instantiates a new PBRMaterial instance.
  46153. *
  46154. * @param name The material name
  46155. * @param scene The scene the material will be use in.
  46156. */
  46157. function PBRMaterial(name, scene) {
  46158. var _this = _super.call(this, name, scene) || this;
  46159. /**
  46160. * Intensity of the direct lights e.g. the four lights available in your scene.
  46161. * This impacts both the direct diffuse and specular highlights.
  46162. */
  46163. _this.directIntensity = 1.0;
  46164. /**
  46165. * Intensity of the emissive part of the material.
  46166. * This helps controlling the emissive effect without modifying the emissive color.
  46167. */
  46168. _this.emissiveIntensity = 1.0;
  46169. /**
  46170. * Intensity of the environment e.g. how much the environment will light the object
  46171. * either through harmonics for rough material or through the refelction for shiny ones.
  46172. */
  46173. _this.environmentIntensity = 1.0;
  46174. /**
  46175. * This is a special control allowing the reduction of the specular highlights coming from the
  46176. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46177. */
  46178. _this.specularIntensity = 1.0;
  46179. /**
  46180. * Debug Control allowing disabling the bump map on this material.
  46181. */
  46182. _this.disableBumpMap = false;
  46183. /**
  46184. * AKA Occlusion Texture Intensity in other nomenclature.
  46185. */
  46186. _this.ambientTextureStrength = 1.0;
  46187. /**
  46188. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46189. * 1 means it completely occludes it
  46190. * 0 mean it has no impact
  46191. */
  46192. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46193. /**
  46194. * The color of a material in ambient lighting.
  46195. */
  46196. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46197. /**
  46198. * AKA Diffuse Color in other nomenclature.
  46199. */
  46200. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46201. /**
  46202. * AKA Specular Color in other nomenclature.
  46203. */
  46204. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46205. /**
  46206. * The color reflected from the material.
  46207. */
  46208. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46209. /**
  46210. * The color emitted from the material.
  46211. */
  46212. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46213. /**
  46214. * AKA Glossiness in other nomenclature.
  46215. */
  46216. _this.microSurface = 1.0;
  46217. /**
  46218. * source material index of refraction (IOR)' / 'destination material IOR.
  46219. */
  46220. _this.indexOfRefraction = 0.66;
  46221. /**
  46222. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46223. */
  46224. _this.invertRefractionY = false;
  46225. /**
  46226. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46227. * Materials half opaque for instance using refraction could benefit from this control.
  46228. */
  46229. _this.linkRefractionWithTransparency = false;
  46230. /**
  46231. * If true, the light map contains occlusion information instead of lighting info.
  46232. */
  46233. _this.useLightmapAsShadowmap = false;
  46234. /**
  46235. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46236. */
  46237. _this.useAlphaFromAlbedoTexture = false;
  46238. /**
  46239. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46240. */
  46241. _this.forceAlphaTest = false;
  46242. /**
  46243. * Defines the alpha limits in alpha test mode.
  46244. */
  46245. _this.alphaCutOff = 0.4;
  46246. /**
  46247. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46248. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46249. */
  46250. _this.useSpecularOverAlpha = true;
  46251. /**
  46252. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46253. */
  46254. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46255. /**
  46256. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46257. */
  46258. _this.useRoughnessFromMetallicTextureAlpha = true;
  46259. /**
  46260. * Specifies if the metallic texture contains the roughness information in its green channel.
  46261. */
  46262. _this.useRoughnessFromMetallicTextureGreen = false;
  46263. /**
  46264. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46265. */
  46266. _this.useMetallnessFromMetallicTextureBlue = false;
  46267. /**
  46268. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46269. */
  46270. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46271. /**
  46272. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46273. */
  46274. _this.useAmbientInGrayScale = false;
  46275. /**
  46276. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46277. * The material will try to infer what glossiness each pixel should be.
  46278. */
  46279. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46280. /**
  46281. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46282. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46283. */
  46284. _this.useRadianceOverAlpha = true;
  46285. /**
  46286. * Allows using an object space normal map (instead of tangent space).
  46287. */
  46288. _this.useObjectSpaceNormalMap = false;
  46289. /**
  46290. * Allows using the bump map in parallax mode.
  46291. */
  46292. _this.useParallax = false;
  46293. /**
  46294. * Allows using the bump map in parallax occlusion mode.
  46295. */
  46296. _this.useParallaxOcclusion = false;
  46297. /**
  46298. * Controls the scale bias of the parallax mode.
  46299. */
  46300. _this.parallaxScaleBias = 0.05;
  46301. /**
  46302. * If sets to true, disables all the lights affecting the material.
  46303. */
  46304. _this.disableLighting = false;
  46305. /**
  46306. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46307. */
  46308. _this.forceIrradianceInFragment = false;
  46309. /**
  46310. * Number of Simultaneous lights allowed on the material.
  46311. */
  46312. _this.maxSimultaneousLights = 4;
  46313. /**
  46314. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46315. */
  46316. _this.invertNormalMapX = false;
  46317. /**
  46318. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46319. */
  46320. _this.invertNormalMapY = false;
  46321. /**
  46322. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46323. */
  46324. _this.twoSidedLighting = false;
  46325. /**
  46326. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46327. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46328. */
  46329. _this.useAlphaFresnel = false;
  46330. /**
  46331. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46332. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46333. */
  46334. _this.useLinearAlphaFresnel = false;
  46335. /**
  46336. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46337. * And/Or occlude the blended part.
  46338. */
  46339. _this.environmentBRDFTexture = null;
  46340. /**
  46341. * Force normal to face away from face.
  46342. */
  46343. _this.forceNormalForward = false;
  46344. /**
  46345. * Enables specular anti aliasing in the PBR shader.
  46346. * It will both interacts on the Geometry for analytical and IBL lighting.
  46347. * It also prefilter the roughness map based on the bump values.
  46348. */
  46349. _this.enableSpecularAntiAliasing = false;
  46350. /**
  46351. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46352. * makes the reflect vector face the model (under horizon).
  46353. */
  46354. _this.useHorizonOcclusion = true;
  46355. /**
  46356. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46357. * too much the area relying on ambient texture to define their ambient occlusion.
  46358. */
  46359. _this.useRadianceOcclusion = true;
  46360. /**
  46361. * If set to true, no lighting calculations will be applied.
  46362. */
  46363. _this.unlit = false;
  46364. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46365. return _this;
  46366. }
  46367. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46368. /**
  46369. * BJS is using an harcoded light falloff based on a manually sets up range.
  46370. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46371. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46372. */
  46373. get: function () {
  46374. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46375. },
  46376. /**
  46377. * BJS is using an harcoded light falloff based on a manually sets up range.
  46378. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46379. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46380. */
  46381. set: function (value) {
  46382. if (value !== this.usePhysicalLightFalloff) {
  46383. // Ensure the effect will be rebuilt.
  46384. this._markAllSubMeshesAsTexturesDirty();
  46385. if (value) {
  46386. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46387. }
  46388. else {
  46389. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46390. }
  46391. }
  46392. },
  46393. enumerable: true,
  46394. configurable: true
  46395. });
  46396. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46397. /**
  46398. * In order to support the falloff compatibility with gltf, a special mode has been added
  46399. * to reproduce the gltf light falloff.
  46400. */
  46401. get: function () {
  46402. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46403. },
  46404. /**
  46405. * In order to support the falloff compatibility with gltf, a special mode has been added
  46406. * to reproduce the gltf light falloff.
  46407. */
  46408. set: function (value) {
  46409. if (value !== this.useGLTFLightFalloff) {
  46410. // Ensure the effect will be rebuilt.
  46411. this._markAllSubMeshesAsTexturesDirty();
  46412. if (value) {
  46413. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46414. }
  46415. else {
  46416. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46417. }
  46418. }
  46419. },
  46420. enumerable: true,
  46421. configurable: true
  46422. });
  46423. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46424. /**
  46425. * Gets the image processing configuration used either in this material.
  46426. */
  46427. get: function () {
  46428. return this._imageProcessingConfiguration;
  46429. },
  46430. /**
  46431. * Sets the Default image processing configuration used either in the this material.
  46432. *
  46433. * If sets to null, the scene one is in use.
  46434. */
  46435. set: function (value) {
  46436. this._attachImageProcessingConfiguration(value);
  46437. // Ensure the effect will be rebuilt.
  46438. this._markAllSubMeshesAsTexturesDirty();
  46439. },
  46440. enumerable: true,
  46441. configurable: true
  46442. });
  46443. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46444. /**
  46445. * Gets wether the color curves effect is enabled.
  46446. */
  46447. get: function () {
  46448. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46449. },
  46450. /**
  46451. * Sets wether the color curves effect is enabled.
  46452. */
  46453. set: function (value) {
  46454. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46455. },
  46456. enumerable: true,
  46457. configurable: true
  46458. });
  46459. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46460. /**
  46461. * Gets wether the color grading effect is enabled.
  46462. */
  46463. get: function () {
  46464. return this.imageProcessingConfiguration.colorGradingEnabled;
  46465. },
  46466. /**
  46467. * Gets wether the color grading effect is enabled.
  46468. */
  46469. set: function (value) {
  46470. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46471. },
  46472. enumerable: true,
  46473. configurable: true
  46474. });
  46475. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46476. /**
  46477. * Gets wether tonemapping is enabled or not.
  46478. */
  46479. get: function () {
  46480. return this._imageProcessingConfiguration.toneMappingEnabled;
  46481. },
  46482. /**
  46483. * Sets wether tonemapping is enabled or not
  46484. */
  46485. set: function (value) {
  46486. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46487. },
  46488. enumerable: true,
  46489. configurable: true
  46490. });
  46491. ;
  46492. ;
  46493. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46494. /**
  46495. * The camera exposure used on this material.
  46496. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46497. * This corresponds to a photographic exposure.
  46498. */
  46499. get: function () {
  46500. return this._imageProcessingConfiguration.exposure;
  46501. },
  46502. /**
  46503. * The camera exposure used on this material.
  46504. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46505. * This corresponds to a photographic exposure.
  46506. */
  46507. set: function (value) {
  46508. this._imageProcessingConfiguration.exposure = value;
  46509. },
  46510. enumerable: true,
  46511. configurable: true
  46512. });
  46513. ;
  46514. ;
  46515. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46516. /**
  46517. * Gets The camera contrast used on this material.
  46518. */
  46519. get: function () {
  46520. return this._imageProcessingConfiguration.contrast;
  46521. },
  46522. /**
  46523. * Sets The camera contrast used on this material.
  46524. */
  46525. set: function (value) {
  46526. this._imageProcessingConfiguration.contrast = value;
  46527. },
  46528. enumerable: true,
  46529. configurable: true
  46530. });
  46531. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46532. /**
  46533. * Gets the Color Grading 2D Lookup Texture.
  46534. */
  46535. get: function () {
  46536. return this._imageProcessingConfiguration.colorGradingTexture;
  46537. },
  46538. /**
  46539. * Sets the Color Grading 2D Lookup Texture.
  46540. */
  46541. set: function (value) {
  46542. this._imageProcessingConfiguration.colorGradingTexture = value;
  46543. },
  46544. enumerable: true,
  46545. configurable: true
  46546. });
  46547. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46548. /**
  46549. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46550. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46551. * 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;
  46552. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46553. */
  46554. get: function () {
  46555. return this._imageProcessingConfiguration.colorCurves;
  46556. },
  46557. /**
  46558. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46559. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46560. * 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;
  46561. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46562. */
  46563. set: function (value) {
  46564. this._imageProcessingConfiguration.colorCurves = value;
  46565. },
  46566. enumerable: true,
  46567. configurable: true
  46568. });
  46569. /**
  46570. * Returns the name of this material class.
  46571. */
  46572. PBRMaterial.prototype.getClassName = function () {
  46573. return "PBRMaterial";
  46574. };
  46575. /**
  46576. * Returns an array of the actively used textures.
  46577. * @returns - Array of BaseTextures
  46578. */
  46579. PBRMaterial.prototype.getActiveTextures = function () {
  46580. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46581. if (this._albedoTexture) {
  46582. activeTextures.push(this._albedoTexture);
  46583. }
  46584. if (this._ambientTexture) {
  46585. activeTextures.push(this._ambientTexture);
  46586. }
  46587. if (this._opacityTexture) {
  46588. activeTextures.push(this._opacityTexture);
  46589. }
  46590. if (this._reflectionTexture) {
  46591. activeTextures.push(this._reflectionTexture);
  46592. }
  46593. if (this._emissiveTexture) {
  46594. activeTextures.push(this._emissiveTexture);
  46595. }
  46596. if (this._reflectivityTexture) {
  46597. activeTextures.push(this._reflectivityTexture);
  46598. }
  46599. if (this._metallicTexture) {
  46600. activeTextures.push(this._metallicTexture);
  46601. }
  46602. if (this._microSurfaceTexture) {
  46603. activeTextures.push(this._microSurfaceTexture);
  46604. }
  46605. if (this._bumpTexture) {
  46606. activeTextures.push(this._bumpTexture);
  46607. }
  46608. if (this._lightmapTexture) {
  46609. activeTextures.push(this._lightmapTexture);
  46610. }
  46611. if (this._refractionTexture) {
  46612. activeTextures.push(this._refractionTexture);
  46613. }
  46614. return activeTextures;
  46615. };
  46616. /**
  46617. * Checks to see if a texture is used in the material.
  46618. * @param texture - Base texture to use.
  46619. * @returns - Boolean specifying if a texture is used in the material.
  46620. */
  46621. PBRMaterial.prototype.hasTexture = function (texture) {
  46622. if (_super.prototype.hasTexture.call(this, texture)) {
  46623. return true;
  46624. }
  46625. if (this._albedoTexture === texture) {
  46626. return true;
  46627. }
  46628. if (this._ambientTexture === texture) {
  46629. return true;
  46630. }
  46631. if (this._opacityTexture === texture) {
  46632. return true;
  46633. }
  46634. if (this._reflectionTexture === texture) {
  46635. return true;
  46636. }
  46637. if (this._reflectivityTexture === texture) {
  46638. return true;
  46639. }
  46640. if (this._metallicTexture === texture) {
  46641. return true;
  46642. }
  46643. if (this._microSurfaceTexture === texture) {
  46644. return true;
  46645. }
  46646. if (this._bumpTexture === texture) {
  46647. return true;
  46648. }
  46649. if (this._lightmapTexture === texture) {
  46650. return true;
  46651. }
  46652. if (this._refractionTexture === texture) {
  46653. return true;
  46654. }
  46655. return false;
  46656. };
  46657. /**
  46658. * Makes a duplicate of the current material.
  46659. * @param name - name to use for the new material.
  46660. */
  46661. PBRMaterial.prototype.clone = function (name) {
  46662. var _this = this;
  46663. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46664. clone.id = name;
  46665. clone.name = name;
  46666. return clone;
  46667. };
  46668. /**
  46669. * Serializes this PBR Material.
  46670. * @returns - An object with the serialized material.
  46671. */
  46672. PBRMaterial.prototype.serialize = function () {
  46673. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46674. serializationObject.customType = "BABYLON.PBRMaterial";
  46675. return serializationObject;
  46676. };
  46677. // Statics
  46678. /**
  46679. * Parses a PBR Material from a serialized object.
  46680. * @param source - Serialized object.
  46681. * @param scene - BJS scene instance.
  46682. * @param rootUrl - url for the scene object
  46683. * @returns - PBRMaterial
  46684. */
  46685. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46686. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46687. };
  46688. /**
  46689. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46690. */
  46691. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  46692. /**
  46693. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46694. */
  46695. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  46696. /**
  46697. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46698. */
  46699. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  46700. /**
  46701. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46702. * They are also discarded below the alpha cutoff threshold to improve performances.
  46703. */
  46704. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46705. /**
  46706. * Defines the default value of how much AO map is occluding the analytical lights
  46707. * (point spot...).
  46708. */
  46709. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  46710. __decorate([
  46711. BABYLON.serialize(),
  46712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46713. ], PBRMaterial.prototype, "directIntensity", void 0);
  46714. __decorate([
  46715. BABYLON.serialize(),
  46716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46717. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46718. __decorate([
  46719. BABYLON.serialize(),
  46720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46721. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46722. __decorate([
  46723. BABYLON.serialize(),
  46724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46725. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46726. __decorate([
  46727. BABYLON.serialize(),
  46728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46729. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46730. __decorate([
  46731. BABYLON.serializeAsTexture(),
  46732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46733. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46734. __decorate([
  46735. BABYLON.serializeAsTexture(),
  46736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46737. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46738. __decorate([
  46739. BABYLON.serialize(),
  46740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46741. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46742. __decorate([
  46743. BABYLON.serialize(),
  46744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46745. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  46746. __decorate([
  46747. BABYLON.serializeAsTexture(),
  46748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46749. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46750. __decorate([
  46751. BABYLON.serializeAsTexture(),
  46752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46753. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46754. __decorate([
  46755. BABYLON.serializeAsTexture(),
  46756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46757. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46758. __decorate([
  46759. BABYLON.serializeAsTexture(),
  46760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46761. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46762. __decorate([
  46763. BABYLON.serializeAsTexture(),
  46764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46765. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46766. __decorate([
  46767. BABYLON.serialize(),
  46768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46769. ], PBRMaterial.prototype, "metallic", void 0);
  46770. __decorate([
  46771. BABYLON.serialize(),
  46772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46773. ], PBRMaterial.prototype, "roughness", void 0);
  46774. __decorate([
  46775. BABYLON.serializeAsTexture(),
  46776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46777. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46778. __decorate([
  46779. BABYLON.serializeAsTexture(),
  46780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46781. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46782. __decorate([
  46783. BABYLON.serializeAsTexture(),
  46784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46785. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46786. __decorate([
  46787. BABYLON.serializeAsTexture(),
  46788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46789. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46790. __decorate([
  46791. BABYLON.serializeAsColor3("ambient"),
  46792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46793. ], PBRMaterial.prototype, "ambientColor", void 0);
  46794. __decorate([
  46795. BABYLON.serializeAsColor3("albedo"),
  46796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46797. ], PBRMaterial.prototype, "albedoColor", void 0);
  46798. __decorate([
  46799. BABYLON.serializeAsColor3("reflectivity"),
  46800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46801. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46802. __decorate([
  46803. BABYLON.serializeAsColor3("reflection"),
  46804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46805. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46806. __decorate([
  46807. BABYLON.serializeAsColor3("emissive"),
  46808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46809. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46810. __decorate([
  46811. BABYLON.serialize(),
  46812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46813. ], PBRMaterial.prototype, "microSurface", void 0);
  46814. __decorate([
  46815. BABYLON.serialize(),
  46816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46817. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46818. __decorate([
  46819. BABYLON.serialize(),
  46820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46821. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46822. __decorate([
  46823. BABYLON.serialize(),
  46824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46825. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46826. __decorate([
  46827. BABYLON.serialize(),
  46828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46829. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46830. __decorate([
  46831. BABYLON.serialize(),
  46832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46833. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46834. __decorate([
  46835. BABYLON.serialize(),
  46836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46837. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46838. __decorate([
  46839. BABYLON.serialize(),
  46840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46841. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46842. __decorate([
  46843. BABYLON.serialize(),
  46844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46845. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46846. __decorate([
  46847. BABYLON.serialize(),
  46848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46849. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46850. __decorate([
  46851. BABYLON.serialize(),
  46852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46853. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46854. __decorate([
  46855. BABYLON.serialize(),
  46856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46857. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46858. __decorate([
  46859. BABYLON.serialize(),
  46860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46861. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46862. __decorate([
  46863. BABYLON.serialize(),
  46864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46865. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46866. __decorate([
  46867. BABYLON.serialize(),
  46868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46869. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46870. __decorate([
  46871. BABYLON.serialize(),
  46872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46873. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46874. __decorate([
  46875. BABYLON.serialize()
  46876. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46877. __decorate([
  46878. BABYLON.serialize()
  46879. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46880. __decorate([
  46881. BABYLON.serialize(),
  46882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46883. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46884. __decorate([
  46885. BABYLON.serialize(),
  46886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46887. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46888. __decorate([
  46889. BABYLON.serialize(),
  46890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46891. ], PBRMaterial.prototype, "useParallax", void 0);
  46892. __decorate([
  46893. BABYLON.serialize(),
  46894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46895. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46896. __decorate([
  46897. BABYLON.serialize(),
  46898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46899. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46900. __decorate([
  46901. BABYLON.serialize(),
  46902. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46903. ], PBRMaterial.prototype, "disableLighting", void 0);
  46904. __decorate([
  46905. BABYLON.serialize(),
  46906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46907. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46908. __decorate([
  46909. BABYLON.serialize(),
  46910. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46911. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46912. __decorate([
  46913. BABYLON.serialize(),
  46914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46915. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46916. __decorate([
  46917. BABYLON.serialize(),
  46918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46919. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46920. __decorate([
  46921. BABYLON.serialize(),
  46922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46923. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46924. __decorate([
  46925. BABYLON.serialize(),
  46926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46927. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46928. __decorate([
  46929. BABYLON.serialize(),
  46930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46931. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46932. __decorate([
  46933. BABYLON.serializeAsTexture(),
  46934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46935. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46936. __decorate([
  46937. BABYLON.serialize(),
  46938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46939. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46940. __decorate([
  46941. BABYLON.serialize(),
  46942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46943. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46944. __decorate([
  46945. BABYLON.serialize(),
  46946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46947. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46948. __decorate([
  46949. BABYLON.serialize(),
  46950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46951. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46952. __decorate([
  46953. BABYLON.serialize(),
  46954. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46955. ], PBRMaterial.prototype, "unlit", void 0);
  46956. return PBRMaterial;
  46957. }(BABYLON.PBRBaseMaterial));
  46958. BABYLON.PBRMaterial = PBRMaterial;
  46959. })(BABYLON || (BABYLON = {}));
  46960. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46961. var BABYLON;
  46962. (function (BABYLON) {
  46963. /**
  46964. * The PBR material of BJS following the metal roughness convention.
  46965. *
  46966. * This fits to the PBR convention in the GLTF definition:
  46967. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46968. */
  46969. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46970. __extends(PBRMetallicRoughnessMaterial, _super);
  46971. /**
  46972. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46973. *
  46974. * @param name The material name
  46975. * @param scene The scene the material will be use in.
  46976. */
  46977. function PBRMetallicRoughnessMaterial(name, scene) {
  46978. var _this = _super.call(this, name, scene) || this;
  46979. _this._useRoughnessFromMetallicTextureAlpha = false;
  46980. _this._useRoughnessFromMetallicTextureGreen = true;
  46981. _this._useMetallnessFromMetallicTextureBlue = true;
  46982. _this.metallic = 1.0;
  46983. _this.roughness = 1.0;
  46984. return _this;
  46985. }
  46986. /**
  46987. * Return the currrent class name of the material.
  46988. */
  46989. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46990. return "PBRMetallicRoughnessMaterial";
  46991. };
  46992. /**
  46993. * Return the active textures of the material.
  46994. */
  46995. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46996. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46997. if (this.baseTexture) {
  46998. activeTextures.push(this.baseTexture);
  46999. }
  47000. if (this.metallicRoughnessTexture) {
  47001. activeTextures.push(this.metallicRoughnessTexture);
  47002. }
  47003. return activeTextures;
  47004. };
  47005. /**
  47006. * Checks to see if a texture is used in the material.
  47007. * @param texture - Base texture to use.
  47008. * @returns - Boolean specifying if a texture is used in the material.
  47009. */
  47010. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47011. if (_super.prototype.hasTexture.call(this, texture)) {
  47012. return true;
  47013. }
  47014. if (this.baseTexture === texture) {
  47015. return true;
  47016. }
  47017. if (this.metallicRoughnessTexture === texture) {
  47018. return true;
  47019. }
  47020. return false;
  47021. };
  47022. /**
  47023. * Makes a duplicate of the current material.
  47024. * @param name - name to use for the new material.
  47025. */
  47026. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47027. var _this = this;
  47028. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47029. clone.id = name;
  47030. clone.name = name;
  47031. return clone;
  47032. };
  47033. /**
  47034. * Serialize the material to a parsable JSON object.
  47035. */
  47036. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47037. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47038. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47039. return serializationObject;
  47040. };
  47041. /**
  47042. * Parses a JSON object correponding to the serialize function.
  47043. */
  47044. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47045. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47046. };
  47047. __decorate([
  47048. BABYLON.serializeAsColor3(),
  47049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47050. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47051. __decorate([
  47052. BABYLON.serializeAsTexture(),
  47053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47054. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47055. __decorate([
  47056. BABYLON.serialize(),
  47057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47058. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47059. __decorate([
  47060. BABYLON.serialize(),
  47061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47062. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47063. __decorate([
  47064. BABYLON.serializeAsTexture(),
  47065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47066. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47067. return PBRMetallicRoughnessMaterial;
  47068. }(BABYLON.PBRBaseSimpleMaterial));
  47069. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47070. })(BABYLON || (BABYLON = {}));
  47071. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47072. var BABYLON;
  47073. (function (BABYLON) {
  47074. /**
  47075. * The PBR material of BJS following the specular glossiness convention.
  47076. *
  47077. * This fits to the PBR convention in the GLTF definition:
  47078. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47079. */
  47080. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47081. __extends(PBRSpecularGlossinessMaterial, _super);
  47082. /**
  47083. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47084. *
  47085. * @param name The material name
  47086. * @param scene The scene the material will be use in.
  47087. */
  47088. function PBRSpecularGlossinessMaterial(name, scene) {
  47089. var _this = _super.call(this, name, scene) || this;
  47090. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47091. return _this;
  47092. }
  47093. /**
  47094. * Return the currrent class name of the material.
  47095. */
  47096. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47097. return "PBRSpecularGlossinessMaterial";
  47098. };
  47099. /**
  47100. * Return the active textures of the material.
  47101. */
  47102. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47103. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47104. if (this.diffuseTexture) {
  47105. activeTextures.push(this.diffuseTexture);
  47106. }
  47107. if (this.specularGlossinessTexture) {
  47108. activeTextures.push(this.specularGlossinessTexture);
  47109. }
  47110. return activeTextures;
  47111. };
  47112. /**
  47113. * Checks to see if a texture is used in the material.
  47114. * @param texture - Base texture to use.
  47115. * @returns - Boolean specifying if a texture is used in the material.
  47116. */
  47117. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47118. if (_super.prototype.hasTexture.call(this, texture)) {
  47119. return true;
  47120. }
  47121. if (this.diffuseTexture === texture) {
  47122. return true;
  47123. }
  47124. if (this.specularGlossinessTexture === texture) {
  47125. return true;
  47126. }
  47127. return false;
  47128. };
  47129. /**
  47130. * Makes a duplicate of the current material.
  47131. * @param name - name to use for the new material.
  47132. */
  47133. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47134. var _this = this;
  47135. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47136. clone.id = name;
  47137. clone.name = name;
  47138. return clone;
  47139. };
  47140. /**
  47141. * Serialize the material to a parsable JSON object.
  47142. */
  47143. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47144. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47145. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47146. return serializationObject;
  47147. };
  47148. /**
  47149. * Parses a JSON object correponding to the serialize function.
  47150. */
  47151. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47152. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47153. };
  47154. __decorate([
  47155. BABYLON.serializeAsColor3("diffuse"),
  47156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47157. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47158. __decorate([
  47159. BABYLON.serializeAsTexture(),
  47160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47161. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47162. __decorate([
  47163. BABYLON.serializeAsColor3("specular"),
  47164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47165. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47166. __decorate([
  47167. BABYLON.serialize(),
  47168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47169. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47170. __decorate([
  47171. BABYLON.serializeAsTexture(),
  47172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47173. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47174. return PBRSpecularGlossinessMaterial;
  47175. }(BABYLON.PBRBaseSimpleMaterial));
  47176. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47177. })(BABYLON || (BABYLON = {}));
  47178. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47179. var BABYLON;
  47180. (function (BABYLON) {
  47181. /**
  47182. * This is a list of all the different input types that are available in the application.
  47183. * Fo instance: ArcRotateCameraGamepadInput...
  47184. */
  47185. BABYLON.CameraInputTypes = {};
  47186. /**
  47187. * This represents the input manager used within a camera.
  47188. * It helps dealing with all the different kind of input attached to a camera.
  47189. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47190. */
  47191. var CameraInputsManager = /** @class */ (function () {
  47192. /**
  47193. * Instantiate a new Camera Input Manager.
  47194. * @param camera Defines the camera the input manager blongs to
  47195. */
  47196. function CameraInputsManager(camera) {
  47197. this.attached = {};
  47198. this.camera = camera;
  47199. this.checkInputs = function () { };
  47200. }
  47201. /**
  47202. * Add an input method to a camera
  47203. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47204. * @param input camera input method
  47205. */
  47206. CameraInputsManager.prototype.add = function (input) {
  47207. var type = input.getSimpleName();
  47208. if (this.attached[type]) {
  47209. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47210. return;
  47211. }
  47212. this.attached[type] = input;
  47213. input.camera = this.camera;
  47214. //for checkInputs, we are dynamically creating a function
  47215. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47216. if (input.checkInputs) {
  47217. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47218. }
  47219. if (this.attachedElement) {
  47220. input.attachControl(this.attachedElement);
  47221. }
  47222. };
  47223. /**
  47224. * Remove a specific input method from a camera
  47225. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47226. * @param inputToRemove camera input method
  47227. */
  47228. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47229. for (var cam in this.attached) {
  47230. var input = this.attached[cam];
  47231. if (input === inputToRemove) {
  47232. input.detachControl(this.attachedElement);
  47233. input.camera = null;
  47234. delete this.attached[cam];
  47235. this.rebuildInputCheck();
  47236. }
  47237. }
  47238. };
  47239. /**
  47240. * Remove a specific input type from a camera
  47241. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47242. * @param inputType the type of the input to remove
  47243. */
  47244. CameraInputsManager.prototype.removeByType = function (inputType) {
  47245. for (var cam in this.attached) {
  47246. var input = this.attached[cam];
  47247. if (input.getClassName() === inputType) {
  47248. input.detachControl(this.attachedElement);
  47249. input.camera = null;
  47250. delete this.attached[cam];
  47251. this.rebuildInputCheck();
  47252. }
  47253. }
  47254. };
  47255. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47256. var current = this.checkInputs;
  47257. return function () {
  47258. current();
  47259. fn();
  47260. };
  47261. };
  47262. /**
  47263. * Attach the input controls to the currently attached dom element to listen the events from.
  47264. * @param input Defines the input to attach
  47265. */
  47266. CameraInputsManager.prototype.attachInput = function (input) {
  47267. if (this.attachedElement) {
  47268. input.attachControl(this.attachedElement, this.noPreventDefault);
  47269. }
  47270. };
  47271. /**
  47272. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47273. * @param element Defines the dom element to collect the events from
  47274. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47275. */
  47276. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47277. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47278. if (this.attachedElement) {
  47279. return;
  47280. }
  47281. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47282. this.attachedElement = element;
  47283. this.noPreventDefault = noPreventDefault;
  47284. for (var cam in this.attached) {
  47285. this.attached[cam].attachControl(element, noPreventDefault);
  47286. }
  47287. };
  47288. /**
  47289. * Detach the current manager inputs controls from a specific dom element.
  47290. * @param element Defines the dom element to collect the events from
  47291. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47292. */
  47293. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47294. if (disconnect === void 0) { disconnect = false; }
  47295. if (this.attachedElement !== element) {
  47296. return;
  47297. }
  47298. for (var cam in this.attached) {
  47299. this.attached[cam].detachControl(element);
  47300. if (disconnect) {
  47301. this.attached[cam].camera = null;
  47302. }
  47303. }
  47304. this.attachedElement = null;
  47305. };
  47306. /**
  47307. * Rebuild the dynamic inputCheck function from the current list of
  47308. * defined inputs in the manager.
  47309. */
  47310. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47311. this.checkInputs = function () { };
  47312. for (var cam in this.attached) {
  47313. var input = this.attached[cam];
  47314. if (input.checkInputs) {
  47315. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47316. }
  47317. }
  47318. };
  47319. /**
  47320. * Remove all attached input methods from a camera
  47321. */
  47322. CameraInputsManager.prototype.clear = function () {
  47323. if (this.attachedElement) {
  47324. this.detachElement(this.attachedElement, true);
  47325. }
  47326. this.attached = {};
  47327. this.attachedElement = null;
  47328. this.checkInputs = function () { };
  47329. };
  47330. /**
  47331. * Serialize the current input manager attached to a camera.
  47332. * This ensures than once parsed,
  47333. * the input associated to the camera will be identical to the current ones
  47334. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47335. */
  47336. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47337. var inputs = {};
  47338. for (var cam in this.attached) {
  47339. var input = this.attached[cam];
  47340. var res = BABYLON.SerializationHelper.Serialize(input);
  47341. inputs[input.getClassName()] = res;
  47342. }
  47343. serializedCamera.inputsmgr = inputs;
  47344. };
  47345. /**
  47346. * Parses an input manager serialized JSON to restore the previous list of inputs
  47347. * and states associated to a camera.
  47348. * @param parsedCamera Defines the JSON to parse
  47349. */
  47350. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47351. var parsedInputs = parsedCamera.inputsmgr;
  47352. if (parsedInputs) {
  47353. this.clear();
  47354. for (var n in parsedInputs) {
  47355. var construct = BABYLON.CameraInputTypes[n];
  47356. if (construct) {
  47357. var parsedinput = parsedInputs[n];
  47358. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47359. this.add(input);
  47360. }
  47361. }
  47362. }
  47363. else {
  47364. //2016-03-08 this part is for managing backward compatibility
  47365. for (var n in this.attached) {
  47366. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47367. if (construct) {
  47368. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47369. this.remove(this.attached[n]);
  47370. this.add(input);
  47371. }
  47372. }
  47373. }
  47374. };
  47375. return CameraInputsManager;
  47376. }());
  47377. BABYLON.CameraInputsManager = CameraInputsManager;
  47378. })(BABYLON || (BABYLON = {}));
  47379. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47380. var BABYLON;
  47381. (function (BABYLON) {
  47382. /**
  47383. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47384. * This is the base of the follow, arc rotate cameras and Free camera
  47385. * @see http://doc.babylonjs.com/features/cameras
  47386. */
  47387. var TargetCamera = /** @class */ (function (_super) {
  47388. __extends(TargetCamera, _super);
  47389. /**
  47390. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47391. * This is the base of the follow, arc rotate cameras and Free camera
  47392. * @see http://doc.babylonjs.com/features/cameras
  47393. * @param name Defines the name of the camera in the scene
  47394. * @param position Defines the start position of the camera in the scene
  47395. * @param scene Defines the scene the camera belongs to
  47396. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47397. */
  47398. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47399. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47400. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47401. /**
  47402. * Define the current direction the camera is moving to
  47403. */
  47404. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47405. /**
  47406. * Define the current rotation the camera is rotating to
  47407. */
  47408. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47409. /**
  47410. * Define the current rotation of the camera
  47411. */
  47412. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47413. /**
  47414. * Define the current speed of the camera
  47415. */
  47416. _this.speed = 2.0;
  47417. /**
  47418. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47419. * around all axis.
  47420. */
  47421. _this.noRotationConstraint = false;
  47422. /**
  47423. * Define the current target of the camera as an object or a position.
  47424. */
  47425. _this.lockedTarget = null;
  47426. /** @hidden */
  47427. _this._currentTarget = BABYLON.Vector3.Zero();
  47428. /** @hidden */
  47429. _this._viewMatrix = BABYLON.Matrix.Zero();
  47430. /** @hidden */
  47431. _this._camMatrix = BABYLON.Matrix.Zero();
  47432. /** @hidden */
  47433. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47434. /** @hidden */
  47435. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47436. /** @hidden */
  47437. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47438. /** @hidden */
  47439. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47440. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47441. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47442. _this._defaultUp = BABYLON.Vector3.Up();
  47443. _this._cachedRotationZ = 0;
  47444. return _this;
  47445. }
  47446. /**
  47447. * Gets the position in front of the camera at a given distance.
  47448. * @param distance The distance from the camera we want the position to be
  47449. * @returns the position
  47450. */
  47451. TargetCamera.prototype.getFrontPosition = function (distance) {
  47452. this.getWorldMatrix();
  47453. var direction = this.getTarget().subtract(this.position);
  47454. direction.normalize();
  47455. direction.scaleInPlace(distance);
  47456. return this.globalPosition.add(direction);
  47457. };
  47458. /** @hidden */
  47459. TargetCamera.prototype._getLockedTargetPosition = function () {
  47460. if (!this.lockedTarget) {
  47461. return null;
  47462. }
  47463. if (this.lockedTarget.absolutePosition) {
  47464. this.lockedTarget.computeWorldMatrix();
  47465. }
  47466. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47467. };
  47468. /**
  47469. * Store current camera state of the camera (fov, position, rotation, etc..)
  47470. * @returns the camera
  47471. */
  47472. TargetCamera.prototype.storeState = function () {
  47473. this._storedPosition = this.position.clone();
  47474. this._storedRotation = this.rotation.clone();
  47475. if (this.rotationQuaternion) {
  47476. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47477. }
  47478. return _super.prototype.storeState.call(this);
  47479. };
  47480. /**
  47481. * Restored camera state. You must call storeState() first
  47482. * @returns whether it was successful or not
  47483. * @hidden
  47484. */
  47485. TargetCamera.prototype._restoreStateValues = function () {
  47486. if (!_super.prototype._restoreStateValues.call(this)) {
  47487. return false;
  47488. }
  47489. this.position = this._storedPosition.clone();
  47490. this.rotation = this._storedRotation.clone();
  47491. if (this.rotationQuaternion) {
  47492. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47493. }
  47494. this.cameraDirection.copyFromFloats(0, 0, 0);
  47495. this.cameraRotation.copyFromFloats(0, 0);
  47496. return true;
  47497. };
  47498. /** @hidden */
  47499. TargetCamera.prototype._initCache = function () {
  47500. _super.prototype._initCache.call(this);
  47501. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47502. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47503. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47504. };
  47505. /** @hidden */
  47506. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47507. if (!ignoreParentClass) {
  47508. _super.prototype._updateCache.call(this);
  47509. }
  47510. var lockedTargetPosition = this._getLockedTargetPosition();
  47511. if (!lockedTargetPosition) {
  47512. this._cache.lockedTarget = null;
  47513. }
  47514. else {
  47515. if (!this._cache.lockedTarget) {
  47516. this._cache.lockedTarget = lockedTargetPosition.clone();
  47517. }
  47518. else {
  47519. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47520. }
  47521. }
  47522. this._cache.rotation.copyFrom(this.rotation);
  47523. if (this.rotationQuaternion)
  47524. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47525. };
  47526. // Synchronized
  47527. /** @hidden */
  47528. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47529. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47530. return false;
  47531. }
  47532. var lockedTargetPosition = this._getLockedTargetPosition();
  47533. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47534. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47535. };
  47536. // Methods
  47537. /** @hidden */
  47538. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47539. var engine = this.getEngine();
  47540. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47541. };
  47542. // Target
  47543. /** @hidden */
  47544. TargetCamera.prototype.setTarget = function (target) {
  47545. this.upVector.normalize();
  47546. if (this.position.z === target.z) {
  47547. this.position.z += BABYLON.Epsilon;
  47548. }
  47549. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  47550. this._camMatrix.invert();
  47551. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47552. var vDir = target.subtract(this.position);
  47553. if (vDir.x >= 0.0) {
  47554. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47555. }
  47556. else {
  47557. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47558. }
  47559. this.rotation.z = 0;
  47560. if (isNaN(this.rotation.x)) {
  47561. this.rotation.x = 0;
  47562. }
  47563. if (isNaN(this.rotation.y)) {
  47564. this.rotation.y = 0;
  47565. }
  47566. if (isNaN(this.rotation.z)) {
  47567. this.rotation.z = 0;
  47568. }
  47569. if (this.rotationQuaternion) {
  47570. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47571. }
  47572. };
  47573. /**
  47574. * Return the current target position of the camera. This value is expressed in local space.
  47575. * @returns the target position
  47576. */
  47577. TargetCamera.prototype.getTarget = function () {
  47578. return this._currentTarget;
  47579. };
  47580. /** @hidden */
  47581. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47582. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47583. };
  47584. /** @hidden */
  47585. TargetCamera.prototype._updatePosition = function () {
  47586. if (this.parent) {
  47587. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47588. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47589. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47590. return;
  47591. }
  47592. this.position.addInPlace(this.cameraDirection);
  47593. };
  47594. /** @hidden */
  47595. TargetCamera.prototype._checkInputs = function () {
  47596. var needToMove = this._decideIfNeedsToMove();
  47597. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47598. // Move
  47599. if (needToMove) {
  47600. this._updatePosition();
  47601. }
  47602. // Rotate
  47603. if (needToRotate) {
  47604. this.rotation.x += this.cameraRotation.x;
  47605. this.rotation.y += this.cameraRotation.y;
  47606. //rotate, if quaternion is set and rotation was used
  47607. if (this.rotationQuaternion) {
  47608. var len = this.rotation.lengthSquared();
  47609. if (len) {
  47610. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47611. }
  47612. }
  47613. if (!this.noRotationConstraint) {
  47614. var limit = (Math.PI / 2) * 0.95;
  47615. if (this.rotation.x > limit)
  47616. this.rotation.x = limit;
  47617. if (this.rotation.x < -limit)
  47618. this.rotation.x = -limit;
  47619. }
  47620. }
  47621. // Inertia
  47622. if (needToMove) {
  47623. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47624. this.cameraDirection.x = 0;
  47625. }
  47626. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47627. this.cameraDirection.y = 0;
  47628. }
  47629. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47630. this.cameraDirection.z = 0;
  47631. }
  47632. this.cameraDirection.scaleInPlace(this.inertia);
  47633. }
  47634. if (needToRotate) {
  47635. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47636. this.cameraRotation.x = 0;
  47637. }
  47638. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47639. this.cameraRotation.y = 0;
  47640. }
  47641. this.cameraRotation.scaleInPlace(this.inertia);
  47642. }
  47643. _super.prototype._checkInputs.call(this);
  47644. };
  47645. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47646. if (this.rotationQuaternion) {
  47647. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47648. }
  47649. else {
  47650. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47651. }
  47652. };
  47653. /**
  47654. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  47655. * @returns the current camera
  47656. */
  47657. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  47658. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  47659. return this;
  47660. };
  47661. /** @hidden */
  47662. TargetCamera.prototype._getViewMatrix = function () {
  47663. if (this.lockedTarget) {
  47664. this.setTarget(this._getLockedTargetPosition());
  47665. }
  47666. // Compute
  47667. this._updateCameraRotationMatrix();
  47668. // Apply the changed rotation to the upVector.
  47669. if (this._cachedRotationZ != this.rotation.z) {
  47670. this._rotateUpVectorWithCameraRotationMatrix();
  47671. this._cachedRotationZ = this.rotation.z;
  47672. }
  47673. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47674. // Computing target and final matrix
  47675. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47676. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  47677. return this._viewMatrix;
  47678. };
  47679. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47680. if (this.parent) {
  47681. var parentWorldMatrix = this.parent.getWorldMatrix();
  47682. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  47683. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47684. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47685. this._markSyncedWithParent();
  47686. }
  47687. else {
  47688. this._globalPosition.copyFrom(position);
  47689. this._globalCurrentTarget.copyFrom(target);
  47690. this._globalCurrentUpVector.copyFrom(up);
  47691. }
  47692. if (this.getScene().useRightHandedSystem) {
  47693. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47694. }
  47695. else {
  47696. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47697. }
  47698. };
  47699. /**
  47700. * @hidden
  47701. */
  47702. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47703. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47704. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47705. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47706. if (!this.rotationQuaternion) {
  47707. this.rotationQuaternion = new BABYLON.Quaternion();
  47708. }
  47709. rigCamera._cameraRigParams = {};
  47710. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47711. }
  47712. return rigCamera;
  47713. }
  47714. return null;
  47715. };
  47716. /**
  47717. * @hidden
  47718. */
  47719. TargetCamera.prototype._updateRigCameras = function () {
  47720. var camLeft = this._rigCameras[0];
  47721. var camRight = this._rigCameras[1];
  47722. switch (this.cameraRigMode) {
  47723. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47724. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47725. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47726. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47727. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47728. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47729. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47730. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47731. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47732. camLeft.setTarget(this.getTarget());
  47733. camRight.setTarget(this.getTarget());
  47734. break;
  47735. case BABYLON.Camera.RIG_MODE_VR:
  47736. if (camLeft.rotationQuaternion) {
  47737. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47738. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47739. }
  47740. else {
  47741. camLeft.rotation.copyFrom(this.rotation);
  47742. camRight.rotation.copyFrom(this.rotation);
  47743. }
  47744. camLeft.position.copyFrom(this.position);
  47745. camRight.position.copyFrom(this.position);
  47746. break;
  47747. }
  47748. _super.prototype._updateRigCameras.call(this);
  47749. };
  47750. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47751. if (!this._rigCamTransformMatrix) {
  47752. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47753. }
  47754. var target = this.getTarget();
  47755. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47756. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47757. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47758. };
  47759. /**
  47760. * Gets the current object class name.
  47761. * @return the class name
  47762. */
  47763. TargetCamera.prototype.getClassName = function () {
  47764. return "TargetCamera";
  47765. };
  47766. __decorate([
  47767. BABYLON.serializeAsVector3()
  47768. ], TargetCamera.prototype, "rotation", void 0);
  47769. __decorate([
  47770. BABYLON.serialize()
  47771. ], TargetCamera.prototype, "speed", void 0);
  47772. __decorate([
  47773. BABYLON.serializeAsMeshReference("lockedTargetId")
  47774. ], TargetCamera.prototype, "lockedTarget", void 0);
  47775. return TargetCamera;
  47776. }(BABYLON.Camera));
  47777. BABYLON.TargetCamera = TargetCamera;
  47778. })(BABYLON || (BABYLON = {}));
  47779. //# sourceMappingURL=babylon.targetCamera.js.map
  47780. var BABYLON;
  47781. (function (BABYLON) {
  47782. /**
  47783. * Manage the mouse inputs to control the movement of a free camera.
  47784. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47785. */
  47786. var FreeCameraMouseInput = /** @class */ (function () {
  47787. /**
  47788. * Manage the mouse inputs to control the movement of a free camera.
  47789. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47790. * @param touchEnabled Defines if touch is enabled or not
  47791. */
  47792. function FreeCameraMouseInput(
  47793. /**
  47794. * Define if touch is enabled in the mouse input
  47795. */
  47796. touchEnabled) {
  47797. if (touchEnabled === void 0) { touchEnabled = true; }
  47798. this.touchEnabled = touchEnabled;
  47799. /**
  47800. * Defines the buttons associated with the input to handle camera move.
  47801. */
  47802. this.buttons = [0, 1, 2];
  47803. /**
  47804. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  47805. */
  47806. this.angularSensibility = 2000.0;
  47807. this.previousPosition = null;
  47808. }
  47809. /**
  47810. * Attach the input controls to a specific dom element to get the input from.
  47811. * @param element Defines the element the controls should be listened from
  47812. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47813. */
  47814. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47815. var _this = this;
  47816. var engine = this.camera.getEngine();
  47817. if (!this._pointerInput) {
  47818. this._pointerInput = function (p, s) {
  47819. var evt = p.event;
  47820. if (engine.isInVRExclusivePointerMode) {
  47821. return;
  47822. }
  47823. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47824. return;
  47825. }
  47826. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47827. return;
  47828. }
  47829. var srcElement = (evt.srcElement || evt.target);
  47830. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47831. try {
  47832. srcElement.setPointerCapture(evt.pointerId);
  47833. }
  47834. catch (e) {
  47835. //Nothing to do with the error. Execution will continue.
  47836. }
  47837. _this.previousPosition = {
  47838. x: evt.clientX,
  47839. y: evt.clientY
  47840. };
  47841. if (!noPreventDefault) {
  47842. evt.preventDefault();
  47843. element.focus();
  47844. }
  47845. }
  47846. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47847. try {
  47848. srcElement.releasePointerCapture(evt.pointerId);
  47849. }
  47850. catch (e) {
  47851. //Nothing to do with the error.
  47852. }
  47853. _this.previousPosition = null;
  47854. if (!noPreventDefault) {
  47855. evt.preventDefault();
  47856. }
  47857. }
  47858. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47859. if (!_this.previousPosition || engine.isPointerLock) {
  47860. return;
  47861. }
  47862. var offsetX = evt.clientX - _this.previousPosition.x;
  47863. if (_this.camera.getScene().useRightHandedSystem)
  47864. offsetX *= -1;
  47865. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47866. offsetX *= -1;
  47867. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47868. var offsetY = evt.clientY - _this.previousPosition.y;
  47869. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47870. _this.previousPosition = {
  47871. x: evt.clientX,
  47872. y: evt.clientY
  47873. };
  47874. if (!noPreventDefault) {
  47875. evt.preventDefault();
  47876. }
  47877. }
  47878. };
  47879. }
  47880. this._onMouseMove = function (evt) {
  47881. if (!engine.isPointerLock) {
  47882. return;
  47883. }
  47884. if (engine.isInVRExclusivePointerMode) {
  47885. return;
  47886. }
  47887. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47888. if (_this.camera.getScene().useRightHandedSystem)
  47889. offsetX *= -1;
  47890. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47891. offsetX *= -1;
  47892. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47893. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47894. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47895. _this.previousPosition = null;
  47896. if (!noPreventDefault) {
  47897. evt.preventDefault();
  47898. }
  47899. };
  47900. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47901. element.addEventListener("mousemove", this._onMouseMove, false);
  47902. };
  47903. /**
  47904. * Detach the current controls from the specified dom element.
  47905. * @param element Defines the element to stop listening the inputs from
  47906. */
  47907. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47908. if (this._observer && element) {
  47909. this.camera.getScene().onPointerObservable.remove(this._observer);
  47910. if (this._onMouseMove) {
  47911. element.removeEventListener("mousemove", this._onMouseMove);
  47912. }
  47913. this._observer = null;
  47914. this._onMouseMove = null;
  47915. this.previousPosition = null;
  47916. }
  47917. };
  47918. /**
  47919. * Gets the class name of the current intput.
  47920. * @returns the class name
  47921. */
  47922. FreeCameraMouseInput.prototype.getClassName = function () {
  47923. return "FreeCameraMouseInput";
  47924. };
  47925. /**
  47926. * Get the friendly name associated with the input class.
  47927. * @returns the input friendly name
  47928. */
  47929. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47930. return "mouse";
  47931. };
  47932. __decorate([
  47933. BABYLON.serialize()
  47934. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47935. __decorate([
  47936. BABYLON.serialize()
  47937. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47938. return FreeCameraMouseInput;
  47939. }());
  47940. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47941. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47942. })(BABYLON || (BABYLON = {}));
  47943. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47944. var BABYLON;
  47945. (function (BABYLON) {
  47946. /**
  47947. * Manage the keyboard inputs to control the movement of a free camera.
  47948. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47949. */
  47950. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47951. function FreeCameraKeyboardMoveInput() {
  47952. /**
  47953. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47954. */
  47955. this.keysUp = [38];
  47956. /**
  47957. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47958. */
  47959. this.keysDown = [40];
  47960. /**
  47961. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47962. */
  47963. this.keysLeft = [37];
  47964. /**
  47965. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47966. */
  47967. this.keysRight = [39];
  47968. this._keys = new Array();
  47969. }
  47970. /**
  47971. * Attach the input controls to a specific dom element to get the input from.
  47972. * @param element Defines the element the controls should be listened from
  47973. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47974. */
  47975. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47976. var _this = this;
  47977. if (this._onCanvasBlurObserver) {
  47978. return;
  47979. }
  47980. this._scene = this.camera.getScene();
  47981. this._engine = this._scene.getEngine();
  47982. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47983. _this._keys = [];
  47984. });
  47985. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47986. var evt = info.event;
  47987. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47988. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47989. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47990. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47991. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47992. var index = _this._keys.indexOf(evt.keyCode);
  47993. if (index === -1) {
  47994. _this._keys.push(evt.keyCode);
  47995. }
  47996. if (!noPreventDefault) {
  47997. evt.preventDefault();
  47998. }
  47999. }
  48000. }
  48001. else {
  48002. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48003. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48004. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48005. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48006. var index = _this._keys.indexOf(evt.keyCode);
  48007. if (index >= 0) {
  48008. _this._keys.splice(index, 1);
  48009. }
  48010. if (!noPreventDefault) {
  48011. evt.preventDefault();
  48012. }
  48013. }
  48014. }
  48015. });
  48016. };
  48017. /**
  48018. * Detach the current controls from the specified dom element.
  48019. * @param element Defines the element to stop listening the inputs from
  48020. */
  48021. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48022. if (this._scene) {
  48023. if (this._onKeyboardObserver) {
  48024. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48025. }
  48026. if (this._onCanvasBlurObserver) {
  48027. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48028. }
  48029. this._onKeyboardObserver = null;
  48030. this._onCanvasBlurObserver = null;
  48031. }
  48032. this._keys = [];
  48033. };
  48034. /**
  48035. * Update the current camera state depending on the inputs that have been used this frame.
  48036. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48037. */
  48038. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48039. if (this._onKeyboardObserver) {
  48040. var camera = this.camera;
  48041. // Keyboard
  48042. for (var index = 0; index < this._keys.length; index++) {
  48043. var keyCode = this._keys[index];
  48044. var speed = camera._computeLocalCameraSpeed();
  48045. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48046. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48047. }
  48048. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48049. camera._localDirection.copyFromFloats(0, 0, speed);
  48050. }
  48051. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48052. camera._localDirection.copyFromFloats(speed, 0, 0);
  48053. }
  48054. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48055. camera._localDirection.copyFromFloats(0, 0, -speed);
  48056. }
  48057. if (camera.getScene().useRightHandedSystem) {
  48058. camera._localDirection.z *= -1;
  48059. }
  48060. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48061. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48062. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48063. }
  48064. }
  48065. };
  48066. /**
  48067. * Gets the class name of the current intput.
  48068. * @returns the class name
  48069. */
  48070. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48071. return "FreeCameraKeyboardMoveInput";
  48072. };
  48073. /** @hidden */
  48074. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48075. this._keys = [];
  48076. };
  48077. /**
  48078. * Get the friendly name associated with the input class.
  48079. * @returns the input friendly name
  48080. */
  48081. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48082. return "keyboard";
  48083. };
  48084. __decorate([
  48085. BABYLON.serialize()
  48086. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48087. __decorate([
  48088. BABYLON.serialize()
  48089. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48090. __decorate([
  48091. BABYLON.serialize()
  48092. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48093. __decorate([
  48094. BABYLON.serialize()
  48095. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48096. return FreeCameraKeyboardMoveInput;
  48097. }());
  48098. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48099. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48100. })(BABYLON || (BABYLON = {}));
  48101. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48102. var BABYLON;
  48103. (function (BABYLON) {
  48104. /**
  48105. * Default Inputs manager for the FreeCamera.
  48106. * It groups all the default supported inputs for ease of use.
  48107. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48108. */
  48109. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48110. __extends(FreeCameraInputsManager, _super);
  48111. /**
  48112. * Instantiates a new FreeCameraInputsManager.
  48113. * @param camera Defines the camera the inputs belong to
  48114. */
  48115. function FreeCameraInputsManager(camera) {
  48116. return _super.call(this, camera) || this;
  48117. }
  48118. /**
  48119. * Add keyboard input support to the input manager.
  48120. * @returns the current input manager
  48121. */
  48122. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48123. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48124. return this;
  48125. };
  48126. /**
  48127. * Add mouse input support to the input manager.
  48128. * @returns the current input manager
  48129. */
  48130. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48131. if (touchEnabled === void 0) { touchEnabled = true; }
  48132. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48133. return this;
  48134. };
  48135. /**
  48136. * Add orientation input support to the input manager.
  48137. * @returns the current input manager
  48138. */
  48139. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48140. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48141. return this;
  48142. };
  48143. /**
  48144. * Add touch input support to the input manager.
  48145. * @returns the current input manager
  48146. */
  48147. FreeCameraInputsManager.prototype.addTouch = function () {
  48148. this.add(new BABYLON.FreeCameraTouchInput());
  48149. return this;
  48150. };
  48151. /**
  48152. * Add virtual joystick input support to the input manager.
  48153. * @returns the current input manager
  48154. */
  48155. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48156. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48157. return this;
  48158. };
  48159. return FreeCameraInputsManager;
  48160. }(BABYLON.CameraInputsManager));
  48161. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48162. })(BABYLON || (BABYLON = {}));
  48163. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48164. var BABYLON;
  48165. (function (BABYLON) {
  48166. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48167. // Forcing to use the Universal camera
  48168. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48169. });
  48170. /**
  48171. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48172. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48173. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48174. */
  48175. var FreeCamera = /** @class */ (function (_super) {
  48176. __extends(FreeCamera, _super);
  48177. /**
  48178. * Instantiates a Free Camera.
  48179. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48180. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48181. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48182. * @param name Define the name of the camera in the scene
  48183. * @param position Define the start position of the camera in the scene
  48184. * @param scene Define the scene the camera belongs to
  48185. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48186. */
  48187. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48188. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48189. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48190. /**
  48191. * Define the collision ellipsoid of the camera.
  48192. * This is helpful to simulate a camera body like the player body around the camera
  48193. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48194. */
  48195. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48196. /**
  48197. * Define an offset for the position of the ellipsoid around the camera.
  48198. * This can be helpful to determine the center of the body near the gravity center of the body
  48199. * instead of its head.
  48200. */
  48201. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48202. /**
  48203. * Enable or disable collisions of the camera with the rest of the scene objects.
  48204. */
  48205. _this.checkCollisions = false;
  48206. /**
  48207. * Enable or disable gravity on the camera.
  48208. */
  48209. _this.applyGravity = false;
  48210. _this._needMoveForGravity = false;
  48211. _this._oldPosition = BABYLON.Vector3.Zero();
  48212. _this._diffPosition = BABYLON.Vector3.Zero();
  48213. _this._newPosition = BABYLON.Vector3.Zero();
  48214. // Collisions
  48215. _this._collisionMask = -1;
  48216. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48217. if (collidedMesh === void 0) { collidedMesh = null; }
  48218. //TODO move this to the collision coordinator!
  48219. if (_this.getScene().workerCollisions)
  48220. newPosition.multiplyInPlace(_this._collider._radius);
  48221. var updatePosition = function (newPos) {
  48222. _this._newPosition.copyFrom(newPos);
  48223. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48224. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48225. _this.position.addInPlace(_this._diffPosition);
  48226. if (_this.onCollide && collidedMesh) {
  48227. _this.onCollide(collidedMesh);
  48228. }
  48229. }
  48230. };
  48231. updatePosition(newPosition);
  48232. };
  48233. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48234. _this.inputs.addKeyboard().addMouse();
  48235. return _this;
  48236. }
  48237. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48238. /**
  48239. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48240. * Higher values reduce sensitivity.
  48241. */
  48242. get: function () {
  48243. var mouse = this.inputs.attached["mouse"];
  48244. if (mouse)
  48245. return mouse.angularSensibility;
  48246. return 0;
  48247. },
  48248. /**
  48249. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48250. * Higher values reduce sensitivity.
  48251. */
  48252. set: function (value) {
  48253. var mouse = this.inputs.attached["mouse"];
  48254. if (mouse)
  48255. mouse.angularSensibility = value;
  48256. },
  48257. enumerable: true,
  48258. configurable: true
  48259. });
  48260. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48261. /**
  48262. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48263. */
  48264. get: function () {
  48265. var keyboard = this.inputs.attached["keyboard"];
  48266. if (keyboard)
  48267. return keyboard.keysUp;
  48268. return [];
  48269. },
  48270. set: function (value) {
  48271. var keyboard = this.inputs.attached["keyboard"];
  48272. if (keyboard)
  48273. keyboard.keysUp = value;
  48274. },
  48275. enumerable: true,
  48276. configurable: true
  48277. });
  48278. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48279. /**
  48280. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48281. */
  48282. get: function () {
  48283. var keyboard = this.inputs.attached["keyboard"];
  48284. if (keyboard)
  48285. return keyboard.keysDown;
  48286. return [];
  48287. },
  48288. set: function (value) {
  48289. var keyboard = this.inputs.attached["keyboard"];
  48290. if (keyboard)
  48291. keyboard.keysDown = value;
  48292. },
  48293. enumerable: true,
  48294. configurable: true
  48295. });
  48296. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48297. /**
  48298. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48299. */
  48300. get: function () {
  48301. var keyboard = this.inputs.attached["keyboard"];
  48302. if (keyboard)
  48303. return keyboard.keysLeft;
  48304. return [];
  48305. },
  48306. set: function (value) {
  48307. var keyboard = this.inputs.attached["keyboard"];
  48308. if (keyboard)
  48309. keyboard.keysLeft = value;
  48310. },
  48311. enumerable: true,
  48312. configurable: true
  48313. });
  48314. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48315. /**
  48316. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48317. */
  48318. get: function () {
  48319. var keyboard = this.inputs.attached["keyboard"];
  48320. if (keyboard)
  48321. return keyboard.keysRight;
  48322. return [];
  48323. },
  48324. set: function (value) {
  48325. var keyboard = this.inputs.attached["keyboard"];
  48326. if (keyboard)
  48327. keyboard.keysRight = value;
  48328. },
  48329. enumerable: true,
  48330. configurable: true
  48331. });
  48332. /**
  48333. * Attached controls to the current camera.
  48334. * @param element Defines the element the controls should be listened from
  48335. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48336. */
  48337. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48338. this.inputs.attachElement(element, noPreventDefault);
  48339. };
  48340. /**
  48341. * Detach the current controls from the camera.
  48342. * The camera will stop reacting to inputs.
  48343. * @param element Defines the element to stop listening the inputs from
  48344. */
  48345. FreeCamera.prototype.detachControl = function (element) {
  48346. this.inputs.detachElement(element);
  48347. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48348. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48349. };
  48350. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48351. /**
  48352. * Define a collision mask to limit the list of object the camera can collide with
  48353. */
  48354. get: function () {
  48355. return this._collisionMask;
  48356. },
  48357. set: function (mask) {
  48358. this._collisionMask = !isNaN(mask) ? mask : -1;
  48359. },
  48360. enumerable: true,
  48361. configurable: true
  48362. });
  48363. /** @hidden */
  48364. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48365. var globalPosition;
  48366. if (this.parent) {
  48367. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48368. }
  48369. else {
  48370. globalPosition = this.position;
  48371. }
  48372. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48373. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48374. if (!this._collider) {
  48375. this._collider = new BABYLON.Collider();
  48376. }
  48377. this._collider._radius = this.ellipsoid;
  48378. this._collider.collisionMask = this._collisionMask;
  48379. //no need for clone, as long as gravity is not on.
  48380. var actualDisplacement = displacement;
  48381. //add gravity to the direction to prevent the dual-collision checking
  48382. if (this.applyGravity) {
  48383. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48384. actualDisplacement = displacement.add(this.getScene().gravity);
  48385. }
  48386. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48387. };
  48388. /** @hidden */
  48389. FreeCamera.prototype._checkInputs = function () {
  48390. if (!this._localDirection) {
  48391. this._localDirection = BABYLON.Vector3.Zero();
  48392. this._transformedDirection = BABYLON.Vector3.Zero();
  48393. }
  48394. this.inputs.checkInputs();
  48395. _super.prototype._checkInputs.call(this);
  48396. };
  48397. /** @hidden */
  48398. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48399. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48400. };
  48401. /** @hidden */
  48402. FreeCamera.prototype._updatePosition = function () {
  48403. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48404. this._collideWithWorld(this.cameraDirection);
  48405. }
  48406. else {
  48407. _super.prototype._updatePosition.call(this);
  48408. }
  48409. };
  48410. /**
  48411. * Destroy the camera and release the current resources hold by it.
  48412. */
  48413. FreeCamera.prototype.dispose = function () {
  48414. this.inputs.clear();
  48415. _super.prototype.dispose.call(this);
  48416. };
  48417. /**
  48418. * Gets the current object class name.
  48419. * @return the class name
  48420. */
  48421. FreeCamera.prototype.getClassName = function () {
  48422. return "FreeCamera";
  48423. };
  48424. __decorate([
  48425. BABYLON.serializeAsVector3()
  48426. ], FreeCamera.prototype, "ellipsoid", void 0);
  48427. __decorate([
  48428. BABYLON.serializeAsVector3()
  48429. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48430. __decorate([
  48431. BABYLON.serialize()
  48432. ], FreeCamera.prototype, "checkCollisions", void 0);
  48433. __decorate([
  48434. BABYLON.serialize()
  48435. ], FreeCamera.prototype, "applyGravity", void 0);
  48436. return FreeCamera;
  48437. }(BABYLON.TargetCamera));
  48438. BABYLON.FreeCamera = FreeCamera;
  48439. })(BABYLON || (BABYLON = {}));
  48440. //# sourceMappingURL=babylon.freeCamera.js.map
  48441. var BABYLON;
  48442. (function (BABYLON) {
  48443. /**
  48444. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48445. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48446. */
  48447. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48448. function ArcRotateCameraKeyboardMoveInput() {
  48449. /**
  48450. * Defines the list of key codes associated with the up action (increase alpha)
  48451. */
  48452. this.keysUp = [38];
  48453. /**
  48454. * Defines the list of key codes associated with the down action (decrease alpha)
  48455. */
  48456. this.keysDown = [40];
  48457. /**
  48458. * Defines the list of key codes associated with the left action (increase beta)
  48459. */
  48460. this.keysLeft = [37];
  48461. /**
  48462. * Defines the list of key codes associated with the right action (decrease beta)
  48463. */
  48464. this.keysRight = [39];
  48465. /**
  48466. * Defines the list of key codes associated with the reset action.
  48467. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48468. */
  48469. this.keysReset = [220];
  48470. /**
  48471. * Defines the panning sensibility of the inputs.
  48472. * (How fast is the camera paning)
  48473. */
  48474. this.panningSensibility = 50.0;
  48475. /**
  48476. * Defines the zooming sensibility of the inputs.
  48477. * (How fast is the camera zooming)
  48478. */
  48479. this.zoomingSensibility = 25.0;
  48480. /**
  48481. * Defines wether maintaining the alt key down switch the movement mode from
  48482. * orientation to zoom.
  48483. */
  48484. this.useAltToZoom = true;
  48485. /**
  48486. * Rotation speed of the camera
  48487. */
  48488. this.angularSpeed = 0.01;
  48489. this._keys = new Array();
  48490. }
  48491. /**
  48492. * Attach the input controls to a specific dom element to get the input from.
  48493. * @param element Defines the element the controls should be listened from
  48494. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48495. */
  48496. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48497. var _this = this;
  48498. if (this._onCanvasBlurObserver) {
  48499. return;
  48500. }
  48501. this._scene = this.camera.getScene();
  48502. this._engine = this._scene.getEngine();
  48503. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48504. _this._keys = [];
  48505. });
  48506. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48507. var evt = info.event;
  48508. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48509. _this._ctrlPressed = evt.ctrlKey;
  48510. _this._altPressed = evt.altKey;
  48511. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48512. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48513. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48514. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48515. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48516. var index = _this._keys.indexOf(evt.keyCode);
  48517. if (index === -1) {
  48518. _this._keys.push(evt.keyCode);
  48519. }
  48520. if (evt.preventDefault) {
  48521. if (!noPreventDefault) {
  48522. evt.preventDefault();
  48523. }
  48524. }
  48525. }
  48526. }
  48527. else {
  48528. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48529. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48530. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48531. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48532. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48533. var index = _this._keys.indexOf(evt.keyCode);
  48534. if (index >= 0) {
  48535. _this._keys.splice(index, 1);
  48536. }
  48537. if (evt.preventDefault) {
  48538. if (!noPreventDefault) {
  48539. evt.preventDefault();
  48540. }
  48541. }
  48542. }
  48543. }
  48544. });
  48545. };
  48546. /**
  48547. * Detach the current controls from the specified dom element.
  48548. * @param element Defines the element to stop listening the inputs from
  48549. */
  48550. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48551. if (this._scene) {
  48552. if (this._onKeyboardObserver) {
  48553. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48554. }
  48555. if (this._onCanvasBlurObserver) {
  48556. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48557. }
  48558. this._onKeyboardObserver = null;
  48559. this._onCanvasBlurObserver = null;
  48560. }
  48561. this._keys = [];
  48562. };
  48563. /**
  48564. * Update the current camera state depending on the inputs that have been used this frame.
  48565. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48566. */
  48567. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48568. if (this._onKeyboardObserver) {
  48569. var camera = this.camera;
  48570. for (var index = 0; index < this._keys.length; index++) {
  48571. var keyCode = this._keys[index];
  48572. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48573. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48574. camera.inertialPanningX -= 1 / this.panningSensibility;
  48575. }
  48576. else {
  48577. camera.inertialAlphaOffset -= this.angularSpeed;
  48578. }
  48579. }
  48580. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48581. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48582. camera.inertialPanningY += 1 / this.panningSensibility;
  48583. }
  48584. else if (this._altPressed && this.useAltToZoom) {
  48585. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48586. }
  48587. else {
  48588. camera.inertialBetaOffset -= this.angularSpeed;
  48589. }
  48590. }
  48591. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48592. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48593. camera.inertialPanningX += 1 / this.panningSensibility;
  48594. }
  48595. else {
  48596. camera.inertialAlphaOffset += this.angularSpeed;
  48597. }
  48598. }
  48599. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48600. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48601. camera.inertialPanningY -= 1 / this.panningSensibility;
  48602. }
  48603. else if (this._altPressed && this.useAltToZoom) {
  48604. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48605. }
  48606. else {
  48607. camera.inertialBetaOffset += this.angularSpeed;
  48608. }
  48609. }
  48610. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48611. if (camera.useInputToRestoreState) {
  48612. camera.restoreState();
  48613. }
  48614. }
  48615. }
  48616. }
  48617. };
  48618. /**
  48619. * Gets the class name of the current intput.
  48620. * @returns the class name
  48621. */
  48622. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48623. return "ArcRotateCameraKeyboardMoveInput";
  48624. };
  48625. /**
  48626. * Get the friendly name associated with the input class.
  48627. * @returns the input friendly name
  48628. */
  48629. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48630. return "keyboard";
  48631. };
  48632. __decorate([
  48633. BABYLON.serialize()
  48634. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48635. __decorate([
  48636. BABYLON.serialize()
  48637. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48638. __decorate([
  48639. BABYLON.serialize()
  48640. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48641. __decorate([
  48642. BABYLON.serialize()
  48643. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48644. __decorate([
  48645. BABYLON.serialize()
  48646. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48647. __decorate([
  48648. BABYLON.serialize()
  48649. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48650. __decorate([
  48651. BABYLON.serialize()
  48652. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48653. __decorate([
  48654. BABYLON.serialize()
  48655. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48656. __decorate([
  48657. BABYLON.serialize()
  48658. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  48659. return ArcRotateCameraKeyboardMoveInput;
  48660. }());
  48661. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48662. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48663. })(BABYLON || (BABYLON = {}));
  48664. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48665. var BABYLON;
  48666. (function (BABYLON) {
  48667. /**
  48668. * Manage the mouse wheel inputs to control an arc rotate camera.
  48669. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48670. */
  48671. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48672. function ArcRotateCameraMouseWheelInput() {
  48673. /**
  48674. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48675. */
  48676. this.wheelPrecision = 3.0;
  48677. /**
  48678. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48679. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48680. */
  48681. this.wheelDeltaPercentage = 0;
  48682. }
  48683. /**
  48684. * Attach the input controls to a specific dom element to get the input from.
  48685. * @param element Defines the element the controls should be listened from
  48686. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48687. */
  48688. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48689. var _this = this;
  48690. this._wheel = function (p, s) {
  48691. //sanity check - this should be a PointerWheel event.
  48692. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48693. return;
  48694. var event = p.event;
  48695. var delta = 0;
  48696. if (event.wheelDelta) {
  48697. if (_this.wheelDeltaPercentage) {
  48698. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48699. if (event.wheelDelta > 0) {
  48700. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48701. }
  48702. else {
  48703. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48704. }
  48705. }
  48706. else {
  48707. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48708. }
  48709. }
  48710. else if (event.detail) {
  48711. delta = -event.detail / _this.wheelPrecision;
  48712. }
  48713. if (delta)
  48714. _this.camera.inertialRadiusOffset += delta;
  48715. if (event.preventDefault) {
  48716. if (!noPreventDefault) {
  48717. event.preventDefault();
  48718. }
  48719. }
  48720. };
  48721. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48722. };
  48723. /**
  48724. * Detach the current controls from the specified dom element.
  48725. * @param element Defines the element to stop listening the inputs from
  48726. */
  48727. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48728. if (this._observer && element) {
  48729. this.camera.getScene().onPointerObservable.remove(this._observer);
  48730. this._observer = null;
  48731. this._wheel = null;
  48732. }
  48733. };
  48734. /**
  48735. * Gets the class name of the current intput.
  48736. * @returns the class name
  48737. */
  48738. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48739. return "ArcRotateCameraMouseWheelInput";
  48740. };
  48741. /**
  48742. * Get the friendly name associated with the input class.
  48743. * @returns the input friendly name
  48744. */
  48745. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48746. return "mousewheel";
  48747. };
  48748. __decorate([
  48749. BABYLON.serialize()
  48750. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48751. __decorate([
  48752. BABYLON.serialize()
  48753. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48754. return ArcRotateCameraMouseWheelInput;
  48755. }());
  48756. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48757. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48758. })(BABYLON || (BABYLON = {}));
  48759. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48760. var BABYLON;
  48761. (function (BABYLON) {
  48762. /**
  48763. * Manage the pointers inputs to control an arc rotate camera.
  48764. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48765. */
  48766. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48767. function ArcRotateCameraPointersInput() {
  48768. /**
  48769. * Defines the buttons associated with the input to handle camera move.
  48770. */
  48771. this.buttons = [0, 1, 2];
  48772. /**
  48773. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48774. */
  48775. this.angularSensibilityX = 1000.0;
  48776. /**
  48777. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48778. */
  48779. this.angularSensibilityY = 1000.0;
  48780. /**
  48781. * Defines the pointer pinch precision or how fast is the camera zooming.
  48782. */
  48783. this.pinchPrecision = 12.0;
  48784. /**
  48785. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48786. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48787. */
  48788. this.pinchDeltaPercentage = 0;
  48789. /**
  48790. * Defines the pointer panning sensibility or how fast is the camera moving.
  48791. */
  48792. this.panningSensibility = 1000.0;
  48793. /**
  48794. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  48795. */
  48796. this.multiTouchPanning = true;
  48797. /**
  48798. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  48799. */
  48800. this.multiTouchPanAndZoom = true;
  48801. /**
  48802. * Revers pinch action direction.
  48803. */
  48804. this.pinchInwards = true;
  48805. this._isPanClick = false;
  48806. }
  48807. /**
  48808. * Attach the input controls to a specific dom element to get the input from.
  48809. * @param element Defines the element the controls should be listened from
  48810. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48811. */
  48812. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48813. var _this = this;
  48814. var engine = this.camera.getEngine();
  48815. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48816. var pointA = null;
  48817. var pointB = null;
  48818. var previousPinchSquaredDistance = 0;
  48819. var initialDistance = 0;
  48820. var twoFingerActivityCount = 0;
  48821. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48822. this._pointerInput = function (p, s) {
  48823. var evt = p.event;
  48824. var isTouch = p.event.pointerType === "touch";
  48825. if (engine.isInVRExclusivePointerMode) {
  48826. return;
  48827. }
  48828. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48829. return;
  48830. }
  48831. var srcElement = (evt.srcElement || evt.target);
  48832. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48833. try {
  48834. srcElement.setPointerCapture(evt.pointerId);
  48835. }
  48836. catch (e) {
  48837. //Nothing to do with the error. Execution will continue.
  48838. }
  48839. // Manage panning with pan button click
  48840. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48841. // manage pointers
  48842. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48843. if (pointA === null) {
  48844. pointA = cacheSoloPointer;
  48845. }
  48846. else if (pointB === null) {
  48847. pointB = cacheSoloPointer;
  48848. }
  48849. if (!noPreventDefault) {
  48850. evt.preventDefault();
  48851. element.focus();
  48852. }
  48853. }
  48854. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48855. if (_this.camera.useInputToRestoreState) {
  48856. _this.camera.restoreState();
  48857. }
  48858. }
  48859. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48860. try {
  48861. srcElement.releasePointerCapture(evt.pointerId);
  48862. }
  48863. catch (e) {
  48864. //Nothing to do with the error.
  48865. }
  48866. cacheSoloPointer = null;
  48867. previousPinchSquaredDistance = 0;
  48868. previousMultiTouchPanPosition.isPaning = false;
  48869. previousMultiTouchPanPosition.isPinching = false;
  48870. twoFingerActivityCount = 0;
  48871. initialDistance = 0;
  48872. if (!isTouch) {
  48873. pointB = null; // Mouse and pen are mono pointer
  48874. }
  48875. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48876. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48877. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48878. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48879. if (engine._badOS) {
  48880. pointA = pointB = null;
  48881. }
  48882. else {
  48883. //only remove the impacted pointer in case of multitouch allowing on most
  48884. //platforms switching from rotate to zoom and pan seamlessly.
  48885. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48886. pointA = pointB;
  48887. pointB = null;
  48888. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48889. }
  48890. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48891. pointB = null;
  48892. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48893. }
  48894. else {
  48895. pointA = pointB = null;
  48896. }
  48897. }
  48898. if (!noPreventDefault) {
  48899. evt.preventDefault();
  48900. }
  48901. }
  48902. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48903. if (!noPreventDefault) {
  48904. evt.preventDefault();
  48905. }
  48906. // One button down
  48907. if (pointA && pointB === null && cacheSoloPointer) {
  48908. if (_this.panningSensibility !== 0 &&
  48909. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48910. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48911. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48912. }
  48913. else {
  48914. var offsetX = evt.clientX - cacheSoloPointer.x;
  48915. var offsetY = evt.clientY - cacheSoloPointer.y;
  48916. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48917. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48918. }
  48919. cacheSoloPointer.x = evt.clientX;
  48920. cacheSoloPointer.y = evt.clientY;
  48921. }
  48922. // Two buttons down: pinch/pan
  48923. else if (pointA && pointB) {
  48924. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48925. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48926. ed.x = evt.clientX;
  48927. ed.y = evt.clientY;
  48928. var direction = _this.pinchInwards ? 1 : -1;
  48929. var distX = pointA.x - pointB.x;
  48930. var distY = pointA.y - pointB.y;
  48931. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48932. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48933. if (previousPinchSquaredDistance === 0) {
  48934. initialDistance = pinchDistance;
  48935. previousPinchSquaredDistance = pinchSquaredDistance;
  48936. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48937. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48938. return;
  48939. }
  48940. if (_this.multiTouchPanAndZoom) {
  48941. if (_this.pinchDeltaPercentage) {
  48942. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48943. }
  48944. else {
  48945. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48946. (_this.pinchPrecision *
  48947. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48948. direction);
  48949. }
  48950. if (_this.panningSensibility !== 0) {
  48951. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48952. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48953. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48954. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48955. previousMultiTouchPanPosition.x = pointersCenterX;
  48956. previousMultiTouchPanPosition.y = pointersCenterY;
  48957. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48958. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48959. }
  48960. }
  48961. else {
  48962. twoFingerActivityCount++;
  48963. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48964. if (_this.pinchDeltaPercentage) {
  48965. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48966. }
  48967. else {
  48968. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48969. (_this.pinchPrecision *
  48970. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48971. direction);
  48972. }
  48973. previousMultiTouchPanPosition.isPaning = false;
  48974. previousMultiTouchPanPosition.isPinching = true;
  48975. }
  48976. else {
  48977. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48978. if (!previousMultiTouchPanPosition.isPaning) {
  48979. previousMultiTouchPanPosition.isPaning = true;
  48980. previousMultiTouchPanPosition.isPinching = false;
  48981. previousMultiTouchPanPosition.x = ed.x;
  48982. previousMultiTouchPanPosition.y = ed.y;
  48983. return;
  48984. }
  48985. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48986. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48987. }
  48988. }
  48989. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48990. previousMultiTouchPanPosition.x = ed.x;
  48991. previousMultiTouchPanPosition.y = ed.y;
  48992. }
  48993. }
  48994. previousPinchSquaredDistance = pinchSquaredDistance;
  48995. }
  48996. }
  48997. };
  48998. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48999. this._onContextMenu = function (evt) {
  49000. evt.preventDefault();
  49001. };
  49002. if (!this.camera._useCtrlForPanning) {
  49003. element.addEventListener("contextmenu", this._onContextMenu, false);
  49004. }
  49005. this._onLostFocus = function () {
  49006. //this._keys = [];
  49007. pointA = pointB = null;
  49008. previousPinchSquaredDistance = 0;
  49009. previousMultiTouchPanPosition.isPaning = false;
  49010. previousMultiTouchPanPosition.isPinching = false;
  49011. twoFingerActivityCount = 0;
  49012. cacheSoloPointer = null;
  49013. initialDistance = 0;
  49014. };
  49015. this._onMouseMove = function (evt) {
  49016. if (!engine.isPointerLock) {
  49017. return;
  49018. }
  49019. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49020. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49021. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49022. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49023. if (!noPreventDefault) {
  49024. evt.preventDefault();
  49025. }
  49026. };
  49027. this._onGestureStart = function (e) {
  49028. if (window.MSGesture === undefined) {
  49029. return;
  49030. }
  49031. if (!_this._MSGestureHandler) {
  49032. _this._MSGestureHandler = new MSGesture();
  49033. _this._MSGestureHandler.target = element;
  49034. }
  49035. _this._MSGestureHandler.addPointer(e.pointerId);
  49036. };
  49037. this._onGesture = function (e) {
  49038. _this.camera.radius *= e.scale;
  49039. if (e.preventDefault) {
  49040. if (!noPreventDefault) {
  49041. e.stopPropagation();
  49042. e.preventDefault();
  49043. }
  49044. }
  49045. };
  49046. element.addEventListener("mousemove", this._onMouseMove, false);
  49047. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49048. element.addEventListener("MSGestureChange", this._onGesture, false);
  49049. BABYLON.Tools.RegisterTopRootEvents([
  49050. { name: "blur", handler: this._onLostFocus }
  49051. ]);
  49052. };
  49053. /**
  49054. * Detach the current controls from the specified dom element.
  49055. * @param element Defines the element to stop listening the inputs from
  49056. */
  49057. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49058. if (this._onLostFocus) {
  49059. BABYLON.Tools.UnregisterTopRootEvents([
  49060. { name: "blur", handler: this._onLostFocus }
  49061. ]);
  49062. }
  49063. if (element && this._observer) {
  49064. this.camera.getScene().onPointerObservable.remove(this._observer);
  49065. this._observer = null;
  49066. if (this._onContextMenu) {
  49067. element.removeEventListener("contextmenu", this._onContextMenu);
  49068. }
  49069. if (this._onMouseMove) {
  49070. element.removeEventListener("mousemove", this._onMouseMove);
  49071. }
  49072. if (this._onGestureStart) {
  49073. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49074. }
  49075. if (this._onGesture) {
  49076. element.removeEventListener("MSGestureChange", this._onGesture);
  49077. }
  49078. this._isPanClick = false;
  49079. this.pinchInwards = true;
  49080. this._onMouseMove = null;
  49081. this._onGestureStart = null;
  49082. this._onGesture = null;
  49083. this._MSGestureHandler = null;
  49084. this._onLostFocus = null;
  49085. this._onContextMenu = null;
  49086. }
  49087. };
  49088. /**
  49089. * Gets the class name of the current intput.
  49090. * @returns the class name
  49091. */
  49092. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49093. return "ArcRotateCameraPointersInput";
  49094. };
  49095. /**
  49096. * Get the friendly name associated with the input class.
  49097. * @returns the input friendly name
  49098. */
  49099. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49100. return "pointers";
  49101. };
  49102. __decorate([
  49103. BABYLON.serialize()
  49104. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49105. __decorate([
  49106. BABYLON.serialize()
  49107. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49108. __decorate([
  49109. BABYLON.serialize()
  49110. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49111. __decorate([
  49112. BABYLON.serialize()
  49113. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49114. __decorate([
  49115. BABYLON.serialize()
  49116. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49117. __decorate([
  49118. BABYLON.serialize()
  49119. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49120. __decorate([
  49121. BABYLON.serialize()
  49122. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49123. __decorate([
  49124. BABYLON.serialize()
  49125. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49126. return ArcRotateCameraPointersInput;
  49127. }());
  49128. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49129. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49130. })(BABYLON || (BABYLON = {}));
  49131. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49132. var BABYLON;
  49133. (function (BABYLON) {
  49134. /**
  49135. * Default Inputs manager for the ArcRotateCamera.
  49136. * It groups all the default supported inputs for ease of use.
  49137. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49138. */
  49139. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49140. __extends(ArcRotateCameraInputsManager, _super);
  49141. /**
  49142. * Instantiates a new ArcRotateCameraInputsManager.
  49143. * @param camera Defines the camera the inputs belong to
  49144. */
  49145. function ArcRotateCameraInputsManager(camera) {
  49146. return _super.call(this, camera) || this;
  49147. }
  49148. /**
  49149. * Add mouse wheel input support to the input manager.
  49150. * @returns the current input manager
  49151. */
  49152. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49153. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49154. return this;
  49155. };
  49156. /**
  49157. * Add pointers input support to the input manager.
  49158. * @returns the current input manager
  49159. */
  49160. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49161. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49162. return this;
  49163. };
  49164. /**
  49165. * Add keyboard input support to the input manager.
  49166. * @returns the current input manager
  49167. */
  49168. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49169. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49170. return this;
  49171. };
  49172. /**
  49173. * Add orientation input support to the input manager.
  49174. * @returns the current input manager
  49175. */
  49176. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49177. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49178. return this;
  49179. };
  49180. return ArcRotateCameraInputsManager;
  49181. }(BABYLON.CameraInputsManager));
  49182. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49183. })(BABYLON || (BABYLON = {}));
  49184. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49185. var BABYLON;
  49186. (function (BABYLON) {
  49187. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49188. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49189. });
  49190. /**
  49191. * This represents an orbital type of camera.
  49192. *
  49193. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  49194. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  49195. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49196. */
  49197. var ArcRotateCamera = /** @class */ (function (_super) {
  49198. __extends(ArcRotateCamera, _super);
  49199. /**
  49200. * Instantiates a new ArcRotateCamera in a given scene
  49201. * @param name Defines the name of the camera
  49202. * @param alpha Defines the camera rotation along the logitudinal axis
  49203. * @param beta Defines the camera rotation along the latitudinal axis
  49204. * @param radius Defines the camera distance from its target
  49205. * @param target Defines the camera target
  49206. * @param scene Defines the scene the camera belongs to
  49207. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49208. */
  49209. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49210. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49211. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49212. /**
  49213. * Current inertia value on the longitudinal axis.
  49214. * The bigger this number the longer it will take for the camera to stop.
  49215. */
  49216. _this.inertialAlphaOffset = 0;
  49217. /**
  49218. * Current inertia value on the latitudinal axis.
  49219. * The bigger this number the longer it will take for the camera to stop.
  49220. */
  49221. _this.inertialBetaOffset = 0;
  49222. /**
  49223. * Current inertia value on the radius axis.
  49224. * The bigger this number the longer it will take for the camera to stop.
  49225. */
  49226. _this.inertialRadiusOffset = 0;
  49227. /**
  49228. * Minimum allowed angle on the longitudinal axis.
  49229. * This can help limiting how the Camera is able to move in the scene.
  49230. */
  49231. _this.lowerAlphaLimit = null;
  49232. /**
  49233. * Maximum allowed angle on the longitudinal axis.
  49234. * This can help limiting how the Camera is able to move in the scene.
  49235. */
  49236. _this.upperAlphaLimit = null;
  49237. /**
  49238. * Minimum allowed angle on the latitudinal axis.
  49239. * This can help limiting how the Camera is able to move in the scene.
  49240. */
  49241. _this.lowerBetaLimit = 0.01;
  49242. /**
  49243. * Maximum allowed angle on the latitudinal axis.
  49244. * This can help limiting how the Camera is able to move in the scene.
  49245. */
  49246. _this.upperBetaLimit = Math.PI;
  49247. /**
  49248. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49249. * This can help limiting how the Camera is able to move in the scene.
  49250. */
  49251. _this.lowerRadiusLimit = null;
  49252. /**
  49253. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49254. * This can help limiting how the Camera is able to move in the scene.
  49255. */
  49256. _this.upperRadiusLimit = null;
  49257. /**
  49258. * Defines the current inertia value used during panning of the camera along the X axis.
  49259. */
  49260. _this.inertialPanningX = 0;
  49261. /**
  49262. * Defines the current inertia value used during panning of the camera along the Y axis.
  49263. */
  49264. _this.inertialPanningY = 0;
  49265. /**
  49266. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49267. * Basically if your fingers moves away from more than this distance you will be considered
  49268. * in pinch mode.
  49269. */
  49270. _this.pinchToPanMaxDistance = 20;
  49271. /**
  49272. * Defines the maximum distance the camera can pan.
  49273. * This could help keeping the cammera always in your scene.
  49274. */
  49275. _this.panningDistanceLimit = null;
  49276. /**
  49277. * Defines the target of the camera before paning.
  49278. */
  49279. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49280. /**
  49281. * Defines the value of the inertia used during panning.
  49282. * 0 would mean stop inertia and one would mean no decelleration at all.
  49283. */
  49284. _this.panningInertia = 0.9;
  49285. //-- end properties for backward compatibility for inputs
  49286. /**
  49287. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49288. */
  49289. _this.zoomOnFactor = 1;
  49290. /**
  49291. * Defines a screen offset for the camera position.
  49292. */
  49293. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49294. /**
  49295. * Allows the camera to be completely reversed.
  49296. * If false the camera can not arrive upside down.
  49297. */
  49298. _this.allowUpsideDown = true;
  49299. /**
  49300. * Define if double tap/click is used to restore the previously saved state of the camera.
  49301. */
  49302. _this.useInputToRestoreState = true;
  49303. /** @hidden */
  49304. _this._viewMatrix = new BABYLON.Matrix();
  49305. /**
  49306. * Defines the allowed panning axis.
  49307. */
  49308. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49309. /**
  49310. * Observable triggered when the mesh target has been changed on the camera.
  49311. */
  49312. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49313. /**
  49314. * Defines whether the camera should check collision with the objects oh the scene.
  49315. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49316. */
  49317. _this.checkCollisions = false;
  49318. /**
  49319. * Defines the collision radius of the camera.
  49320. * This simulates a sphere around the camera.
  49321. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49322. */
  49323. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49324. _this._previousPosition = BABYLON.Vector3.Zero();
  49325. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49326. _this._newPosition = BABYLON.Vector3.Zero();
  49327. _this._computationVector = BABYLON.Vector3.Zero();
  49328. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49329. if (collidedMesh === void 0) { collidedMesh = null; }
  49330. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49331. newPosition.multiplyInPlace(_this._collider._radius);
  49332. }
  49333. if (!collidedMesh) {
  49334. _this._previousPosition.copyFrom(_this.position);
  49335. }
  49336. else {
  49337. _this.setPosition(newPosition);
  49338. if (_this.onCollide) {
  49339. _this.onCollide(collidedMesh);
  49340. }
  49341. }
  49342. // Recompute because of constraints
  49343. var cosa = Math.cos(_this.alpha);
  49344. var sina = Math.sin(_this.alpha);
  49345. var cosb = Math.cos(_this.beta);
  49346. var sinb = Math.sin(_this.beta);
  49347. if (sinb === 0) {
  49348. sinb = 0.0001;
  49349. }
  49350. var target = _this._getTargetPosition();
  49351. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49352. target.addToRef(_this._computationVector, _this._newPosition);
  49353. _this.position.copyFrom(_this._newPosition);
  49354. var up = _this.upVector;
  49355. if (_this.allowUpsideDown && _this.beta < 0) {
  49356. up = up.clone();
  49357. up = up.negate();
  49358. }
  49359. _this._computeViewMatrix(_this.position, target, up);
  49360. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49361. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49362. _this._collisionTriggered = false;
  49363. };
  49364. _this._target = BABYLON.Vector3.Zero();
  49365. if (target) {
  49366. _this.setTarget(target);
  49367. }
  49368. _this.alpha = alpha;
  49369. _this.beta = beta;
  49370. _this.radius = radius;
  49371. _this.getViewMatrix();
  49372. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49373. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49374. return _this;
  49375. }
  49376. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49377. /**
  49378. * Defines the target point of the camera.
  49379. * The camera looks towards it form the radius distance.
  49380. */
  49381. get: function () {
  49382. return this._target;
  49383. },
  49384. set: function (value) {
  49385. this.setTarget(value);
  49386. },
  49387. enumerable: true,
  49388. configurable: true
  49389. });
  49390. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49391. //-- begin properties for backward compatibility for inputs
  49392. /**
  49393. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49394. */
  49395. get: function () {
  49396. var pointers = this.inputs.attached["pointers"];
  49397. if (pointers)
  49398. return pointers.angularSensibilityX;
  49399. return 0;
  49400. },
  49401. set: function (value) {
  49402. var pointers = this.inputs.attached["pointers"];
  49403. if (pointers) {
  49404. pointers.angularSensibilityX = value;
  49405. }
  49406. },
  49407. enumerable: true,
  49408. configurable: true
  49409. });
  49410. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49411. /**
  49412. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49413. */
  49414. get: function () {
  49415. var pointers = this.inputs.attached["pointers"];
  49416. if (pointers)
  49417. return pointers.angularSensibilityY;
  49418. return 0;
  49419. },
  49420. set: function (value) {
  49421. var pointers = this.inputs.attached["pointers"];
  49422. if (pointers) {
  49423. pointers.angularSensibilityY = value;
  49424. }
  49425. },
  49426. enumerable: true,
  49427. configurable: true
  49428. });
  49429. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49430. /**
  49431. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49432. */
  49433. get: function () {
  49434. var pointers = this.inputs.attached["pointers"];
  49435. if (pointers)
  49436. return pointers.pinchPrecision;
  49437. return 0;
  49438. },
  49439. set: function (value) {
  49440. var pointers = this.inputs.attached["pointers"];
  49441. if (pointers) {
  49442. pointers.pinchPrecision = value;
  49443. }
  49444. },
  49445. enumerable: true,
  49446. configurable: true
  49447. });
  49448. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49449. /**
  49450. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49451. * It will be used instead of pinchDeltaPrecision if different from 0.
  49452. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49453. */
  49454. get: function () {
  49455. var pointers = this.inputs.attached["pointers"];
  49456. if (pointers)
  49457. return pointers.pinchDeltaPercentage;
  49458. return 0;
  49459. },
  49460. set: function (value) {
  49461. var pointers = this.inputs.attached["pointers"];
  49462. if (pointers) {
  49463. pointers.pinchDeltaPercentage = value;
  49464. }
  49465. },
  49466. enumerable: true,
  49467. configurable: true
  49468. });
  49469. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49470. /**
  49471. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49472. */
  49473. get: function () {
  49474. var pointers = this.inputs.attached["pointers"];
  49475. if (pointers)
  49476. return pointers.panningSensibility;
  49477. return 0;
  49478. },
  49479. set: function (value) {
  49480. var pointers = this.inputs.attached["pointers"];
  49481. if (pointers) {
  49482. pointers.panningSensibility = value;
  49483. }
  49484. },
  49485. enumerable: true,
  49486. configurable: true
  49487. });
  49488. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49489. /**
  49490. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49491. */
  49492. get: function () {
  49493. var keyboard = this.inputs.attached["keyboard"];
  49494. if (keyboard)
  49495. return keyboard.keysUp;
  49496. return [];
  49497. },
  49498. set: function (value) {
  49499. var keyboard = this.inputs.attached["keyboard"];
  49500. if (keyboard)
  49501. keyboard.keysUp = value;
  49502. },
  49503. enumerable: true,
  49504. configurable: true
  49505. });
  49506. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49507. /**
  49508. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49509. */
  49510. get: function () {
  49511. var keyboard = this.inputs.attached["keyboard"];
  49512. if (keyboard)
  49513. return keyboard.keysDown;
  49514. return [];
  49515. },
  49516. set: function (value) {
  49517. var keyboard = this.inputs.attached["keyboard"];
  49518. if (keyboard)
  49519. keyboard.keysDown = value;
  49520. },
  49521. enumerable: true,
  49522. configurable: true
  49523. });
  49524. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49525. /**
  49526. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  49527. */
  49528. get: function () {
  49529. var keyboard = this.inputs.attached["keyboard"];
  49530. if (keyboard)
  49531. return keyboard.keysLeft;
  49532. return [];
  49533. },
  49534. set: function (value) {
  49535. var keyboard = this.inputs.attached["keyboard"];
  49536. if (keyboard)
  49537. keyboard.keysLeft = value;
  49538. },
  49539. enumerable: true,
  49540. configurable: true
  49541. });
  49542. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49543. /**
  49544. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  49545. */
  49546. get: function () {
  49547. var keyboard = this.inputs.attached["keyboard"];
  49548. if (keyboard)
  49549. return keyboard.keysRight;
  49550. return [];
  49551. },
  49552. set: function (value) {
  49553. var keyboard = this.inputs.attached["keyboard"];
  49554. if (keyboard)
  49555. keyboard.keysRight = value;
  49556. },
  49557. enumerable: true,
  49558. configurable: true
  49559. });
  49560. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49561. /**
  49562. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49563. */
  49564. get: function () {
  49565. var mousewheel = this.inputs.attached["mousewheel"];
  49566. if (mousewheel)
  49567. return mousewheel.wheelPrecision;
  49568. return 0;
  49569. },
  49570. set: function (value) {
  49571. var mousewheel = this.inputs.attached["mousewheel"];
  49572. if (mousewheel)
  49573. mousewheel.wheelPrecision = value;
  49574. },
  49575. enumerable: true,
  49576. configurable: true
  49577. });
  49578. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49579. /**
  49580. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  49581. * It will be used instead of pinchDeltaPrecision if different from 0.
  49582. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49583. */
  49584. get: function () {
  49585. var mousewheel = this.inputs.attached["mousewheel"];
  49586. if (mousewheel)
  49587. return mousewheel.wheelDeltaPercentage;
  49588. return 0;
  49589. },
  49590. set: function (value) {
  49591. var mousewheel = this.inputs.attached["mousewheel"];
  49592. if (mousewheel)
  49593. mousewheel.wheelDeltaPercentage = value;
  49594. },
  49595. enumerable: true,
  49596. configurable: true
  49597. });
  49598. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49599. /**
  49600. * Gets the bouncing behavior of the camera if it has been enabled.
  49601. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49602. */
  49603. get: function () {
  49604. return this._bouncingBehavior;
  49605. },
  49606. enumerable: true,
  49607. configurable: true
  49608. });
  49609. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49610. /**
  49611. * Defines if the bouncing behavior of the camera is enabled on the camera.
  49612. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49613. */
  49614. get: function () {
  49615. return this._bouncingBehavior != null;
  49616. },
  49617. set: function (value) {
  49618. if (value === this.useBouncingBehavior) {
  49619. return;
  49620. }
  49621. if (value) {
  49622. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49623. this.addBehavior(this._bouncingBehavior);
  49624. }
  49625. else if (this._bouncingBehavior) {
  49626. this.removeBehavior(this._bouncingBehavior);
  49627. this._bouncingBehavior = null;
  49628. }
  49629. },
  49630. enumerable: true,
  49631. configurable: true
  49632. });
  49633. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49634. /**
  49635. * Gets the framing behavior of the camera if it has been enabled.
  49636. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49637. */
  49638. get: function () {
  49639. return this._framingBehavior;
  49640. },
  49641. enumerable: true,
  49642. configurable: true
  49643. });
  49644. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49645. /**
  49646. * Defines if the framing behavior of the camera is enabled on the camera.
  49647. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49648. */
  49649. get: function () {
  49650. return this._framingBehavior != null;
  49651. },
  49652. set: function (value) {
  49653. if (value === this.useFramingBehavior) {
  49654. return;
  49655. }
  49656. if (value) {
  49657. this._framingBehavior = new BABYLON.FramingBehavior();
  49658. this.addBehavior(this._framingBehavior);
  49659. }
  49660. else if (this._framingBehavior) {
  49661. this.removeBehavior(this._framingBehavior);
  49662. this._framingBehavior = null;
  49663. }
  49664. },
  49665. enumerable: true,
  49666. configurable: true
  49667. });
  49668. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49669. /**
  49670. * Gets the auto rotation behavior of the camera if it has been enabled.
  49671. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49672. */
  49673. get: function () {
  49674. return this._autoRotationBehavior;
  49675. },
  49676. enumerable: true,
  49677. configurable: true
  49678. });
  49679. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49680. /**
  49681. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  49682. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49683. */
  49684. get: function () {
  49685. return this._autoRotationBehavior != null;
  49686. },
  49687. set: function (value) {
  49688. if (value === this.useAutoRotationBehavior) {
  49689. return;
  49690. }
  49691. if (value) {
  49692. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49693. this.addBehavior(this._autoRotationBehavior);
  49694. }
  49695. else if (this._autoRotationBehavior) {
  49696. this.removeBehavior(this._autoRotationBehavior);
  49697. this._autoRotationBehavior = null;
  49698. }
  49699. },
  49700. enumerable: true,
  49701. configurable: true
  49702. });
  49703. // Cache
  49704. /** @hidden */
  49705. ArcRotateCamera.prototype._initCache = function () {
  49706. _super.prototype._initCache.call(this);
  49707. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49708. this._cache.alpha = undefined;
  49709. this._cache.beta = undefined;
  49710. this._cache.radius = undefined;
  49711. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49712. };
  49713. /** @hidden */
  49714. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49715. if (!ignoreParentClass) {
  49716. _super.prototype._updateCache.call(this);
  49717. }
  49718. this._cache._target.copyFrom(this._getTargetPosition());
  49719. this._cache.alpha = this.alpha;
  49720. this._cache.beta = this.beta;
  49721. this._cache.radius = this.radius;
  49722. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49723. };
  49724. ArcRotateCamera.prototype._getTargetPosition = function () {
  49725. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49726. var pos = this._targetHost.getAbsolutePosition();
  49727. if (this._targetBoundingCenter) {
  49728. pos.addToRef(this._targetBoundingCenter, this._target);
  49729. }
  49730. else {
  49731. this._target.copyFrom(pos);
  49732. }
  49733. }
  49734. var lockedTargetPosition = this._getLockedTargetPosition();
  49735. if (lockedTargetPosition) {
  49736. return lockedTargetPosition;
  49737. }
  49738. return this._target;
  49739. };
  49740. /**
  49741. * Stores the current state of the camera (alpha, beta, radius and target)
  49742. * @returns the camera itself
  49743. */
  49744. ArcRotateCamera.prototype.storeState = function () {
  49745. this._storedAlpha = this.alpha;
  49746. this._storedBeta = this.beta;
  49747. this._storedRadius = this.radius;
  49748. this._storedTarget = this._getTargetPosition().clone();
  49749. return _super.prototype.storeState.call(this);
  49750. };
  49751. /**
  49752. * @hidden
  49753. * Restored camera state. You must call storeState() first
  49754. */
  49755. ArcRotateCamera.prototype._restoreStateValues = function () {
  49756. if (!_super.prototype._restoreStateValues.call(this)) {
  49757. return false;
  49758. }
  49759. this.alpha = this._storedAlpha;
  49760. this.beta = this._storedBeta;
  49761. this.radius = this._storedRadius;
  49762. this.setTarget(this._storedTarget.clone());
  49763. this.inertialAlphaOffset = 0;
  49764. this.inertialBetaOffset = 0;
  49765. this.inertialRadiusOffset = 0;
  49766. this.inertialPanningX = 0;
  49767. this.inertialPanningY = 0;
  49768. return true;
  49769. };
  49770. // Synchronized
  49771. /** @hidden */
  49772. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49773. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49774. return false;
  49775. return this._cache._target.equals(this._getTargetPosition())
  49776. && this._cache.alpha === this.alpha
  49777. && this._cache.beta === this.beta
  49778. && this._cache.radius === this.radius
  49779. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49780. };
  49781. /**
  49782. * Attached controls to the current camera.
  49783. * @param element Defines the element the controls should be listened from
  49784. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49785. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  49786. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  49787. */
  49788. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49789. var _this = this;
  49790. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49791. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49792. this._useCtrlForPanning = useCtrlForPanning;
  49793. this._panningMouseButton = panningMouseButton;
  49794. this.inputs.attachElement(element, noPreventDefault);
  49795. this._reset = function () {
  49796. _this.inertialAlphaOffset = 0;
  49797. _this.inertialBetaOffset = 0;
  49798. _this.inertialRadiusOffset = 0;
  49799. _this.inertialPanningX = 0;
  49800. _this.inertialPanningY = 0;
  49801. };
  49802. };
  49803. /**
  49804. * Detach the current controls from the camera.
  49805. * The camera will stop reacting to inputs.
  49806. * @param element Defines the element to stop listening the inputs from
  49807. */
  49808. ArcRotateCamera.prototype.detachControl = function (element) {
  49809. this.inputs.detachElement(element);
  49810. if (this._reset) {
  49811. this._reset();
  49812. }
  49813. };
  49814. /** @hidden */
  49815. ArcRotateCamera.prototype._checkInputs = function () {
  49816. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49817. if (this._collisionTriggered) {
  49818. return;
  49819. }
  49820. this.inputs.checkInputs();
  49821. // Inertia
  49822. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49823. var inertialAlphaOffset = this.inertialAlphaOffset;
  49824. if (this.beta <= 0)
  49825. inertialAlphaOffset *= -1;
  49826. if (this.getScene().useRightHandedSystem)
  49827. inertialAlphaOffset *= -1;
  49828. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49829. inertialAlphaOffset *= -1;
  49830. this.alpha += inertialAlphaOffset;
  49831. this.beta += this.inertialBetaOffset;
  49832. this.radius -= this.inertialRadiusOffset;
  49833. this.inertialAlphaOffset *= this.inertia;
  49834. this.inertialBetaOffset *= this.inertia;
  49835. this.inertialRadiusOffset *= this.inertia;
  49836. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49837. this.inertialAlphaOffset = 0;
  49838. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49839. this.inertialBetaOffset = 0;
  49840. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49841. this.inertialRadiusOffset = 0;
  49842. }
  49843. // Panning inertia
  49844. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49845. if (!this._localDirection) {
  49846. this._localDirection = BABYLON.Vector3.Zero();
  49847. this._transformedDirection = BABYLON.Vector3.Zero();
  49848. }
  49849. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49850. this._localDirection.multiplyInPlace(this.panningAxis);
  49851. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49852. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49853. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49854. if (!this.panningAxis.y) {
  49855. this._transformedDirection.y = 0;
  49856. }
  49857. if (!this._targetHost) {
  49858. if (this.panningDistanceLimit) {
  49859. this._transformedDirection.addInPlace(this._target);
  49860. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49861. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49862. this._target.copyFrom(this._transformedDirection);
  49863. }
  49864. }
  49865. else {
  49866. this._target.addInPlace(this._transformedDirection);
  49867. }
  49868. }
  49869. this.inertialPanningX *= this.panningInertia;
  49870. this.inertialPanningY *= this.panningInertia;
  49871. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49872. this.inertialPanningX = 0;
  49873. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49874. this.inertialPanningY = 0;
  49875. }
  49876. // Limits
  49877. this._checkLimits();
  49878. _super.prototype._checkInputs.call(this);
  49879. };
  49880. ArcRotateCamera.prototype._checkLimits = function () {
  49881. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49882. if (this.allowUpsideDown && this.beta > Math.PI) {
  49883. this.beta = this.beta - (2 * Math.PI);
  49884. }
  49885. }
  49886. else {
  49887. if (this.beta < this.lowerBetaLimit) {
  49888. this.beta = this.lowerBetaLimit;
  49889. }
  49890. }
  49891. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49892. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49893. this.beta = this.beta + (2 * Math.PI);
  49894. }
  49895. }
  49896. else {
  49897. if (this.beta > this.upperBetaLimit) {
  49898. this.beta = this.upperBetaLimit;
  49899. }
  49900. }
  49901. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  49902. this.alpha = this.lowerAlphaLimit;
  49903. }
  49904. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  49905. this.alpha = this.upperAlphaLimit;
  49906. }
  49907. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  49908. this.radius = this.lowerRadiusLimit;
  49909. }
  49910. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  49911. this.radius = this.upperRadiusLimit;
  49912. }
  49913. };
  49914. /**
  49915. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  49916. */
  49917. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49918. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49919. this.radius = this._computationVector.length();
  49920. if (this.radius === 0) {
  49921. this.radius = 0.0001; // Just to avoid division by zero
  49922. }
  49923. // Alpha
  49924. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49925. if (this._computationVector.z < 0) {
  49926. this.alpha = 2 * Math.PI - this.alpha;
  49927. }
  49928. // Beta
  49929. this.beta = Math.acos(this._computationVector.y / this.radius);
  49930. this._checkLimits();
  49931. };
  49932. /**
  49933. * Use a position to define the current camera related information like aplha, beta and radius
  49934. * @param position Defines the position to set the camera at
  49935. */
  49936. ArcRotateCamera.prototype.setPosition = function (position) {
  49937. if (this.position.equals(position)) {
  49938. return;
  49939. }
  49940. this.position.copyFrom(position);
  49941. this.rebuildAnglesAndRadius();
  49942. };
  49943. /**
  49944. * Defines the target the camera should look at.
  49945. * This will automatically adapt alpha beta and radius to fit within the new target.
  49946. * @param target Defines the new target as a Vector or a mesh
  49947. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  49948. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  49949. */
  49950. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49951. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49952. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49953. if (target.getBoundingInfo) {
  49954. if (toBoundingCenter) {
  49955. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49956. }
  49957. else {
  49958. this._targetBoundingCenter = null;
  49959. }
  49960. this._targetHost = target;
  49961. this._target = this._getTargetPosition();
  49962. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49963. }
  49964. else {
  49965. var newTarget = target;
  49966. var currentTarget = this._getTargetPosition();
  49967. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49968. return;
  49969. }
  49970. this._targetHost = null;
  49971. this._target = newTarget;
  49972. this._targetBoundingCenter = null;
  49973. this.onMeshTargetChangedObservable.notifyObservers(null);
  49974. }
  49975. this.rebuildAnglesAndRadius();
  49976. };
  49977. /** @hidden */
  49978. ArcRotateCamera.prototype._getViewMatrix = function () {
  49979. // Compute
  49980. var cosa = Math.cos(this.alpha);
  49981. var sina = Math.sin(this.alpha);
  49982. var cosb = Math.cos(this.beta);
  49983. var sinb = Math.sin(this.beta);
  49984. if (sinb === 0) {
  49985. sinb = 0.0001;
  49986. }
  49987. var target = this._getTargetPosition();
  49988. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49989. target.addToRef(this._computationVector, this._newPosition);
  49990. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49991. if (!this._collider) {
  49992. this._collider = new BABYLON.Collider();
  49993. }
  49994. this._collider._radius = this.collisionRadius;
  49995. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49996. this._collisionTriggered = true;
  49997. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49998. }
  49999. else {
  50000. this.position.copyFrom(this._newPosition);
  50001. var up = this.upVector;
  50002. if (this.allowUpsideDown && sinb < 0) {
  50003. up = up.clone();
  50004. up = up.negate();
  50005. }
  50006. this._computeViewMatrix(this.position, target, up);
  50007. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50008. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50009. }
  50010. this._currentTarget = target;
  50011. return this._viewMatrix;
  50012. };
  50013. /**
  50014. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50015. * @param meshes Defines the mesh to zoom on
  50016. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50017. */
  50018. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50019. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50020. meshes = meshes || this.getScene().meshes;
  50021. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50022. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50023. this.radius = distance * this.zoomOnFactor;
  50024. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50025. };
  50026. /**
  50027. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50028. * The target will be changed but the radius
  50029. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50030. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50031. */
  50032. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50033. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50034. var meshesOrMinMaxVector;
  50035. var distance;
  50036. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50037. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50038. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50039. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50040. }
  50041. else { //minMaxVector and distance
  50042. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50043. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50044. distance = minMaxVectorAndDistance.distance;
  50045. }
  50046. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50047. if (!doNotUpdateMaxZ) {
  50048. this.maxZ = distance * 2;
  50049. }
  50050. };
  50051. /**
  50052. * @override
  50053. * Override Camera.createRigCamera
  50054. */
  50055. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50056. var alphaShift = 0;
  50057. switch (this.cameraRigMode) {
  50058. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50059. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50060. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50061. case BABYLON.Camera.RIG_MODE_VR:
  50062. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50063. break;
  50064. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50065. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50066. break;
  50067. }
  50068. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50069. rigCam._cameraRigParams = {};
  50070. return rigCam;
  50071. };
  50072. /**
  50073. * @hidden
  50074. * @override
  50075. * Override Camera._updateRigCameras
  50076. */
  50077. ArcRotateCamera.prototype._updateRigCameras = function () {
  50078. var camLeft = this._rigCameras[0];
  50079. var camRight = this._rigCameras[1];
  50080. camLeft.beta = camRight.beta = this.beta;
  50081. camLeft.radius = camRight.radius = this.radius;
  50082. switch (this.cameraRigMode) {
  50083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50084. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50085. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50086. case BABYLON.Camera.RIG_MODE_VR:
  50087. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50088. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50089. break;
  50090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50091. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50092. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50093. break;
  50094. }
  50095. _super.prototype._updateRigCameras.call(this);
  50096. };
  50097. /**
  50098. * Destroy the camera and release the current resources hold by it.
  50099. */
  50100. ArcRotateCamera.prototype.dispose = function () {
  50101. this.inputs.clear();
  50102. _super.prototype.dispose.call(this);
  50103. };
  50104. /**
  50105. * Gets the current object class name.
  50106. * @return the class name
  50107. */
  50108. ArcRotateCamera.prototype.getClassName = function () {
  50109. return "ArcRotateCamera";
  50110. };
  50111. __decorate([
  50112. BABYLON.serialize()
  50113. ], ArcRotateCamera.prototype, "alpha", void 0);
  50114. __decorate([
  50115. BABYLON.serialize()
  50116. ], ArcRotateCamera.prototype, "beta", void 0);
  50117. __decorate([
  50118. BABYLON.serialize()
  50119. ], ArcRotateCamera.prototype, "radius", void 0);
  50120. __decorate([
  50121. BABYLON.serializeAsVector3("target")
  50122. ], ArcRotateCamera.prototype, "_target", void 0);
  50123. __decorate([
  50124. BABYLON.serialize()
  50125. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50126. __decorate([
  50127. BABYLON.serialize()
  50128. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50129. __decorate([
  50130. BABYLON.serialize()
  50131. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50132. __decorate([
  50133. BABYLON.serialize()
  50134. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50135. __decorate([
  50136. BABYLON.serialize()
  50137. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50138. __decorate([
  50139. BABYLON.serialize()
  50140. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50141. __decorate([
  50142. BABYLON.serialize()
  50143. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50144. __decorate([
  50145. BABYLON.serialize()
  50146. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50147. __decorate([
  50148. BABYLON.serialize()
  50149. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50150. __decorate([
  50151. BABYLON.serialize()
  50152. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50153. __decorate([
  50154. BABYLON.serialize()
  50155. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50156. __decorate([
  50157. BABYLON.serialize()
  50158. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50159. __decorate([
  50160. BABYLON.serialize()
  50161. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50162. __decorate([
  50163. BABYLON.serializeAsVector3()
  50164. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50165. __decorate([
  50166. BABYLON.serialize()
  50167. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50168. __decorate([
  50169. BABYLON.serialize()
  50170. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50171. __decorate([
  50172. BABYLON.serialize()
  50173. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50174. __decorate([
  50175. BABYLON.serialize()
  50176. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50177. __decorate([
  50178. BABYLON.serialize()
  50179. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50180. return ArcRotateCamera;
  50181. }(BABYLON.TargetCamera));
  50182. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50183. })(BABYLON || (BABYLON = {}));
  50184. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50185. var BABYLON;
  50186. (function (BABYLON) {
  50187. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50188. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50189. });
  50190. /**
  50191. * The HemisphericLight simulates the ambient environment light,
  50192. * so the passed direction is the light reflection direction, not the incoming direction.
  50193. */
  50194. var HemisphericLight = /** @class */ (function (_super) {
  50195. __extends(HemisphericLight, _super);
  50196. /**
  50197. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50198. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50199. * The HemisphericLight can't cast shadows.
  50200. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50201. * @param name The friendly name of the light
  50202. * @param direction The direction of the light reflection
  50203. * @param scene The scene the light belongs to
  50204. */
  50205. function HemisphericLight(name, direction, scene) {
  50206. var _this = _super.call(this, name, scene) || this;
  50207. /**
  50208. * The groundColor is the light in the opposite direction to the one specified during creation.
  50209. * 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.
  50210. */
  50211. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50212. _this.direction = direction || BABYLON.Vector3.Up();
  50213. return _this;
  50214. }
  50215. HemisphericLight.prototype._buildUniformLayout = function () {
  50216. this._uniformBuffer.addUniform("vLightData", 4);
  50217. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50218. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50219. this._uniformBuffer.addUniform("vLightGround", 3);
  50220. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50221. this._uniformBuffer.addUniform("depthValues", 2);
  50222. this._uniformBuffer.create();
  50223. };
  50224. /**
  50225. * Returns the string "HemisphericLight".
  50226. * @return The class name
  50227. */
  50228. HemisphericLight.prototype.getClassName = function () {
  50229. return "HemisphericLight";
  50230. };
  50231. /**
  50232. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50233. * Returns the updated direction.
  50234. * @param target The target the direction should point to
  50235. * @return The computed direction
  50236. */
  50237. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50238. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50239. return this.direction;
  50240. };
  50241. /**
  50242. * Returns the shadow generator associated to the light.
  50243. * @returns Always null for hemispheric lights because it does not support shadows.
  50244. */
  50245. HemisphericLight.prototype.getShadowGenerator = function () {
  50246. return null;
  50247. };
  50248. /**
  50249. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50250. * @param effect The effect to update
  50251. * @param lightIndex The index of the light in the effect to update
  50252. * @returns The hemispheric light
  50253. */
  50254. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50255. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50256. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50257. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50258. return this;
  50259. };
  50260. /**
  50261. * Computes the world matrix of the node
  50262. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50263. * @param useWasUpdatedFlag defines a reserved property
  50264. * @returns the world matrix
  50265. */
  50266. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50267. if (!this._worldMatrix) {
  50268. this._worldMatrix = BABYLON.Matrix.Identity();
  50269. }
  50270. return this._worldMatrix;
  50271. };
  50272. /**
  50273. * Returns the integer 3.
  50274. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50275. */
  50276. HemisphericLight.prototype.getTypeID = function () {
  50277. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50278. };
  50279. /**
  50280. * Prepares the list of defines specific to the light type.
  50281. * @param defines the list of defines
  50282. * @param lightIndex defines the index of the light for the effect
  50283. */
  50284. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50285. defines["HEMILIGHT" + lightIndex] = true;
  50286. };
  50287. __decorate([
  50288. BABYLON.serializeAsColor3()
  50289. ], HemisphericLight.prototype, "groundColor", void 0);
  50290. __decorate([
  50291. BABYLON.serializeAsVector3()
  50292. ], HemisphericLight.prototype, "direction", void 0);
  50293. return HemisphericLight;
  50294. }(BABYLON.Light));
  50295. BABYLON.HemisphericLight = HemisphericLight;
  50296. })(BABYLON || (BABYLON = {}));
  50297. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50298. var BABYLON;
  50299. (function (BABYLON) {
  50300. /**
  50301. * Base implementation IShadowLight
  50302. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50303. */
  50304. var ShadowLight = /** @class */ (function (_super) {
  50305. __extends(ShadowLight, _super);
  50306. function ShadowLight() {
  50307. var _this = _super !== null && _super.apply(this, arguments) || this;
  50308. _this._needProjectionMatrixCompute = true;
  50309. return _this;
  50310. }
  50311. ShadowLight.prototype._setPosition = function (value) {
  50312. this._position = value;
  50313. };
  50314. Object.defineProperty(ShadowLight.prototype, "position", {
  50315. /**
  50316. * Sets the position the shadow will be casted from. Also use as the light position for both
  50317. * point and spot lights.
  50318. */
  50319. get: function () {
  50320. return this._position;
  50321. },
  50322. /**
  50323. * Sets the position the shadow will be casted from. Also use as the light position for both
  50324. * point and spot lights.
  50325. */
  50326. set: function (value) {
  50327. this._setPosition(value);
  50328. },
  50329. enumerable: true,
  50330. configurable: true
  50331. });
  50332. ShadowLight.prototype._setDirection = function (value) {
  50333. this._direction = value;
  50334. };
  50335. Object.defineProperty(ShadowLight.prototype, "direction", {
  50336. /**
  50337. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50338. * Also use as the light direction on spot and directional lights.
  50339. */
  50340. get: function () {
  50341. return this._direction;
  50342. },
  50343. /**
  50344. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50345. * Also use as the light direction on spot and directional lights.
  50346. */
  50347. set: function (value) {
  50348. this._setDirection(value);
  50349. },
  50350. enumerable: true,
  50351. configurable: true
  50352. });
  50353. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50354. /**
  50355. * Gets the shadow projection clipping minimum z value.
  50356. */
  50357. get: function () {
  50358. return this._shadowMinZ;
  50359. },
  50360. /**
  50361. * Sets the shadow projection clipping minimum z value.
  50362. */
  50363. set: function (value) {
  50364. this._shadowMinZ = value;
  50365. this.forceProjectionMatrixCompute();
  50366. },
  50367. enumerable: true,
  50368. configurable: true
  50369. });
  50370. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50371. /**
  50372. * Sets the shadow projection clipping maximum z value.
  50373. */
  50374. get: function () {
  50375. return this._shadowMaxZ;
  50376. },
  50377. /**
  50378. * Gets the shadow projection clipping maximum z value.
  50379. */
  50380. set: function (value) {
  50381. this._shadowMaxZ = value;
  50382. this.forceProjectionMatrixCompute();
  50383. },
  50384. enumerable: true,
  50385. configurable: true
  50386. });
  50387. /**
  50388. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50389. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50390. */
  50391. ShadowLight.prototype.computeTransformedInformation = function () {
  50392. if (this.parent && this.parent.getWorldMatrix) {
  50393. if (!this.transformedPosition) {
  50394. this.transformedPosition = BABYLON.Vector3.Zero();
  50395. }
  50396. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50397. // In case the direction is present.
  50398. if (this.direction) {
  50399. if (!this.transformedDirection) {
  50400. this.transformedDirection = BABYLON.Vector3.Zero();
  50401. }
  50402. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50403. }
  50404. return true;
  50405. }
  50406. return false;
  50407. };
  50408. /**
  50409. * Return the depth scale used for the shadow map.
  50410. * @returns the depth scale.
  50411. */
  50412. ShadowLight.prototype.getDepthScale = function () {
  50413. return 50.0;
  50414. };
  50415. /**
  50416. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50417. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50418. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50419. */
  50420. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50421. return this.transformedDirection ? this.transformedDirection : this.direction;
  50422. };
  50423. /**
  50424. * Returns the ShadowLight absolute position in the World.
  50425. * @returns the position vector in world space
  50426. */
  50427. ShadowLight.prototype.getAbsolutePosition = function () {
  50428. return this.transformedPosition ? this.transformedPosition : this.position;
  50429. };
  50430. /**
  50431. * Sets the ShadowLight direction toward the passed target.
  50432. * @param target The point tot target in local space
  50433. * @returns the updated ShadowLight direction
  50434. */
  50435. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50436. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50437. return this.direction;
  50438. };
  50439. /**
  50440. * Returns the light rotation in euler definition.
  50441. * @returns the x y z rotation in local space.
  50442. */
  50443. ShadowLight.prototype.getRotation = function () {
  50444. this.direction.normalize();
  50445. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50446. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50447. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50448. };
  50449. /**
  50450. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50451. * @returns true if a cube texture needs to be use
  50452. */
  50453. ShadowLight.prototype.needCube = function () {
  50454. return false;
  50455. };
  50456. /**
  50457. * Detects if the projection matrix requires to be recomputed this frame.
  50458. * @returns true if it requires to be recomputed otherwise, false.
  50459. */
  50460. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50461. return this._needProjectionMatrixCompute;
  50462. };
  50463. /**
  50464. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50465. */
  50466. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50467. this._needProjectionMatrixCompute = true;
  50468. };
  50469. /** @hidden */
  50470. ShadowLight.prototype._initCache = function () {
  50471. _super.prototype._initCache.call(this);
  50472. this._cache.position = BABYLON.Vector3.Zero();
  50473. };
  50474. /** @hidden */
  50475. ShadowLight.prototype._isSynchronized = function () {
  50476. if (!this._cache.position.equals(this.position))
  50477. return false;
  50478. return true;
  50479. };
  50480. /**
  50481. * Computes the world matrix of the node
  50482. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50483. * @returns the world matrix
  50484. */
  50485. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50486. if (!force && this.isSynchronized()) {
  50487. this._currentRenderId = this.getScene().getRenderId();
  50488. return this._worldMatrix;
  50489. }
  50490. this._updateCache();
  50491. this._cache.position.copyFrom(this.position);
  50492. if (!this._worldMatrix) {
  50493. this._worldMatrix = BABYLON.Matrix.Identity();
  50494. }
  50495. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50496. if (this.parent && this.parent.getWorldMatrix) {
  50497. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50498. this._markSyncedWithParent();
  50499. }
  50500. // Cache the determinant
  50501. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50502. return this._worldMatrix;
  50503. };
  50504. /**
  50505. * Gets the minZ used for shadow according to both the scene and the light.
  50506. * @param activeCamera The camera we are returning the min for
  50507. * @returns the depth min z
  50508. */
  50509. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50510. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50511. };
  50512. /**
  50513. * Gets the maxZ used for shadow according to both the scene and the light.
  50514. * @param activeCamera The camera we are returning the max for
  50515. * @returns the depth max z
  50516. */
  50517. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50518. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50519. };
  50520. /**
  50521. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50522. * @param matrix The materix to updated with the projection information
  50523. * @param viewMatrix The transform matrix of the light
  50524. * @param renderList The list of mesh to render in the map
  50525. * @returns The current light
  50526. */
  50527. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50528. if (this.customProjectionMatrixBuilder) {
  50529. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  50530. }
  50531. else {
  50532. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50533. }
  50534. return this;
  50535. };
  50536. __decorate([
  50537. BABYLON.serializeAsVector3()
  50538. ], ShadowLight.prototype, "position", null);
  50539. __decorate([
  50540. BABYLON.serializeAsVector3()
  50541. ], ShadowLight.prototype, "direction", null);
  50542. __decorate([
  50543. BABYLON.serialize()
  50544. ], ShadowLight.prototype, "shadowMinZ", null);
  50545. __decorate([
  50546. BABYLON.serialize()
  50547. ], ShadowLight.prototype, "shadowMaxZ", null);
  50548. return ShadowLight;
  50549. }(BABYLON.Light));
  50550. BABYLON.ShadowLight = ShadowLight;
  50551. })(BABYLON || (BABYLON = {}));
  50552. //# sourceMappingURL=babylon.shadowLight.js.map
  50553. var BABYLON;
  50554. (function (BABYLON) {
  50555. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  50556. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  50557. });
  50558. /**
  50559. * A point light is a light defined by an unique point in world space.
  50560. * The light is emitted in every direction from this point.
  50561. * A good example of a point light is a standard light bulb.
  50562. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50563. */
  50564. var PointLight = /** @class */ (function (_super) {
  50565. __extends(PointLight, _super);
  50566. /**
  50567. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  50568. * A PointLight emits the light in every direction.
  50569. * It can cast shadows.
  50570. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  50571. * ```javascript
  50572. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  50573. * ```
  50574. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50575. * @param name The light friendly name
  50576. * @param position The position of the point light in the scene
  50577. * @param scene The scene the lights belongs to
  50578. */
  50579. function PointLight(name, position, scene) {
  50580. var _this = _super.call(this, name, scene) || this;
  50581. _this._shadowAngle = Math.PI / 2;
  50582. _this.position = position;
  50583. return _this;
  50584. }
  50585. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  50586. /**
  50587. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50588. * This specifies what angle the shadow will use to be created.
  50589. *
  50590. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50591. */
  50592. get: function () {
  50593. return this._shadowAngle;
  50594. },
  50595. /**
  50596. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50597. * This specifies what angle the shadow will use to be created.
  50598. *
  50599. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50600. */
  50601. set: function (value) {
  50602. this._shadowAngle = value;
  50603. this.forceProjectionMatrixCompute();
  50604. },
  50605. enumerable: true,
  50606. configurable: true
  50607. });
  50608. Object.defineProperty(PointLight.prototype, "direction", {
  50609. /**
  50610. * Gets the direction if it has been set.
  50611. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50612. */
  50613. get: function () {
  50614. return this._direction;
  50615. },
  50616. /**
  50617. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50618. */
  50619. set: function (value) {
  50620. var previousNeedCube = this.needCube();
  50621. this._direction = value;
  50622. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  50623. this._shadowGenerator.recreateShadowMap();
  50624. }
  50625. },
  50626. enumerable: true,
  50627. configurable: true
  50628. });
  50629. /**
  50630. * Returns the string "PointLight"
  50631. * @returns the class name
  50632. */
  50633. PointLight.prototype.getClassName = function () {
  50634. return "PointLight";
  50635. };
  50636. /**
  50637. * Returns the integer 0.
  50638. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50639. */
  50640. PointLight.prototype.getTypeID = function () {
  50641. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50642. };
  50643. /**
  50644. * Specifies wether or not the shadowmap should be a cube texture.
  50645. * @returns true if the shadowmap needs to be a cube texture.
  50646. */
  50647. PointLight.prototype.needCube = function () {
  50648. return !this.direction;
  50649. };
  50650. /**
  50651. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50652. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50653. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50654. */
  50655. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50656. if (this.direction) {
  50657. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50658. }
  50659. else {
  50660. switch (faceIndex) {
  50661. case 0:
  50662. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50663. case 1:
  50664. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50665. case 2:
  50666. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50667. case 3:
  50668. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50669. case 4:
  50670. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50671. case 5:
  50672. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50673. }
  50674. }
  50675. return BABYLON.Vector3.Zero();
  50676. };
  50677. /**
  50678. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50679. * - fov = PI / 2
  50680. * - aspect ratio : 1.0
  50681. * - z-near and far equal to the active camera minZ and maxZ.
  50682. * Returns the PointLight.
  50683. */
  50684. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50685. var activeCamera = this.getScene().activeCamera;
  50686. if (!activeCamera) {
  50687. return;
  50688. }
  50689. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50690. };
  50691. PointLight.prototype._buildUniformLayout = function () {
  50692. this._uniformBuffer.addUniform("vLightData", 4);
  50693. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50694. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50695. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50696. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50697. this._uniformBuffer.addUniform("depthValues", 2);
  50698. this._uniformBuffer.create();
  50699. };
  50700. /**
  50701. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50702. * @param effect The effect to update
  50703. * @param lightIndex The index of the light in the effect to update
  50704. * @returns The point light
  50705. */
  50706. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50707. if (this.computeTransformedInformation()) {
  50708. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50709. }
  50710. else {
  50711. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50712. }
  50713. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  50714. return this;
  50715. };
  50716. /**
  50717. * Prepares the list of defines specific to the light type.
  50718. * @param defines the list of defines
  50719. * @param lightIndex defines the index of the light for the effect
  50720. */
  50721. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50722. defines["POINTLIGHT" + lightIndex] = true;
  50723. };
  50724. __decorate([
  50725. BABYLON.serialize()
  50726. ], PointLight.prototype, "shadowAngle", null);
  50727. return PointLight;
  50728. }(BABYLON.ShadowLight));
  50729. BABYLON.PointLight = PointLight;
  50730. })(BABYLON || (BABYLON = {}));
  50731. //# sourceMappingURL=babylon.pointLight.js.map
  50732. var BABYLON;
  50733. (function (BABYLON) {
  50734. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  50735. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  50736. });
  50737. /**
  50738. * A directional light is defined by a direction (what a surprise!).
  50739. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50740. * 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.
  50741. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50742. */
  50743. var DirectionalLight = /** @class */ (function (_super) {
  50744. __extends(DirectionalLight, _super);
  50745. /**
  50746. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50747. * The directional light is emitted from everywhere in the given direction.
  50748. * It can cast shadows.
  50749. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50750. * @param name The friendly name of the light
  50751. * @param direction The direction of the light
  50752. * @param scene The scene the light belongs to
  50753. */
  50754. function DirectionalLight(name, direction, scene) {
  50755. var _this = _super.call(this, name, scene) || this;
  50756. _this._shadowFrustumSize = 0;
  50757. _this._shadowOrthoScale = 0.1;
  50758. /**
  50759. * Automatically compute the projection matrix to best fit (including all the casters)
  50760. * on each frame.
  50761. */
  50762. _this.autoUpdateExtends = true;
  50763. // Cache
  50764. _this._orthoLeft = Number.MAX_VALUE;
  50765. _this._orthoRight = Number.MIN_VALUE;
  50766. _this._orthoTop = Number.MIN_VALUE;
  50767. _this._orthoBottom = Number.MAX_VALUE;
  50768. _this.position = direction.scale(-1.0);
  50769. _this.direction = direction;
  50770. return _this;
  50771. }
  50772. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50773. /**
  50774. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50775. */
  50776. get: function () {
  50777. return this._shadowFrustumSize;
  50778. },
  50779. /**
  50780. * Specifies a fix frustum size for the shadow generation.
  50781. */
  50782. set: function (value) {
  50783. this._shadowFrustumSize = value;
  50784. this.forceProjectionMatrixCompute();
  50785. },
  50786. enumerable: true,
  50787. configurable: true
  50788. });
  50789. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50790. /**
  50791. * Gets the shadow projection scale against the optimal computed one.
  50792. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50793. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50794. */
  50795. get: function () {
  50796. return this._shadowOrthoScale;
  50797. },
  50798. /**
  50799. * Sets the shadow projection scale against the optimal computed one.
  50800. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50801. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50802. */
  50803. set: function (value) {
  50804. this._shadowOrthoScale = value;
  50805. this.forceProjectionMatrixCompute();
  50806. },
  50807. enumerable: true,
  50808. configurable: true
  50809. });
  50810. /**
  50811. * Returns the string "DirectionalLight".
  50812. * @return The class name
  50813. */
  50814. DirectionalLight.prototype.getClassName = function () {
  50815. return "DirectionalLight";
  50816. };
  50817. /**
  50818. * Returns the integer 1.
  50819. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50820. */
  50821. DirectionalLight.prototype.getTypeID = function () {
  50822. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50823. };
  50824. /**
  50825. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50826. * Returns the DirectionalLight Shadow projection matrix.
  50827. */
  50828. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50829. if (this.shadowFrustumSize > 0) {
  50830. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50831. }
  50832. else {
  50833. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50834. }
  50835. };
  50836. /**
  50837. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50838. * Returns the DirectionalLight Shadow projection matrix.
  50839. */
  50840. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50841. var activeCamera = this.getScene().activeCamera;
  50842. if (!activeCamera) {
  50843. return;
  50844. }
  50845. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50846. };
  50847. /**
  50848. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50849. * Returns the DirectionalLight Shadow projection matrix.
  50850. */
  50851. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50852. var activeCamera = this.getScene().activeCamera;
  50853. if (!activeCamera) {
  50854. return;
  50855. }
  50856. // Check extends
  50857. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50858. var tempVector3 = BABYLON.Vector3.Zero();
  50859. this._orthoLeft = Number.MAX_VALUE;
  50860. this._orthoRight = Number.MIN_VALUE;
  50861. this._orthoTop = Number.MIN_VALUE;
  50862. this._orthoBottom = Number.MAX_VALUE;
  50863. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50864. var mesh = renderList[meshIndex];
  50865. if (!mesh) {
  50866. continue;
  50867. }
  50868. var boundingInfo = mesh.getBoundingInfo();
  50869. var boundingBox = boundingInfo.boundingBox;
  50870. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50871. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50872. if (tempVector3.x < this._orthoLeft)
  50873. this._orthoLeft = tempVector3.x;
  50874. if (tempVector3.y < this._orthoBottom)
  50875. this._orthoBottom = tempVector3.y;
  50876. if (tempVector3.x > this._orthoRight)
  50877. this._orthoRight = tempVector3.x;
  50878. if (tempVector3.y > this._orthoTop)
  50879. this._orthoTop = tempVector3.y;
  50880. }
  50881. }
  50882. }
  50883. var xOffset = this._orthoRight - this._orthoLeft;
  50884. var yOffset = this._orthoTop - this._orthoBottom;
  50885. 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);
  50886. };
  50887. DirectionalLight.prototype._buildUniformLayout = function () {
  50888. this._uniformBuffer.addUniform("vLightData", 4);
  50889. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50890. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50891. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50892. this._uniformBuffer.addUniform("depthValues", 2);
  50893. this._uniformBuffer.create();
  50894. };
  50895. /**
  50896. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50897. * @param effect The effect to update
  50898. * @param lightIndex The index of the light in the effect to update
  50899. * @returns The directional light
  50900. */
  50901. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50902. if (this.computeTransformedInformation()) {
  50903. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50904. return this;
  50905. }
  50906. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50907. return this;
  50908. };
  50909. /**
  50910. * Gets the minZ used for shadow according to both the scene and the light.
  50911. *
  50912. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50913. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50914. * @param activeCamera The camera we are returning the min for
  50915. * @returns the depth min z
  50916. */
  50917. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50918. return 1;
  50919. };
  50920. /**
  50921. * Gets the maxZ used for shadow according to both the scene and the light.
  50922. *
  50923. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50924. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50925. * @param activeCamera The camera we are returning the max for
  50926. * @returns the depth max z
  50927. */
  50928. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50929. return 1;
  50930. };
  50931. /**
  50932. * Prepares the list of defines specific to the light type.
  50933. * @param defines the list of defines
  50934. * @param lightIndex defines the index of the light for the effect
  50935. */
  50936. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50937. defines["DIRLIGHT" + lightIndex] = true;
  50938. };
  50939. __decorate([
  50940. BABYLON.serialize()
  50941. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50942. __decorate([
  50943. BABYLON.serialize()
  50944. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50945. __decorate([
  50946. BABYLON.serialize()
  50947. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50948. return DirectionalLight;
  50949. }(BABYLON.ShadowLight));
  50950. BABYLON.DirectionalLight = DirectionalLight;
  50951. })(BABYLON || (BABYLON = {}));
  50952. //# sourceMappingURL=babylon.directionalLight.js.map
  50953. var BABYLON;
  50954. (function (BABYLON) {
  50955. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50956. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50957. });
  50958. /**
  50959. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50960. * These values define a cone of light starting from the position, emitting toward the direction.
  50961. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50962. * and the exponent defines the speed of the decay of the light with distance (reach).
  50963. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50964. */
  50965. var SpotLight = /** @class */ (function (_super) {
  50966. __extends(SpotLight, _super);
  50967. /**
  50968. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50969. * It can cast shadows.
  50970. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50971. * @param name The light friendly name
  50972. * @param position The position of the spot light in the scene
  50973. * @param direction The direction of the light in the scene
  50974. * @param angle The cone angle of the light in Radians
  50975. * @param exponent The light decay speed with the distance from the emission spot
  50976. * @param scene The scene the lights belongs to
  50977. */
  50978. function SpotLight(name, position, direction, angle, exponent, scene) {
  50979. var _this = _super.call(this, name, scene) || this;
  50980. _this._innerAngle = 0;
  50981. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50982. _this._projectionTextureLightNear = 1e-6;
  50983. _this._projectionTextureLightFar = 1000.0;
  50984. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50985. _this._projectionTextureViewLightDirty = true;
  50986. _this._projectionTextureProjectionLightDirty = true;
  50987. _this._projectionTextureDirty = true;
  50988. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50989. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50990. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50991. _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);
  50992. _this.position = position;
  50993. _this.direction = direction;
  50994. _this.angle = angle;
  50995. _this.exponent = exponent;
  50996. return _this;
  50997. }
  50998. Object.defineProperty(SpotLight.prototype, "angle", {
  50999. /**
  51000. * Gets the cone angle of the spot light in Radians.
  51001. */
  51002. get: function () {
  51003. return this._angle;
  51004. },
  51005. /**
  51006. * Sets the cone angle of the spot light in Radians.
  51007. */
  51008. set: function (value) {
  51009. this._angle = value;
  51010. this._cosHalfAngle = Math.cos(value * 0.5);
  51011. this._projectionTextureProjectionLightDirty = true;
  51012. this.forceProjectionMatrixCompute();
  51013. this._computeAngleValues();
  51014. },
  51015. enumerable: true,
  51016. configurable: true
  51017. });
  51018. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51019. /**
  51020. * Only used in gltf falloff mode, this defines the angle where
  51021. * the directional falloff will start before cutting at angle which could be seen
  51022. * as outer angle.
  51023. */
  51024. get: function () {
  51025. return this._innerAngle;
  51026. },
  51027. /**
  51028. * Only used in gltf falloff mode, this defines the angle where
  51029. * the directional falloff will start before cutting at angle which could be seen
  51030. * as outer angle.
  51031. */
  51032. set: function (value) {
  51033. this._innerAngle = value;
  51034. this._computeAngleValues();
  51035. },
  51036. enumerable: true,
  51037. configurable: true
  51038. });
  51039. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51040. /**
  51041. * Allows scaling the angle of the light for shadow generation only.
  51042. */
  51043. get: function () {
  51044. return this._shadowAngleScale;
  51045. },
  51046. /**
  51047. * Allows scaling the angle of the light for shadow generation only.
  51048. */
  51049. set: function (value) {
  51050. this._shadowAngleScale = value;
  51051. this.forceProjectionMatrixCompute();
  51052. },
  51053. enumerable: true,
  51054. configurable: true
  51055. });
  51056. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51057. /**
  51058. * Allows reading the projecton texture
  51059. */
  51060. get: function () {
  51061. return this._projectionTextureMatrix;
  51062. },
  51063. enumerable: true,
  51064. configurable: true
  51065. });
  51066. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51067. /**
  51068. * Gets the near clip of the Spotlight for texture projection.
  51069. */
  51070. get: function () {
  51071. return this._projectionTextureLightNear;
  51072. },
  51073. /**
  51074. * Sets the near clip of the Spotlight for texture projection.
  51075. */
  51076. set: function (value) {
  51077. this._projectionTextureLightNear = value;
  51078. this._projectionTextureProjectionLightDirty = true;
  51079. },
  51080. enumerable: true,
  51081. configurable: true
  51082. });
  51083. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51084. /**
  51085. * Gets the far clip of the Spotlight for texture projection.
  51086. */
  51087. get: function () {
  51088. return this._projectionTextureLightFar;
  51089. },
  51090. /**
  51091. * Sets the far clip of the Spotlight for texture projection.
  51092. */
  51093. set: function (value) {
  51094. this._projectionTextureLightFar = value;
  51095. this._projectionTextureProjectionLightDirty = true;
  51096. },
  51097. enumerable: true,
  51098. configurable: true
  51099. });
  51100. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51101. /**
  51102. * Gets the Up vector of the Spotlight for texture projection.
  51103. */
  51104. get: function () {
  51105. return this._projectionTextureUpDirection;
  51106. },
  51107. /**
  51108. * Sets the Up vector of the Spotlight for texture projection.
  51109. */
  51110. set: function (value) {
  51111. this._projectionTextureUpDirection = value;
  51112. this._projectionTextureProjectionLightDirty = true;
  51113. },
  51114. enumerable: true,
  51115. configurable: true
  51116. });
  51117. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51118. /**
  51119. * Gets the projection texture of the light.
  51120. */
  51121. get: function () {
  51122. return this._projectionTexture;
  51123. },
  51124. /**
  51125. * Sets the projection texture of the light.
  51126. */
  51127. set: function (value) {
  51128. this._projectionTexture = value;
  51129. this._projectionTextureDirty = true;
  51130. },
  51131. enumerable: true,
  51132. configurable: true
  51133. });
  51134. /**
  51135. * Returns the string "SpotLight".
  51136. * @returns the class name
  51137. */
  51138. SpotLight.prototype.getClassName = function () {
  51139. return "SpotLight";
  51140. };
  51141. /**
  51142. * Returns the integer 2.
  51143. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51144. */
  51145. SpotLight.prototype.getTypeID = function () {
  51146. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51147. };
  51148. /**
  51149. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51150. */
  51151. SpotLight.prototype._setDirection = function (value) {
  51152. _super.prototype._setDirection.call(this, value);
  51153. this._projectionTextureViewLightDirty = true;
  51154. };
  51155. /**
  51156. * Overrides the position setter to recompute the projection texture view light Matrix.
  51157. */
  51158. SpotLight.prototype._setPosition = function (value) {
  51159. _super.prototype._setPosition.call(this, value);
  51160. this._projectionTextureViewLightDirty = true;
  51161. };
  51162. /**
  51163. * 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.
  51164. * Returns the SpotLight.
  51165. */
  51166. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51167. var activeCamera = this.getScene().activeCamera;
  51168. if (!activeCamera) {
  51169. return;
  51170. }
  51171. this._shadowAngleScale = this._shadowAngleScale || 1;
  51172. var angle = this._shadowAngleScale * this._angle;
  51173. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51174. };
  51175. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51176. this._projectionTextureViewLightDirty = false;
  51177. this._projectionTextureDirty = true;
  51178. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51179. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51180. };
  51181. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51182. this._projectionTextureProjectionLightDirty = false;
  51183. this._projectionTextureDirty = true;
  51184. var light_far = this.projectionTextureLightFar;
  51185. var light_near = this.projectionTextureLightNear;
  51186. var P = light_far / (light_far - light_near);
  51187. var Q = -P * light_near;
  51188. var S = 1.0 / Math.tan(this._angle / 2.0);
  51189. var A = 1.0;
  51190. 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);
  51191. };
  51192. /**
  51193. * Main function for light texture projection matrix computing.
  51194. */
  51195. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51196. this._projectionTextureDirty = false;
  51197. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51198. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51199. };
  51200. SpotLight.prototype._buildUniformLayout = function () {
  51201. this._uniformBuffer.addUniform("vLightData", 4);
  51202. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51203. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51204. this._uniformBuffer.addUniform("vLightDirection", 3);
  51205. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51206. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51207. this._uniformBuffer.addUniform("depthValues", 2);
  51208. this._uniformBuffer.create();
  51209. };
  51210. SpotLight.prototype._computeAngleValues = function () {
  51211. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51212. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51213. };
  51214. /**
  51215. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51216. * @param effect The effect to update
  51217. * @param lightIndex The index of the light in the effect to update
  51218. * @returns The spot light
  51219. */
  51220. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51221. var normalizeDirection;
  51222. if (this.computeTransformedInformation()) {
  51223. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51224. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51225. }
  51226. else {
  51227. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51228. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51229. }
  51230. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51231. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51232. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51233. if (this._projectionTextureViewLightDirty) {
  51234. this._computeProjectionTextureViewLightMatrix();
  51235. }
  51236. if (this._projectionTextureProjectionLightDirty) {
  51237. this._computeProjectionTextureProjectionLightMatrix();
  51238. }
  51239. if (this._projectionTextureDirty) {
  51240. this._computeProjectionTextureMatrix();
  51241. }
  51242. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51243. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51244. }
  51245. return this;
  51246. };
  51247. /**
  51248. * Disposes the light and the associated resources.
  51249. */
  51250. SpotLight.prototype.dispose = function () {
  51251. _super.prototype.dispose.call(this);
  51252. if (this._projectionTexture) {
  51253. this._projectionTexture.dispose();
  51254. }
  51255. };
  51256. /**
  51257. * Prepares the list of defines specific to the light type.
  51258. * @param defines the list of defines
  51259. * @param lightIndex defines the index of the light for the effect
  51260. */
  51261. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51262. defines["SPOTLIGHT" + lightIndex] = true;
  51263. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51264. };
  51265. __decorate([
  51266. BABYLON.serialize()
  51267. ], SpotLight.prototype, "angle", null);
  51268. __decorate([
  51269. BABYLON.serialize()
  51270. ], SpotLight.prototype, "innerAngle", null);
  51271. __decorate([
  51272. BABYLON.serialize()
  51273. ], SpotLight.prototype, "shadowAngleScale", null);
  51274. __decorate([
  51275. BABYLON.serialize()
  51276. ], SpotLight.prototype, "exponent", void 0);
  51277. __decorate([
  51278. BABYLON.serialize()
  51279. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51280. __decorate([
  51281. BABYLON.serialize()
  51282. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51283. __decorate([
  51284. BABYLON.serialize()
  51285. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51286. __decorate([
  51287. BABYLON.serializeAsTexture("projectedLightTexture")
  51288. ], SpotLight.prototype, "_projectionTexture", void 0);
  51289. return SpotLight;
  51290. }(BABYLON.ShadowLight));
  51291. BABYLON.SpotLight = SpotLight;
  51292. })(BABYLON || (BABYLON = {}));
  51293. //# sourceMappingURL=babylon.spotLight.js.map
  51294. var BABYLON;
  51295. (function (BABYLON) {
  51296. /**
  51297. * Class used to override all child animations of a given target
  51298. */
  51299. var AnimationPropertiesOverride = /** @class */ (function () {
  51300. function AnimationPropertiesOverride() {
  51301. /**
  51302. * Gets or sets a value indicating if animation blending must be used
  51303. */
  51304. this.enableBlending = false;
  51305. /**
  51306. * Gets or sets the blending speed to use when enableBlending is true
  51307. */
  51308. this.blendingSpeed = 0.01;
  51309. /**
  51310. * Gets or sets the default loop mode to use
  51311. */
  51312. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51313. }
  51314. return AnimationPropertiesOverride;
  51315. }());
  51316. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51317. })(BABYLON || (BABYLON = {}));
  51318. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51319. var BABYLON;
  51320. (function (BABYLON) {
  51321. /**
  51322. * Represents the range of an animation
  51323. */
  51324. var AnimationRange = /** @class */ (function () {
  51325. /**
  51326. * Initializes the range of an animation
  51327. * @param name The name of the animation range
  51328. * @param from The starting frame of the animation
  51329. * @param to The ending frame of the animation
  51330. */
  51331. function AnimationRange(
  51332. /**The name of the animation range**/
  51333. name,
  51334. /**The starting frame of the animation */
  51335. from,
  51336. /**The ending frame of the animation*/
  51337. to) {
  51338. this.name = name;
  51339. this.from = from;
  51340. this.to = to;
  51341. }
  51342. /**
  51343. * Makes a copy of the animation range
  51344. * @returns A copy of the animation range
  51345. */
  51346. AnimationRange.prototype.clone = function () {
  51347. return new AnimationRange(this.name, this.from, this.to);
  51348. };
  51349. return AnimationRange;
  51350. }());
  51351. BABYLON.AnimationRange = AnimationRange;
  51352. /**
  51353. * Composed of a frame, and an action function
  51354. */
  51355. var AnimationEvent = /** @class */ (function () {
  51356. /**
  51357. * Initializes the animation event
  51358. * @param frame The frame for which the event is triggered
  51359. * @param action The event to perform when triggered
  51360. * @param onlyOnce Specifies if the event should be triggered only once
  51361. */
  51362. function AnimationEvent(
  51363. /** The frame for which the event is triggered **/
  51364. frame,
  51365. /** The event to perform when triggered **/
  51366. action,
  51367. /** Specifies if the event should be triggered only once**/
  51368. onlyOnce) {
  51369. this.frame = frame;
  51370. this.action = action;
  51371. this.onlyOnce = onlyOnce;
  51372. /**
  51373. * Specifies if the animation event is done
  51374. */
  51375. this.isDone = false;
  51376. }
  51377. /** @hidden */
  51378. AnimationEvent.prototype._clone = function () {
  51379. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51380. };
  51381. return AnimationEvent;
  51382. }());
  51383. BABYLON.AnimationEvent = AnimationEvent;
  51384. /**
  51385. * A cursor which tracks a point on a path
  51386. */
  51387. var PathCursor = /** @class */ (function () {
  51388. /**
  51389. * Initializes the path cursor
  51390. * @param path The path to track
  51391. */
  51392. function PathCursor(path) {
  51393. this.path = path;
  51394. /**
  51395. * Stores path cursor callbacks for when an onchange event is triggered
  51396. */
  51397. this._onchange = new Array();
  51398. /**
  51399. * The value of the path cursor
  51400. */
  51401. this.value = 0;
  51402. /**
  51403. * The animation array of the path cursor
  51404. */
  51405. this.animations = new Array();
  51406. }
  51407. /**
  51408. * Gets the cursor point on the path
  51409. * @returns A point on the path cursor at the cursor location
  51410. */
  51411. PathCursor.prototype.getPoint = function () {
  51412. var point = this.path.getPointAtLengthPosition(this.value);
  51413. return new BABYLON.Vector3(point.x, 0, point.y);
  51414. };
  51415. /**
  51416. * Moves the cursor ahead by the step amount
  51417. * @param step The amount to move the cursor forward
  51418. * @returns This path cursor
  51419. */
  51420. PathCursor.prototype.moveAhead = function (step) {
  51421. if (step === void 0) { step = 0.002; }
  51422. this.move(step);
  51423. return this;
  51424. };
  51425. /**
  51426. * Moves the cursor behind by the step amount
  51427. * @param step The amount to move the cursor back
  51428. * @returns This path cursor
  51429. */
  51430. PathCursor.prototype.moveBack = function (step) {
  51431. if (step === void 0) { step = 0.002; }
  51432. this.move(-step);
  51433. return this;
  51434. };
  51435. /**
  51436. * Moves the cursor by the step amount
  51437. * If the step amount is greater than one, an exception is thrown
  51438. * @param step The amount to move the cursor
  51439. * @returns This path cursor
  51440. */
  51441. PathCursor.prototype.move = function (step) {
  51442. if (Math.abs(step) > 1) {
  51443. throw "step size should be less than 1.";
  51444. }
  51445. this.value += step;
  51446. this.ensureLimits();
  51447. this.raiseOnChange();
  51448. return this;
  51449. };
  51450. /**
  51451. * Ensures that the value is limited between zero and one
  51452. * @returns This path cursor
  51453. */
  51454. PathCursor.prototype.ensureLimits = function () {
  51455. while (this.value > 1) {
  51456. this.value -= 1;
  51457. }
  51458. while (this.value < 0) {
  51459. this.value += 1;
  51460. }
  51461. return this;
  51462. };
  51463. /**
  51464. * Runs onchange callbacks on change (used by the animation engine)
  51465. * @returns This path cursor
  51466. */
  51467. PathCursor.prototype.raiseOnChange = function () {
  51468. var _this = this;
  51469. this._onchange.forEach(function (f) { return f(_this); });
  51470. return this;
  51471. };
  51472. /**
  51473. * Executes a function on change
  51474. * @param f A path cursor onchange callback
  51475. * @returns This path cursor
  51476. */
  51477. PathCursor.prototype.onchange = function (f) {
  51478. this._onchange.push(f);
  51479. return this;
  51480. };
  51481. return PathCursor;
  51482. }());
  51483. BABYLON.PathCursor = PathCursor;
  51484. /**
  51485. * Enum for the animation key frame interpolation type
  51486. */
  51487. var AnimationKeyInterpolation;
  51488. (function (AnimationKeyInterpolation) {
  51489. /**
  51490. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51491. */
  51492. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51493. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51494. /**
  51495. * Class used to store any kind of animation
  51496. */
  51497. var Animation = /** @class */ (function () {
  51498. /**
  51499. * Initializes the animation
  51500. * @param name Name of the animation
  51501. * @param targetProperty Property to animate
  51502. * @param framePerSecond The frames per second of the animation
  51503. * @param dataType The data type of the animation
  51504. * @param loopMode The loop mode of the animation
  51505. * @param enableBlendings Specifies if blending should be enabled
  51506. */
  51507. function Animation(
  51508. /**Name of the animation */
  51509. name,
  51510. /**Property to animate */
  51511. targetProperty,
  51512. /**The frames per second of the animation */
  51513. framePerSecond,
  51514. /**The data type of the animation */
  51515. dataType,
  51516. /**The loop mode of the animation */
  51517. loopMode,
  51518. /**Specifies if blending should be enabled */
  51519. enableBlending) {
  51520. this.name = name;
  51521. this.targetProperty = targetProperty;
  51522. this.framePerSecond = framePerSecond;
  51523. this.dataType = dataType;
  51524. this.loopMode = loopMode;
  51525. this.enableBlending = enableBlending;
  51526. /**
  51527. * @hidden Internal use only
  51528. */
  51529. this._runtimeAnimations = new Array();
  51530. /**
  51531. * The set of event that will be linked to this animation
  51532. */
  51533. this._events = new Array();
  51534. /**
  51535. * Stores the blending speed of the animation
  51536. */
  51537. this.blendingSpeed = 0.01;
  51538. /**
  51539. * Stores the animation ranges for the animation
  51540. */
  51541. this._ranges = {};
  51542. this.targetPropertyPath = targetProperty.split(".");
  51543. this.dataType = dataType;
  51544. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  51545. }
  51546. /**
  51547. * @hidden Internal use
  51548. */
  51549. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  51550. var dataType = undefined;
  51551. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  51552. dataType = Animation.ANIMATIONTYPE_FLOAT;
  51553. }
  51554. else if (from instanceof BABYLON.Quaternion) {
  51555. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  51556. }
  51557. else if (from instanceof BABYLON.Vector3) {
  51558. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  51559. }
  51560. else if (from instanceof BABYLON.Vector2) {
  51561. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  51562. }
  51563. else if (from instanceof BABYLON.Color3) {
  51564. dataType = Animation.ANIMATIONTYPE_COLOR3;
  51565. }
  51566. else if (from instanceof BABYLON.Size) {
  51567. dataType = Animation.ANIMATIONTYPE_SIZE;
  51568. }
  51569. if (dataType == undefined) {
  51570. return null;
  51571. }
  51572. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  51573. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  51574. animation.setKeys(keys);
  51575. if (easingFunction !== undefined) {
  51576. animation.setEasingFunction(easingFunction);
  51577. }
  51578. return animation;
  51579. };
  51580. /**
  51581. * Sets up an animation
  51582. * @param property The property to animate
  51583. * @param animationType The animation type to apply
  51584. * @param framePerSecond The frames per second of the animation
  51585. * @param easingFunction The easing function used in the animation
  51586. * @returns The created animation
  51587. */
  51588. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  51589. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  51590. animation.setEasingFunction(easingFunction);
  51591. return animation;
  51592. };
  51593. /**
  51594. * Create and start an animation on a node
  51595. * @param name defines the name of the global animation that will be run on all nodes
  51596. * @param node defines the root node where the animation will take place
  51597. * @param targetProperty defines property to animate
  51598. * @param framePerSecond defines the number of frame per second yo use
  51599. * @param totalFrame defines the number of frames in total
  51600. * @param from defines the initial value
  51601. * @param to defines the final value
  51602. * @param loopMode defines which loop mode you want to use (off by default)
  51603. * @param easingFunction defines the easing function to use (linear by default)
  51604. * @param onAnimationEnd defines the callback to call when animation end
  51605. * @returns the animatable created for this animation
  51606. */
  51607. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51608. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51609. if (!animation) {
  51610. return null;
  51611. }
  51612. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51613. };
  51614. /**
  51615. * Create and start an animation on a node and its descendants
  51616. * @param name defines the name of the global animation that will be run on all nodes
  51617. * @param node defines the root node where the animation will take place
  51618. * @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
  51619. * @param targetProperty defines property to animate
  51620. * @param framePerSecond defines the number of frame per second to use
  51621. * @param totalFrame defines the number of frames in total
  51622. * @param from defines the initial value
  51623. * @param to defines the final value
  51624. * @param loopMode defines which loop mode you want to use (off by default)
  51625. * @param easingFunction defines the easing function to use (linear by default)
  51626. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  51627. * @returns the list of animatables created for all nodes
  51628. * @example https://www.babylonjs-playground.com/#MH0VLI
  51629. */
  51630. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51631. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51632. if (!animation) {
  51633. return null;
  51634. }
  51635. var scene = node.getScene();
  51636. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51637. };
  51638. /**
  51639. * Creates a new animation, merges it with the existing animations and starts it
  51640. * @param name Name of the animation
  51641. * @param node Node which contains the scene that begins the animations
  51642. * @param targetProperty Specifies which property to animate
  51643. * @param framePerSecond The frames per second of the animation
  51644. * @param totalFrame The total number of frames
  51645. * @param from The frame at the beginning of the animation
  51646. * @param to The frame at the end of the animation
  51647. * @param loopMode Specifies the loop mode of the animation
  51648. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  51649. * @param onAnimationEnd Callback to run once the animation is complete
  51650. * @returns Nullable animation
  51651. */
  51652. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51653. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51654. if (!animation) {
  51655. return null;
  51656. }
  51657. node.animations.push(animation);
  51658. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51659. };
  51660. /**
  51661. * Transition property of an host to the target Value
  51662. * @param property The property to transition
  51663. * @param targetValue The target Value of the property
  51664. * @param host The object where the property to animate belongs
  51665. * @param scene Scene used to run the animation
  51666. * @param frameRate Framerate (in frame/s) to use
  51667. * @param transition The transition type we want to use
  51668. * @param duration The duration of the animation, in milliseconds
  51669. * @param onAnimationEnd Callback trigger at the end of the animation
  51670. * @returns Nullable animation
  51671. */
  51672. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  51673. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  51674. if (duration <= 0) {
  51675. host[property] = targetValue;
  51676. if (onAnimationEnd) {
  51677. onAnimationEnd();
  51678. }
  51679. return null;
  51680. }
  51681. var endFrame = frameRate * (duration / 1000);
  51682. transition.setKeys([{
  51683. frame: 0,
  51684. value: host[property].clone ? host[property].clone() : host[property]
  51685. },
  51686. {
  51687. frame: endFrame,
  51688. value: targetValue
  51689. }]);
  51690. if (!host.animations) {
  51691. host.animations = [];
  51692. }
  51693. host.animations.push(transition);
  51694. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51695. animation.onAnimationEnd = onAnimationEnd;
  51696. return animation;
  51697. };
  51698. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51699. /**
  51700. * Return the array of runtime animations currently using this animation
  51701. */
  51702. get: function () {
  51703. return this._runtimeAnimations;
  51704. },
  51705. enumerable: true,
  51706. configurable: true
  51707. });
  51708. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51709. /**
  51710. * Specifies if any of the runtime animations are currently running
  51711. */
  51712. get: function () {
  51713. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51714. var runtimeAnimation = _a[_i];
  51715. if (!runtimeAnimation.isStopped) {
  51716. return true;
  51717. }
  51718. }
  51719. return false;
  51720. },
  51721. enumerable: true,
  51722. configurable: true
  51723. });
  51724. // Methods
  51725. /**
  51726. * Converts the animation to a string
  51727. * @param fullDetails support for multiple levels of logging within scene loading
  51728. * @returns String form of the animation
  51729. */
  51730. Animation.prototype.toString = function (fullDetails) {
  51731. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51732. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51733. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51734. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51735. if (fullDetails) {
  51736. ret += ", Ranges: {";
  51737. var first = true;
  51738. for (var name in this._ranges) {
  51739. if (first) {
  51740. ret += ", ";
  51741. first = false;
  51742. }
  51743. ret += name;
  51744. }
  51745. ret += "}";
  51746. }
  51747. return ret;
  51748. };
  51749. /**
  51750. * Add an event to this animation
  51751. * @param event Event to add
  51752. */
  51753. Animation.prototype.addEvent = function (event) {
  51754. this._events.push(event);
  51755. };
  51756. /**
  51757. * Remove all events found at the given frame
  51758. * @param frame The frame to remove events from
  51759. */
  51760. Animation.prototype.removeEvents = function (frame) {
  51761. for (var index = 0; index < this._events.length; index++) {
  51762. if (this._events[index].frame === frame) {
  51763. this._events.splice(index, 1);
  51764. index--;
  51765. }
  51766. }
  51767. };
  51768. /**
  51769. * Retrieves all the events from the animation
  51770. * @returns Events from the animation
  51771. */
  51772. Animation.prototype.getEvents = function () {
  51773. return this._events;
  51774. };
  51775. /**
  51776. * Creates an animation range
  51777. * @param name Name of the animation range
  51778. * @param from Starting frame of the animation range
  51779. * @param to Ending frame of the animation
  51780. */
  51781. Animation.prototype.createRange = function (name, from, to) {
  51782. // check name not already in use; could happen for bones after serialized
  51783. if (!this._ranges[name]) {
  51784. this._ranges[name] = new AnimationRange(name, from, to);
  51785. }
  51786. };
  51787. /**
  51788. * Deletes an animation range by name
  51789. * @param name Name of the animation range to delete
  51790. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51791. */
  51792. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51793. if (deleteFrames === void 0) { deleteFrames = true; }
  51794. var range = this._ranges[name];
  51795. if (!range) {
  51796. return;
  51797. }
  51798. if (deleteFrames) {
  51799. var from = range.from;
  51800. var to = range.to;
  51801. // this loop MUST go high to low for multiple splices to work
  51802. for (var key = this._keys.length - 1; key >= 0; key--) {
  51803. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51804. this._keys.splice(key, 1);
  51805. }
  51806. }
  51807. }
  51808. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51809. };
  51810. /**
  51811. * Gets the animation range by name, or null if not defined
  51812. * @param name Name of the animation range
  51813. * @returns Nullable animation range
  51814. */
  51815. Animation.prototype.getRange = function (name) {
  51816. return this._ranges[name];
  51817. };
  51818. /**
  51819. * Gets the key frames from the animation
  51820. * @returns The key frames of the animation
  51821. */
  51822. Animation.prototype.getKeys = function () {
  51823. return this._keys;
  51824. };
  51825. /**
  51826. * Gets the highest frame rate of the animation
  51827. * @returns Highest frame rate of the animation
  51828. */
  51829. Animation.prototype.getHighestFrame = function () {
  51830. var ret = 0;
  51831. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51832. if (ret < this._keys[key].frame) {
  51833. ret = this._keys[key].frame;
  51834. }
  51835. }
  51836. return ret;
  51837. };
  51838. /**
  51839. * Gets the easing function of the animation
  51840. * @returns Easing function of the animation
  51841. */
  51842. Animation.prototype.getEasingFunction = function () {
  51843. return this._easingFunction;
  51844. };
  51845. /**
  51846. * Sets the easing function of the animation
  51847. * @param easingFunction A custom mathematical formula for animation
  51848. */
  51849. Animation.prototype.setEasingFunction = function (easingFunction) {
  51850. this._easingFunction = easingFunction;
  51851. };
  51852. /**
  51853. * Interpolates a scalar linearly
  51854. * @param startValue Start value of the animation curve
  51855. * @param endValue End value of the animation curve
  51856. * @param gradient Scalar amount to interpolate
  51857. * @returns Interpolated scalar value
  51858. */
  51859. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51860. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51861. };
  51862. /**
  51863. * Interpolates a scalar cubically
  51864. * @param startValue Start value of the animation curve
  51865. * @param outTangent End tangent of the animation
  51866. * @param endValue End value of the animation curve
  51867. * @param inTangent Start tangent of the animation curve
  51868. * @param gradient Scalar amount to interpolate
  51869. * @returns Interpolated scalar value
  51870. */
  51871. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51872. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51873. };
  51874. /**
  51875. * Interpolates a quaternion using a spherical linear interpolation
  51876. * @param startValue Start value of the animation curve
  51877. * @param endValue End value of the animation curve
  51878. * @param gradient Scalar amount to interpolate
  51879. * @returns Interpolated quaternion value
  51880. */
  51881. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51882. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51883. };
  51884. /**
  51885. * Interpolates a quaternion cubically
  51886. * @param startValue Start value of the animation curve
  51887. * @param outTangent End tangent of the animation curve
  51888. * @param endValue End value of the animation curve
  51889. * @param inTangent Start tangent of the animation curve
  51890. * @param gradient Scalar amount to interpolate
  51891. * @returns Interpolated quaternion value
  51892. */
  51893. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51894. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51895. };
  51896. /**
  51897. * Interpolates a Vector3 linearl
  51898. * @param startValue Start value of the animation curve
  51899. * @param endValue End value of the animation curve
  51900. * @param gradient Scalar amount to interpolate
  51901. * @returns Interpolated scalar value
  51902. */
  51903. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51904. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51905. };
  51906. /**
  51907. * Interpolates a Vector3 cubically
  51908. * @param startValue Start value of the animation curve
  51909. * @param outTangent End tangent of the animation
  51910. * @param endValue End value of the animation curve
  51911. * @param inTangent Start tangent of the animation curve
  51912. * @param gradient Scalar amount to interpolate
  51913. * @returns InterpolatedVector3 value
  51914. */
  51915. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51916. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51917. };
  51918. /**
  51919. * Interpolates a Vector2 linearly
  51920. * @param startValue Start value of the animation curve
  51921. * @param endValue End value of the animation curve
  51922. * @param gradient Scalar amount to interpolate
  51923. * @returns Interpolated Vector2 value
  51924. */
  51925. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51926. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51927. };
  51928. /**
  51929. * Interpolates a Vector2 cubically
  51930. * @param startValue Start value of the animation curve
  51931. * @param outTangent End tangent of the animation
  51932. * @param endValue End value of the animation curve
  51933. * @param inTangent Start tangent of the animation curve
  51934. * @param gradient Scalar amount to interpolate
  51935. * @returns Interpolated Vector2 value
  51936. */
  51937. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51938. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51939. };
  51940. /**
  51941. * Interpolates a size linearly
  51942. * @param startValue Start value of the animation curve
  51943. * @param endValue End value of the animation curve
  51944. * @param gradient Scalar amount to interpolate
  51945. * @returns Interpolated Size value
  51946. */
  51947. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51948. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51949. };
  51950. /**
  51951. * Interpolates a Color3 linearly
  51952. * @param startValue Start value of the animation curve
  51953. * @param endValue End value of the animation curve
  51954. * @param gradient Scalar amount to interpolate
  51955. * @returns Interpolated Color3 value
  51956. */
  51957. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51958. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51959. };
  51960. /**
  51961. * @hidden Internal use only
  51962. */
  51963. Animation.prototype._getKeyValue = function (value) {
  51964. if (typeof value === "function") {
  51965. return value();
  51966. }
  51967. return value;
  51968. };
  51969. /**
  51970. * @hidden Internal use only
  51971. */
  51972. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51973. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51974. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51975. }
  51976. var keys = this.getKeys();
  51977. // Try to get a hash to find the right key
  51978. 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));
  51979. if (keys[startKeyIndex].frame >= currentFrame) {
  51980. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51981. startKeyIndex--;
  51982. }
  51983. }
  51984. for (var key = startKeyIndex; key < keys.length; key++) {
  51985. var endKey = keys[key + 1];
  51986. if (endKey.frame >= currentFrame) {
  51987. var startKey = keys[key];
  51988. var startValue = this._getKeyValue(startKey.value);
  51989. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51990. return startValue;
  51991. }
  51992. var endValue = this._getKeyValue(endKey.value);
  51993. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51994. var frameDelta = endKey.frame - startKey.frame;
  51995. // gradient : percent of currentFrame between the frame inf and the frame sup
  51996. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51997. // check for easingFunction and correction of gradient
  51998. var easingFunction = this.getEasingFunction();
  51999. if (easingFunction != null) {
  52000. gradient = easingFunction.ease(gradient);
  52001. }
  52002. switch (this.dataType) {
  52003. // Float
  52004. case Animation.ANIMATIONTYPE_FLOAT:
  52005. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52006. switch (loopMode) {
  52007. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52008. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52009. return floatValue;
  52010. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52011. return offsetValue * repeatCount + floatValue;
  52012. }
  52013. break;
  52014. // Quaternion
  52015. case Animation.ANIMATIONTYPE_QUATERNION:
  52016. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52017. switch (loopMode) {
  52018. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52019. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52020. return quatValue;
  52021. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52022. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52023. }
  52024. return quatValue;
  52025. // Vector3
  52026. case Animation.ANIMATIONTYPE_VECTOR3:
  52027. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52028. switch (loopMode) {
  52029. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52030. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52031. return vec3Value;
  52032. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52033. return vec3Value.add(offsetValue.scale(repeatCount));
  52034. }
  52035. // Vector2
  52036. case Animation.ANIMATIONTYPE_VECTOR2:
  52037. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52038. switch (loopMode) {
  52039. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52040. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52041. return vec2Value;
  52042. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52043. return vec2Value.add(offsetValue.scale(repeatCount));
  52044. }
  52045. // Size
  52046. case Animation.ANIMATIONTYPE_SIZE:
  52047. switch (loopMode) {
  52048. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52049. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52050. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52051. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52052. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52053. }
  52054. // Color3
  52055. case Animation.ANIMATIONTYPE_COLOR3:
  52056. switch (loopMode) {
  52057. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52058. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52059. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52060. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52061. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52062. }
  52063. // Matrix
  52064. case Animation.ANIMATIONTYPE_MATRIX:
  52065. switch (loopMode) {
  52066. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52067. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52068. if (Animation.AllowMatricesInterpolation) {
  52069. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52070. }
  52071. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52072. return startValue;
  52073. }
  52074. default:
  52075. break;
  52076. }
  52077. break;
  52078. }
  52079. }
  52080. return this._getKeyValue(keys[keys.length - 1].value);
  52081. };
  52082. /**
  52083. * Defines the function to use to interpolate matrices
  52084. * @param startValue defines the start matrix
  52085. * @param endValue defines the end matrix
  52086. * @param gradient defines the gradient between both matrices
  52087. * @param result defines an optional target matrix where to store the interpolation
  52088. * @returns the interpolated matrix
  52089. */
  52090. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52091. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52092. if (result) {
  52093. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52094. return result;
  52095. }
  52096. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52097. }
  52098. if (result) {
  52099. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52100. return result;
  52101. }
  52102. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52103. };
  52104. /**
  52105. * Makes a copy of the animation
  52106. * @returns Cloned animation
  52107. */
  52108. Animation.prototype.clone = function () {
  52109. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52110. clone.enableBlending = this.enableBlending;
  52111. clone.blendingSpeed = this.blendingSpeed;
  52112. if (this._keys) {
  52113. clone.setKeys(this._keys);
  52114. }
  52115. if (this._ranges) {
  52116. clone._ranges = {};
  52117. for (var name in this._ranges) {
  52118. var range = this._ranges[name];
  52119. if (!range) {
  52120. continue;
  52121. }
  52122. clone._ranges[name] = range.clone();
  52123. }
  52124. }
  52125. return clone;
  52126. };
  52127. /**
  52128. * Sets the key frames of the animation
  52129. * @param values The animation key frames to set
  52130. */
  52131. Animation.prototype.setKeys = function (values) {
  52132. this._keys = values.slice(0);
  52133. };
  52134. /**
  52135. * Serializes the animation to an object
  52136. * @returns Serialized object
  52137. */
  52138. Animation.prototype.serialize = function () {
  52139. var serializationObject = {};
  52140. serializationObject.name = this.name;
  52141. serializationObject.property = this.targetProperty;
  52142. serializationObject.framePerSecond = this.framePerSecond;
  52143. serializationObject.dataType = this.dataType;
  52144. serializationObject.loopBehavior = this.loopMode;
  52145. serializationObject.enableBlending = this.enableBlending;
  52146. serializationObject.blendingSpeed = this.blendingSpeed;
  52147. var dataType = this.dataType;
  52148. serializationObject.keys = [];
  52149. var keys = this.getKeys();
  52150. for (var index = 0; index < keys.length; index++) {
  52151. var animationKey = keys[index];
  52152. var key = {};
  52153. key.frame = animationKey.frame;
  52154. switch (dataType) {
  52155. case Animation.ANIMATIONTYPE_FLOAT:
  52156. key.values = [animationKey.value];
  52157. break;
  52158. case Animation.ANIMATIONTYPE_QUATERNION:
  52159. case Animation.ANIMATIONTYPE_MATRIX:
  52160. case Animation.ANIMATIONTYPE_VECTOR3:
  52161. case Animation.ANIMATIONTYPE_COLOR3:
  52162. key.values = animationKey.value.asArray();
  52163. break;
  52164. }
  52165. serializationObject.keys.push(key);
  52166. }
  52167. serializationObject.ranges = [];
  52168. for (var name in this._ranges) {
  52169. var source = this._ranges[name];
  52170. if (!source) {
  52171. continue;
  52172. }
  52173. var range = {};
  52174. range.name = name;
  52175. range.from = source.from;
  52176. range.to = source.to;
  52177. serializationObject.ranges.push(range);
  52178. }
  52179. return serializationObject;
  52180. };
  52181. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52182. /**
  52183. * Get the float animation type
  52184. */
  52185. get: function () {
  52186. return Animation._ANIMATIONTYPE_FLOAT;
  52187. },
  52188. enumerable: true,
  52189. configurable: true
  52190. });
  52191. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52192. /**
  52193. * Get the Vector3 animation type
  52194. */
  52195. get: function () {
  52196. return Animation._ANIMATIONTYPE_VECTOR3;
  52197. },
  52198. enumerable: true,
  52199. configurable: true
  52200. });
  52201. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52202. /**
  52203. * Get the Vector2 animation type
  52204. */
  52205. get: function () {
  52206. return Animation._ANIMATIONTYPE_VECTOR2;
  52207. },
  52208. enumerable: true,
  52209. configurable: true
  52210. });
  52211. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52212. /**
  52213. * Get the Size animation type
  52214. */
  52215. get: function () {
  52216. return Animation._ANIMATIONTYPE_SIZE;
  52217. },
  52218. enumerable: true,
  52219. configurable: true
  52220. });
  52221. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52222. /**
  52223. * Get the Quaternion animation type
  52224. */
  52225. get: function () {
  52226. return Animation._ANIMATIONTYPE_QUATERNION;
  52227. },
  52228. enumerable: true,
  52229. configurable: true
  52230. });
  52231. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52232. /**
  52233. * Get the Matrix animation type
  52234. */
  52235. get: function () {
  52236. return Animation._ANIMATIONTYPE_MATRIX;
  52237. },
  52238. enumerable: true,
  52239. configurable: true
  52240. });
  52241. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52242. /**
  52243. * Get the Color3 animation type
  52244. */
  52245. get: function () {
  52246. return Animation._ANIMATIONTYPE_COLOR3;
  52247. },
  52248. enumerable: true,
  52249. configurable: true
  52250. });
  52251. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52252. /**
  52253. * Get the Relative Loop Mode
  52254. */
  52255. get: function () {
  52256. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52257. },
  52258. enumerable: true,
  52259. configurable: true
  52260. });
  52261. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52262. /**
  52263. * Get the Cycle Loop Mode
  52264. */
  52265. get: function () {
  52266. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52267. },
  52268. enumerable: true,
  52269. configurable: true
  52270. });
  52271. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52272. /**
  52273. * Get the Constant Loop Mode
  52274. */
  52275. get: function () {
  52276. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52277. },
  52278. enumerable: true,
  52279. configurable: true
  52280. });
  52281. /** @hidden */
  52282. Animation._UniversalLerp = function (left, right, amount) {
  52283. var constructor = left.constructor;
  52284. if (constructor.Lerp) { // Lerp supported
  52285. return constructor.Lerp(left, right, amount);
  52286. }
  52287. else if (constructor.Slerp) { // Slerp supported
  52288. return constructor.Slerp(left, right, amount);
  52289. }
  52290. else if (left.toFixed) { // Number
  52291. return left * (1.0 - amount) + amount * right;
  52292. }
  52293. else { // Blending not supported
  52294. return right;
  52295. }
  52296. };
  52297. /**
  52298. * Parses an animation object and creates an animation
  52299. * @param parsedAnimation Parsed animation object
  52300. * @returns Animation object
  52301. */
  52302. Animation.Parse = function (parsedAnimation) {
  52303. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52304. var dataType = parsedAnimation.dataType;
  52305. var keys = [];
  52306. var data;
  52307. var index;
  52308. if (parsedAnimation.enableBlending) {
  52309. animation.enableBlending = parsedAnimation.enableBlending;
  52310. }
  52311. if (parsedAnimation.blendingSpeed) {
  52312. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52313. }
  52314. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52315. var key = parsedAnimation.keys[index];
  52316. var inTangent;
  52317. var outTangent;
  52318. switch (dataType) {
  52319. case Animation.ANIMATIONTYPE_FLOAT:
  52320. data = key.values[0];
  52321. if (key.values.length >= 1) {
  52322. inTangent = key.values[1];
  52323. }
  52324. if (key.values.length >= 2) {
  52325. outTangent = key.values[2];
  52326. }
  52327. break;
  52328. case Animation.ANIMATIONTYPE_QUATERNION:
  52329. data = BABYLON.Quaternion.FromArray(key.values);
  52330. if (key.values.length >= 8) {
  52331. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52332. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52333. inTangent = _inTangent;
  52334. }
  52335. }
  52336. if (key.values.length >= 12) {
  52337. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52338. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52339. outTangent = _outTangent;
  52340. }
  52341. }
  52342. break;
  52343. case Animation.ANIMATIONTYPE_MATRIX:
  52344. data = BABYLON.Matrix.FromArray(key.values);
  52345. break;
  52346. case Animation.ANIMATIONTYPE_COLOR3:
  52347. data = BABYLON.Color3.FromArray(key.values);
  52348. break;
  52349. case Animation.ANIMATIONTYPE_VECTOR3:
  52350. default:
  52351. data = BABYLON.Vector3.FromArray(key.values);
  52352. break;
  52353. }
  52354. var keyData = {};
  52355. keyData.frame = key.frame;
  52356. keyData.value = data;
  52357. if (inTangent != undefined) {
  52358. keyData.inTangent = inTangent;
  52359. }
  52360. if (outTangent != undefined) {
  52361. keyData.outTangent = outTangent;
  52362. }
  52363. keys.push(keyData);
  52364. }
  52365. animation.setKeys(keys);
  52366. if (parsedAnimation.ranges) {
  52367. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52368. data = parsedAnimation.ranges[index];
  52369. animation.createRange(data.name, data.from, data.to);
  52370. }
  52371. }
  52372. return animation;
  52373. };
  52374. /**
  52375. * Appends the serialized animations from the source animations
  52376. * @param source Source containing the animations
  52377. * @param destination Target to store the animations
  52378. */
  52379. Animation.AppendSerializedAnimations = function (source, destination) {
  52380. if (source.animations) {
  52381. destination.animations = [];
  52382. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52383. var animation = source.animations[animationIndex];
  52384. destination.animations.push(animation.serialize());
  52385. }
  52386. }
  52387. };
  52388. /**
  52389. * Use matrix interpolation instead of using direct key value when animating matrices
  52390. */
  52391. Animation.AllowMatricesInterpolation = false;
  52392. /**
  52393. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52394. */
  52395. Animation.AllowMatrixDecomposeForInterpolation = true;
  52396. // Statics
  52397. /**
  52398. * Float animation type
  52399. */
  52400. Animation._ANIMATIONTYPE_FLOAT = 0;
  52401. /**
  52402. * Vector3 animation type
  52403. */
  52404. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52405. /**
  52406. * Quaternion animation type
  52407. */
  52408. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52409. /**
  52410. * Matrix animation type
  52411. */
  52412. Animation._ANIMATIONTYPE_MATRIX = 3;
  52413. /**
  52414. * Color3 animation type
  52415. */
  52416. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52417. /**
  52418. * Vector2 animation type
  52419. */
  52420. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52421. /**
  52422. * Size animation type
  52423. */
  52424. Animation._ANIMATIONTYPE_SIZE = 6;
  52425. /**
  52426. * Relative Loop Mode
  52427. */
  52428. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52429. /**
  52430. * Cycle Loop Mode
  52431. */
  52432. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52433. /**
  52434. * Constant Loop Mode
  52435. */
  52436. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52437. return Animation;
  52438. }());
  52439. BABYLON.Animation = Animation;
  52440. })(BABYLON || (BABYLON = {}));
  52441. //# sourceMappingURL=babylon.animation.js.map
  52442. var BABYLON;
  52443. (function (BABYLON) {
  52444. /**
  52445. * This class defines the direct association between an animation and a target
  52446. */
  52447. var TargetedAnimation = /** @class */ (function () {
  52448. function TargetedAnimation() {
  52449. }
  52450. return TargetedAnimation;
  52451. }());
  52452. BABYLON.TargetedAnimation = TargetedAnimation;
  52453. /**
  52454. * Use this class to create coordinated animations on multiple targets
  52455. */
  52456. var AnimationGroup = /** @class */ (function () {
  52457. /**
  52458. * Instantiates a new Animation Group.
  52459. * This helps managing several animations at once.
  52460. * @see http://doc.babylonjs.com/how_to/group
  52461. * @param name Defines the name of the group
  52462. * @param scene Defines the scene the group belongs to
  52463. */
  52464. function AnimationGroup(
  52465. /** The name of the animation group */
  52466. name, scene) {
  52467. if (scene === void 0) { scene = null; }
  52468. this.name = name;
  52469. this._targetedAnimations = new Array();
  52470. this._animatables = new Array();
  52471. this._from = Number.MAX_VALUE;
  52472. this._to = -Number.MAX_VALUE;
  52473. this._speedRatio = 1;
  52474. /**
  52475. * This observable will notify when one animation have ended.
  52476. */
  52477. this.onAnimationEndObservable = new BABYLON.Observable();
  52478. /**
  52479. * This observable will notify when all animations have ended.
  52480. */
  52481. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52482. /**
  52483. * This observable will notify when all animations have paused.
  52484. */
  52485. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52486. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52487. this._scene.animationGroups.push(this);
  52488. }
  52489. Object.defineProperty(AnimationGroup.prototype, "from", {
  52490. /**
  52491. * Gets the first frame
  52492. */
  52493. get: function () {
  52494. return this._from;
  52495. },
  52496. enumerable: true,
  52497. configurable: true
  52498. });
  52499. Object.defineProperty(AnimationGroup.prototype, "to", {
  52500. /**
  52501. * Gets the last frame
  52502. */
  52503. get: function () {
  52504. return this._to;
  52505. },
  52506. enumerable: true,
  52507. configurable: true
  52508. });
  52509. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52510. /**
  52511. * Define if the animations are started
  52512. */
  52513. get: function () {
  52514. return this._isStarted;
  52515. },
  52516. enumerable: true,
  52517. configurable: true
  52518. });
  52519. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52520. /**
  52521. * Gets or sets the speed ratio to use for all animations
  52522. */
  52523. get: function () {
  52524. return this._speedRatio;
  52525. },
  52526. /**
  52527. * Gets or sets the speed ratio to use for all animations
  52528. */
  52529. set: function (value) {
  52530. if (this._speedRatio === value) {
  52531. return;
  52532. }
  52533. this._speedRatio = value;
  52534. for (var index = 0; index < this._animatables.length; index++) {
  52535. var animatable = this._animatables[index];
  52536. animatable.speedRatio = this._speedRatio;
  52537. }
  52538. },
  52539. enumerable: true,
  52540. configurable: true
  52541. });
  52542. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  52543. /**
  52544. * Gets the targeted animations for this animation group
  52545. */
  52546. get: function () {
  52547. return this._targetedAnimations;
  52548. },
  52549. enumerable: true,
  52550. configurable: true
  52551. });
  52552. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  52553. /**
  52554. * returning the list of animatables controlled by this animation group.
  52555. */
  52556. get: function () {
  52557. return this._animatables;
  52558. },
  52559. enumerable: true,
  52560. configurable: true
  52561. });
  52562. /**
  52563. * Add an animation (with its target) in the group
  52564. * @param animation defines the animation we want to add
  52565. * @param target defines the target of the animation
  52566. * @returns the {BABYLON.TargetedAnimation} object
  52567. */
  52568. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  52569. var targetedAnimation = {
  52570. animation: animation,
  52571. target: target
  52572. };
  52573. var keys = animation.getKeys();
  52574. if (this._from > keys[0].frame) {
  52575. this._from = keys[0].frame;
  52576. }
  52577. if (this._to < keys[keys.length - 1].frame) {
  52578. this._to = keys[keys.length - 1].frame;
  52579. }
  52580. this._targetedAnimations.push(targetedAnimation);
  52581. return targetedAnimation;
  52582. };
  52583. /**
  52584. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  52585. * It can add constant keys at begin or end
  52586. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  52587. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  52588. * @returns the animation group
  52589. */
  52590. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  52591. if (beginFrame === void 0) { beginFrame = null; }
  52592. if (endFrame === void 0) { endFrame = null; }
  52593. if (beginFrame == null)
  52594. beginFrame = this._from;
  52595. if (endFrame == null)
  52596. endFrame = this._to;
  52597. for (var index = 0; index < this._targetedAnimations.length; index++) {
  52598. var targetedAnimation = this._targetedAnimations[index];
  52599. var keys = targetedAnimation.animation.getKeys();
  52600. var startKey = keys[0];
  52601. var endKey = keys[keys.length - 1];
  52602. if (startKey.frame > beginFrame) {
  52603. var newKey = {
  52604. frame: beginFrame,
  52605. value: startKey.value,
  52606. inTangent: startKey.inTangent,
  52607. outTangent: startKey.outTangent,
  52608. interpolation: startKey.interpolation
  52609. };
  52610. keys.splice(0, 0, newKey);
  52611. }
  52612. if (endKey.frame < endFrame) {
  52613. var newKey = {
  52614. frame: endFrame,
  52615. value: endKey.value,
  52616. inTangent: endKey.outTangent,
  52617. outTangent: endKey.outTangent,
  52618. interpolation: endKey.interpolation
  52619. };
  52620. keys.push(newKey);
  52621. }
  52622. }
  52623. this._from = beginFrame;
  52624. this._to = endFrame;
  52625. return this;
  52626. };
  52627. /**
  52628. * Start all animations on given targets
  52629. * @param loop defines if animations must loop
  52630. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  52631. * @param from defines the from key (optional)
  52632. * @param to defines the to key (optional)
  52633. * @returns the current animation group
  52634. */
  52635. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  52636. var _this = this;
  52637. if (loop === void 0) { loop = false; }
  52638. if (speedRatio === void 0) { speedRatio = 1; }
  52639. if (this._isStarted || this._targetedAnimations.length === 0) {
  52640. return this;
  52641. }
  52642. var _loop_1 = function (targetedAnimation) {
  52643. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  52644. animatable.onAnimationEnd = function () {
  52645. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  52646. _this._checkAnimationGroupEnded(animatable);
  52647. };
  52648. this_1._animatables.push(animatable);
  52649. };
  52650. var this_1 = this;
  52651. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  52652. var targetedAnimation = _a[_i];
  52653. _loop_1(targetedAnimation);
  52654. }
  52655. this._speedRatio = speedRatio;
  52656. this._isStarted = true;
  52657. return this;
  52658. };
  52659. /**
  52660. * Pause all animations
  52661. * @returns the animation group
  52662. */
  52663. AnimationGroup.prototype.pause = function () {
  52664. if (!this._isStarted) {
  52665. return this;
  52666. }
  52667. for (var index = 0; index < this._animatables.length; index++) {
  52668. var animatable = this._animatables[index];
  52669. animatable.pause();
  52670. }
  52671. this.onAnimationGroupPauseObservable.notifyObservers(this);
  52672. return this;
  52673. };
  52674. /**
  52675. * Play all animations to initial state
  52676. * This function will start() the animations if they were not started or will restart() them if they were paused
  52677. * @param loop defines if animations must loop
  52678. * @returns the animation group
  52679. */
  52680. AnimationGroup.prototype.play = function (loop) {
  52681. // only if all animatables are ready and exist
  52682. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  52683. if (loop !== undefined) {
  52684. for (var index = 0; index < this._animatables.length; index++) {
  52685. var animatable = this._animatables[index];
  52686. animatable.loopAnimation = loop;
  52687. }
  52688. }
  52689. this.restart();
  52690. }
  52691. else {
  52692. this.stop();
  52693. this.start(loop, this._speedRatio);
  52694. }
  52695. return this;
  52696. };
  52697. /**
  52698. * Reset all animations to initial state
  52699. * @returns the animation group
  52700. */
  52701. AnimationGroup.prototype.reset = function () {
  52702. if (!this._isStarted) {
  52703. return this;
  52704. }
  52705. for (var index = 0; index < this._animatables.length; index++) {
  52706. var animatable = this._animatables[index];
  52707. animatable.reset();
  52708. }
  52709. return this;
  52710. };
  52711. /**
  52712. * Restart animations from key 0
  52713. * @returns the animation group
  52714. */
  52715. AnimationGroup.prototype.restart = function () {
  52716. if (!this._isStarted) {
  52717. return this;
  52718. }
  52719. for (var index = 0; index < this._animatables.length; index++) {
  52720. var animatable = this._animatables[index];
  52721. animatable.restart();
  52722. }
  52723. return this;
  52724. };
  52725. /**
  52726. * Stop all animations
  52727. * @returns the animation group
  52728. */
  52729. AnimationGroup.prototype.stop = function () {
  52730. if (!this._isStarted) {
  52731. return this;
  52732. }
  52733. var list = this._animatables.slice();
  52734. for (var index = 0; index < list.length; index++) {
  52735. list[index].stop();
  52736. }
  52737. this._isStarted = false;
  52738. return this;
  52739. };
  52740. /**
  52741. * Set animation weight for all animatables
  52742. * @param weight defines the weight to use
  52743. * @return the animationGroup
  52744. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52745. */
  52746. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52747. for (var index = 0; index < this._animatables.length; index++) {
  52748. var animatable = this._animatables[index];
  52749. animatable.weight = weight;
  52750. }
  52751. return this;
  52752. };
  52753. /**
  52754. * Synchronize and normalize all animatables with a source animatable
  52755. * @param root defines the root animatable to synchronize with
  52756. * @return the animationGroup
  52757. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52758. */
  52759. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52760. for (var index = 0; index < this._animatables.length; index++) {
  52761. var animatable = this._animatables[index];
  52762. animatable.syncWith(root);
  52763. }
  52764. return this;
  52765. };
  52766. /**
  52767. * Goes to a specific frame in this animation group
  52768. * @param frame the frame number to go to
  52769. * @return the animationGroup
  52770. */
  52771. AnimationGroup.prototype.goToFrame = function (frame) {
  52772. if (!this._isStarted) {
  52773. return this;
  52774. }
  52775. for (var index = 0; index < this._animatables.length; index++) {
  52776. var animatable = this._animatables[index];
  52777. animatable.goToFrame(frame);
  52778. }
  52779. return this;
  52780. };
  52781. /**
  52782. * Dispose all associated resources
  52783. */
  52784. AnimationGroup.prototype.dispose = function () {
  52785. this._targetedAnimations = [];
  52786. this._animatables = [];
  52787. var index = this._scene.animationGroups.indexOf(this);
  52788. if (index > -1) {
  52789. this._scene.animationGroups.splice(index, 1);
  52790. }
  52791. };
  52792. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52793. // animatable should be taken out of the array
  52794. var idx = this._animatables.indexOf(animatable);
  52795. if (idx > -1) {
  52796. this._animatables.splice(idx, 1);
  52797. }
  52798. // all animatables were removed? animation group ended!
  52799. if (this._animatables.length === 0) {
  52800. this._isStarted = false;
  52801. this.onAnimationGroupEndObservable.notifyObservers(this);
  52802. }
  52803. };
  52804. // Statics
  52805. /**
  52806. * Returns a new AnimationGroup object parsed from the source provided.
  52807. * @param parsedAnimationGroup defines the source
  52808. * @param scene defines the scene that will receive the animationGroup
  52809. * @returns a new AnimationGroup
  52810. */
  52811. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  52812. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  52813. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  52814. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  52815. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  52816. var id = targetedAnimation.targetId;
  52817. var targetNode = scene.getNodeByID(id);
  52818. if (targetNode != null)
  52819. animationGroup.addTargetedAnimation(animation, targetNode);
  52820. }
  52821. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  52822. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  52823. return animationGroup;
  52824. };
  52825. /**
  52826. * Returns the string "AnimationGroup"
  52827. * @returns "AnimationGroup"
  52828. */
  52829. AnimationGroup.prototype.getClassName = function () {
  52830. return "AnimationGroup";
  52831. };
  52832. /**
  52833. * Creates a detailled string about the object
  52834. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  52835. * @returns a string representing the object
  52836. */
  52837. AnimationGroup.prototype.toString = function (fullDetails) {
  52838. var ret = "Name: " + this.name;
  52839. ret += ", type: " + this.getClassName();
  52840. if (fullDetails) {
  52841. ret += ", from: " + this._from;
  52842. ret += ", to: " + this._to;
  52843. ret += ", isStarted: " + this._isStarted;
  52844. ret += ", speedRatio: " + this._speedRatio;
  52845. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  52846. ret += ", animatables length: " + this._animatables;
  52847. }
  52848. return ret;
  52849. };
  52850. return AnimationGroup;
  52851. }());
  52852. BABYLON.AnimationGroup = AnimationGroup;
  52853. })(BABYLON || (BABYLON = {}));
  52854. //# sourceMappingURL=babylon.animationGroup.js.map
  52855. var BABYLON;
  52856. (function (BABYLON) {
  52857. // Static values to help the garbage collector
  52858. // Quaternion
  52859. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  52860. // Vector3
  52861. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  52862. // Vector2
  52863. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  52864. // Size
  52865. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  52866. // Color3
  52867. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  52868. /**
  52869. * Defines a runtime animation
  52870. */
  52871. var RuntimeAnimation = /** @class */ (function () {
  52872. /**
  52873. * Create a new RuntimeAnimation object
  52874. * @param target defines the target of the animation
  52875. * @param animation defines the source animation object
  52876. * @param scene defines the hosting scene
  52877. * @param host defines the initiating Animatable
  52878. */
  52879. function RuntimeAnimation(target, animation, scene, host) {
  52880. var _this = this;
  52881. this._events = new Array();
  52882. /**
  52883. * The current frame of the runtime animation
  52884. */
  52885. this._currentFrame = 0;
  52886. /**
  52887. * The original value of the runtime animation
  52888. */
  52889. this._originalValue = new Array();
  52890. /**
  52891. * The offsets cache of the runtime animation
  52892. */
  52893. this._offsetsCache = {};
  52894. /**
  52895. * The high limits cache of the runtime animation
  52896. */
  52897. this._highLimitsCache = {};
  52898. /**
  52899. * Specifies if the runtime animation has been stopped
  52900. */
  52901. this._stopped = false;
  52902. /**
  52903. * The blending factor of the runtime animation
  52904. */
  52905. this._blendingFactor = 0;
  52906. /**
  52907. * The target path of the runtime animation
  52908. */
  52909. this._targetPath = "";
  52910. /**
  52911. * The weight of the runtime animation
  52912. */
  52913. this._weight = 1.0;
  52914. /**
  52915. * The ratio offset of the runtime animation
  52916. */
  52917. this._ratioOffset = 0;
  52918. /**
  52919. * The previous delay of the runtime animation
  52920. */
  52921. this._previousDelay = 0;
  52922. /**
  52923. * The previous ratio of the runtime animation
  52924. */
  52925. this._previousRatio = 0;
  52926. this._animation = animation;
  52927. this._target = target;
  52928. this._scene = scene;
  52929. this._host = host;
  52930. animation._runtimeAnimations.push(this);
  52931. // Cloning events locally
  52932. var events = animation.getEvents();
  52933. if (events && events.length > 0) {
  52934. events.forEach(function (e) {
  52935. _this._events.push(e._clone());
  52936. });
  52937. }
  52938. }
  52939. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52940. /**
  52941. * Gets the current frame of the runtime animation
  52942. */
  52943. get: function () {
  52944. return this._currentFrame;
  52945. },
  52946. enumerable: true,
  52947. configurable: true
  52948. });
  52949. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52950. /**
  52951. * Gets the weight of the runtime animation
  52952. */
  52953. get: function () {
  52954. return this._weight;
  52955. },
  52956. enumerable: true,
  52957. configurable: true
  52958. });
  52959. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52960. /**
  52961. * Gets the current value of the runtime animation
  52962. */
  52963. get: function () {
  52964. return this._currentValue;
  52965. },
  52966. enumerable: true,
  52967. configurable: true
  52968. });
  52969. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52970. /**
  52971. * Gets the target path of the runtime animation
  52972. */
  52973. get: function () {
  52974. return this._targetPath;
  52975. },
  52976. enumerable: true,
  52977. configurable: true
  52978. });
  52979. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52980. /**
  52981. * Gets the actual target of the runtime animation
  52982. */
  52983. get: function () {
  52984. return this._activeTarget;
  52985. },
  52986. enumerable: true,
  52987. configurable: true
  52988. });
  52989. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52990. /**
  52991. * Gets the animation from the runtime animation
  52992. */
  52993. get: function () {
  52994. return this._animation;
  52995. },
  52996. enumerable: true,
  52997. configurable: true
  52998. });
  52999. /**
  53000. * Resets the runtime animation to the beginning
  53001. * @param restoreOriginal defines whether to restore the target property to the original value
  53002. */
  53003. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53004. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53005. if (restoreOriginal) {
  53006. if (this._target instanceof Array) {
  53007. var index = 0;
  53008. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53009. var target = _a[_i];
  53010. if (this._originalValue[index] !== undefined) {
  53011. this._setValue(target, this._originalValue[index], -1);
  53012. }
  53013. index++;
  53014. }
  53015. }
  53016. else {
  53017. if (this._originalValue[0] !== undefined) {
  53018. this._setValue(this._target, this._originalValue[0], -1);
  53019. }
  53020. }
  53021. }
  53022. this._offsetsCache = {};
  53023. this._highLimitsCache = {};
  53024. this._currentFrame = 0;
  53025. this._blendingFactor = 0;
  53026. this._originalValue = new Array();
  53027. // Events
  53028. for (var index = 0; index < this._events.length; index++) {
  53029. this._events[index].isDone = false;
  53030. }
  53031. };
  53032. /**
  53033. * Specifies if the runtime animation is stopped
  53034. * @returns Boolean specifying if the runtime animation is stopped
  53035. */
  53036. RuntimeAnimation.prototype.isStopped = function () {
  53037. return this._stopped;
  53038. };
  53039. /**
  53040. * Disposes of the runtime animation
  53041. */
  53042. RuntimeAnimation.prototype.dispose = function () {
  53043. var index = this._animation.runtimeAnimations.indexOf(this);
  53044. if (index > -1) {
  53045. this._animation.runtimeAnimations.splice(index, 1);
  53046. }
  53047. };
  53048. /**
  53049. * Interpolates the animation from the current frame
  53050. * @param currentFrame The frame to interpolate the animation to
  53051. * @param repeatCount The number of times that the animation should loop
  53052. * @param loopMode The type of looping mode to use
  53053. * @param offsetValue Animation offset value
  53054. * @param highLimitValue The high limit value
  53055. * @returns The interpolated value
  53056. */
  53057. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53058. this._currentFrame = currentFrame;
  53059. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53060. this._workValue = BABYLON.Matrix.Zero();
  53061. }
  53062. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53063. };
  53064. /**
  53065. * Apply the interpolated value to the target
  53066. * @param currentValue defines the value computed by the animation
  53067. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53068. */
  53069. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53070. if (weight === void 0) { weight = 1.0; }
  53071. if (this._target instanceof Array) {
  53072. var index = 0;
  53073. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53074. var target = _a[_i];
  53075. this._setValue(target, currentValue, weight, index);
  53076. index++;
  53077. }
  53078. }
  53079. else {
  53080. this._setValue(this._target, currentValue, weight);
  53081. }
  53082. };
  53083. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53084. if (targetIndex === void 0) { targetIndex = 0; }
  53085. // Set value
  53086. var path;
  53087. var destination;
  53088. var targetPropertyPath = this._animation.targetPropertyPath;
  53089. if (targetPropertyPath.length > 1) {
  53090. var property = target[targetPropertyPath[0]];
  53091. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53092. property = property[targetPropertyPath[index]];
  53093. }
  53094. path = targetPropertyPath[targetPropertyPath.length - 1];
  53095. destination = property;
  53096. }
  53097. else {
  53098. path = targetPropertyPath[0];
  53099. destination = target;
  53100. }
  53101. this._targetPath = path;
  53102. this._activeTarget = destination;
  53103. this._weight = weight;
  53104. if (this._originalValue[targetIndex] === undefined) {
  53105. var originalValue = void 0;
  53106. if (destination.getRestPose && path === "_matrix") { // For bones
  53107. originalValue = destination.getRestPose();
  53108. }
  53109. else {
  53110. originalValue = destination[path];
  53111. }
  53112. if (originalValue && originalValue.clone) {
  53113. this._originalValue[targetIndex] = originalValue.clone();
  53114. }
  53115. else {
  53116. this._originalValue[targetIndex] = originalValue;
  53117. }
  53118. }
  53119. // Blending
  53120. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53121. if (enableBlending && this._blendingFactor <= 1.0) {
  53122. if (!this._originalBlendValue) {
  53123. var originalValue = destination[path];
  53124. if (originalValue.clone) {
  53125. this._originalBlendValue = originalValue.clone();
  53126. }
  53127. else {
  53128. this._originalBlendValue = originalValue;
  53129. }
  53130. }
  53131. if (this._originalBlendValue.m) { // Matrix
  53132. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53133. if (this._currentValue) {
  53134. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53135. }
  53136. else {
  53137. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53138. }
  53139. }
  53140. else {
  53141. if (this._currentValue) {
  53142. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53143. }
  53144. else {
  53145. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53146. }
  53147. }
  53148. }
  53149. else {
  53150. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53151. }
  53152. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53153. this._blendingFactor += blendingSpeed;
  53154. }
  53155. else {
  53156. this._currentValue = currentValue;
  53157. }
  53158. if (weight !== -1.0) {
  53159. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53160. }
  53161. else {
  53162. destination[path] = this._currentValue;
  53163. }
  53164. if (target.markAsDirty) {
  53165. target.markAsDirty(this._animation.targetProperty);
  53166. }
  53167. };
  53168. /**
  53169. * Gets the loop pmode of the runtime animation
  53170. * @returns Loop Mode
  53171. */
  53172. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53173. if (this._target && this._target.animationPropertiesOverride) {
  53174. return this._target.animationPropertiesOverride.loopMode;
  53175. }
  53176. return this._animation.loopMode;
  53177. };
  53178. /**
  53179. * Move the current animation to a given frame
  53180. * @param frame defines the frame to move to
  53181. */
  53182. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53183. var keys = this._animation.getKeys();
  53184. if (frame < keys[0].frame) {
  53185. frame = keys[0].frame;
  53186. }
  53187. else if (frame > keys[keys.length - 1].frame) {
  53188. frame = keys[keys.length - 1].frame;
  53189. }
  53190. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53191. this.setValue(currentValue, -1);
  53192. };
  53193. /**
  53194. * @hidden Internal use only
  53195. */
  53196. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53197. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53198. this._ratioOffset = this._previousRatio - newRatio;
  53199. };
  53200. /**
  53201. * Execute the current animation
  53202. * @param delay defines the delay to add to the current frame
  53203. * @param from defines the lower bound of the animation range
  53204. * @param to defines the upper bound of the animation range
  53205. * @param loop defines if the current animation must loop
  53206. * @param speedRatio defines the current speed ratio
  53207. * @param weight defines the weight of the animation (default is -1 so no weight)
  53208. * @returns a boolean indicating if the animation is running
  53209. */
  53210. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53211. if (weight === void 0) { weight = -1.0; }
  53212. var targetPropertyPath = this._animation.targetPropertyPath;
  53213. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53214. this._stopped = true;
  53215. return false;
  53216. }
  53217. var returnValue = true;
  53218. var keys = this._animation.getKeys();
  53219. // Adding a start key at frame 0 if missing
  53220. if (keys[0].frame !== 0) {
  53221. var newKey = { frame: 0, value: keys[0].value };
  53222. keys.splice(0, 0, newKey);
  53223. }
  53224. // Adding a duplicate key when there is only one key at frame zero
  53225. else if (keys.length === 1) {
  53226. var newKey = { frame: 0.001, value: keys[0].value };
  53227. keys.push(newKey);
  53228. }
  53229. // Check limits
  53230. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53231. from = keys[0].frame;
  53232. }
  53233. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53234. to = keys[keys.length - 1].frame;
  53235. }
  53236. //to and from cannot be the same key
  53237. if (from === to) {
  53238. if (from > keys[0].frame) {
  53239. from--;
  53240. }
  53241. else if (to < keys[keys.length - 1].frame) {
  53242. to++;
  53243. }
  53244. }
  53245. // Compute ratio
  53246. var range = to - from;
  53247. var offsetValue;
  53248. // ratio represents the frame delta between from and to
  53249. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53250. var highLimitValue = 0;
  53251. this._previousDelay = delay;
  53252. this._previousRatio = ratio;
  53253. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53254. returnValue = false;
  53255. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53256. }
  53257. else {
  53258. // Get max value if required
  53259. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53260. var keyOffset = to.toString() + from.toString();
  53261. if (!this._offsetsCache[keyOffset]) {
  53262. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53263. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53264. switch (this._animation.dataType) {
  53265. // Float
  53266. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53267. this._offsetsCache[keyOffset] = toValue - fromValue;
  53268. break;
  53269. // Quaternion
  53270. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53271. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53272. break;
  53273. // Vector3
  53274. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53275. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53276. // Vector2
  53277. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53278. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53279. // Size
  53280. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53281. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53282. // Color3
  53283. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53284. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53285. default:
  53286. break;
  53287. }
  53288. this._highLimitsCache[keyOffset] = toValue;
  53289. }
  53290. highLimitValue = this._highLimitsCache[keyOffset];
  53291. offsetValue = this._offsetsCache[keyOffset];
  53292. }
  53293. }
  53294. if (offsetValue === undefined) {
  53295. switch (this._animation.dataType) {
  53296. // Float
  53297. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53298. offsetValue = 0;
  53299. break;
  53300. // Quaternion
  53301. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53302. offsetValue = _staticOffsetValueQuaternion;
  53303. break;
  53304. // Vector3
  53305. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53306. offsetValue = _staticOffsetValueVector3;
  53307. break;
  53308. // Vector2
  53309. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53310. offsetValue = _staticOffsetValueVector2;
  53311. break;
  53312. // Size
  53313. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53314. offsetValue = _staticOffsetValueSize;
  53315. break;
  53316. // Color3
  53317. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53318. offsetValue = _staticOffsetValueColor3;
  53319. }
  53320. }
  53321. // Compute value
  53322. var repeatCount = (ratio / range) >> 0;
  53323. var currentFrame = returnValue ? from + ratio % range : to;
  53324. // Need to normalize?
  53325. if (this._host && this._host.syncRoot) {
  53326. var syncRoot = this._host.syncRoot;
  53327. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53328. currentFrame = from + (to - from) * hostNormalizedFrame;
  53329. }
  53330. // Reset events if looping
  53331. var events = this._events;
  53332. if (range > 0 && this.currentFrame > currentFrame ||
  53333. range < 0 && this.currentFrame < currentFrame) {
  53334. // Need to reset animation events
  53335. for (var index = 0; index < events.length; index++) {
  53336. if (!events[index].onlyOnce) {
  53337. // reset event, the animation is looping
  53338. events[index].isDone = false;
  53339. }
  53340. }
  53341. }
  53342. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53343. // Set value
  53344. this.setValue(currentValue, weight);
  53345. // Check events
  53346. for (var index = 0; index < events.length; index++) {
  53347. // Make sure current frame has passed event frame and that event frame is within the current range
  53348. // Also, handle both forward and reverse animations
  53349. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53350. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53351. var event = events[index];
  53352. if (!event.isDone) {
  53353. // If event should be done only once, remove it.
  53354. if (event.onlyOnce) {
  53355. events.splice(index, 1);
  53356. index--;
  53357. }
  53358. event.isDone = true;
  53359. event.action(currentFrame);
  53360. } // Don't do anything if the event has already be done.
  53361. }
  53362. }
  53363. if (!returnValue) {
  53364. this._stopped = true;
  53365. }
  53366. return returnValue;
  53367. };
  53368. return RuntimeAnimation;
  53369. }());
  53370. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53371. })(BABYLON || (BABYLON = {}));
  53372. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53373. var BABYLON;
  53374. (function (BABYLON) {
  53375. /**
  53376. * Class used to store an actual running animation
  53377. */
  53378. var Animatable = /** @class */ (function () {
  53379. /**
  53380. * Creates a new Animatable
  53381. * @param scene defines the hosting scene
  53382. * @param target defines the target object
  53383. * @param fromFrame defines the starting frame number (default is 0)
  53384. * @param toFrame defines the ending frame number (default is 100)
  53385. * @param loopAnimation defines if the animation must loop (default is false)
  53386. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53387. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53388. * @param animations defines a group of animation to add to the new Animatable
  53389. */
  53390. function Animatable(scene,
  53391. /** defines the target object */
  53392. target,
  53393. /** defines the starting frame number (default is 0) */
  53394. fromFrame,
  53395. /** defines the ending frame number (default is 100) */
  53396. toFrame,
  53397. /** defines if the animation must loop (default is false) */
  53398. loopAnimation, speedRatio,
  53399. /** defines a callback to call when animation ends if it is not looping */
  53400. onAnimationEnd, animations) {
  53401. if (fromFrame === void 0) { fromFrame = 0; }
  53402. if (toFrame === void 0) { toFrame = 100; }
  53403. if (loopAnimation === void 0) { loopAnimation = false; }
  53404. if (speedRatio === void 0) { speedRatio = 1.0; }
  53405. this.target = target;
  53406. this.fromFrame = fromFrame;
  53407. this.toFrame = toFrame;
  53408. this.loopAnimation = loopAnimation;
  53409. this.onAnimationEnd = onAnimationEnd;
  53410. this._localDelayOffset = null;
  53411. this._pausedDelay = null;
  53412. this._runtimeAnimations = new Array();
  53413. this._paused = false;
  53414. this._speedRatio = 1;
  53415. this._weight = -1.0;
  53416. /**
  53417. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53418. * This will only apply for non looping animation (default is true)
  53419. */
  53420. this.disposeOnEnd = true;
  53421. /**
  53422. * Gets a boolean indicating if the animation has started
  53423. */
  53424. this.animationStarted = false;
  53425. /**
  53426. * Observer raised when the animation ends
  53427. */
  53428. this.onAnimationEndObservable = new BABYLON.Observable();
  53429. this._scene = scene;
  53430. if (animations) {
  53431. this.appendAnimations(target, animations);
  53432. }
  53433. this._speedRatio = speedRatio;
  53434. scene._activeAnimatables.push(this);
  53435. }
  53436. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53437. /**
  53438. * Gets the root Animatable used to synchronize and normalize animations
  53439. */
  53440. get: function () {
  53441. return this._syncRoot;
  53442. },
  53443. enumerable: true,
  53444. configurable: true
  53445. });
  53446. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53447. /**
  53448. * Gets the current frame of the first RuntimeAnimation
  53449. * Used to synchronize Animatables
  53450. */
  53451. get: function () {
  53452. if (this._runtimeAnimations.length === 0) {
  53453. return 0;
  53454. }
  53455. return this._runtimeAnimations[0].currentFrame;
  53456. },
  53457. enumerable: true,
  53458. configurable: true
  53459. });
  53460. Object.defineProperty(Animatable.prototype, "weight", {
  53461. /**
  53462. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53463. */
  53464. get: function () {
  53465. return this._weight;
  53466. },
  53467. set: function (value) {
  53468. if (value === -1) { // -1 is ok and means no weight
  53469. this._weight = -1;
  53470. return;
  53471. }
  53472. // Else weight must be in [0, 1] range
  53473. this._weight = Math.min(Math.max(value, 0), 1.0);
  53474. },
  53475. enumerable: true,
  53476. configurable: true
  53477. });
  53478. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53479. /**
  53480. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53481. */
  53482. get: function () {
  53483. return this._speedRatio;
  53484. },
  53485. set: function (value) {
  53486. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53487. var animation = this._runtimeAnimations[index];
  53488. animation._prepareForSpeedRatioChange(value);
  53489. }
  53490. this._speedRatio = value;
  53491. },
  53492. enumerable: true,
  53493. configurable: true
  53494. });
  53495. // Methods
  53496. /**
  53497. * Synchronize and normalize current Animatable with a source Animatable
  53498. * This is useful when using animation weights and when animations are not of the same length
  53499. * @param root defines the root Animatable to synchronize with
  53500. * @returns the current Animatable
  53501. */
  53502. Animatable.prototype.syncWith = function (root) {
  53503. this._syncRoot = root;
  53504. if (root) {
  53505. // Make sure this animatable will animate after the root
  53506. var index = this._scene._activeAnimatables.indexOf(this);
  53507. if (index > -1) {
  53508. this._scene._activeAnimatables.splice(index, 1);
  53509. this._scene._activeAnimatables.push(this);
  53510. }
  53511. }
  53512. return this;
  53513. };
  53514. /**
  53515. * Gets the list of runtime animations
  53516. * @returns an array of RuntimeAnimation
  53517. */
  53518. Animatable.prototype.getAnimations = function () {
  53519. return this._runtimeAnimations;
  53520. };
  53521. /**
  53522. * Adds more animations to the current animatable
  53523. * @param target defines the target of the animations
  53524. * @param animations defines the new animations to add
  53525. */
  53526. Animatable.prototype.appendAnimations = function (target, animations) {
  53527. for (var index = 0; index < animations.length; index++) {
  53528. var animation = animations[index];
  53529. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  53530. }
  53531. };
  53532. /**
  53533. * Gets the source animation for a specific property
  53534. * @param property defines the propertyu to look for
  53535. * @returns null or the source animation for the given property
  53536. */
  53537. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  53538. var runtimeAnimations = this._runtimeAnimations;
  53539. for (var index = 0; index < runtimeAnimations.length; index++) {
  53540. if (runtimeAnimations[index].animation.targetProperty === property) {
  53541. return runtimeAnimations[index].animation;
  53542. }
  53543. }
  53544. return null;
  53545. };
  53546. /**
  53547. * Gets the runtime animation for a specific property
  53548. * @param property defines the propertyu to look for
  53549. * @returns null or the runtime animation for the given property
  53550. */
  53551. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  53552. var runtimeAnimations = this._runtimeAnimations;
  53553. for (var index = 0; index < runtimeAnimations.length; index++) {
  53554. if (runtimeAnimations[index].animation.targetProperty === property) {
  53555. return runtimeAnimations[index];
  53556. }
  53557. }
  53558. return null;
  53559. };
  53560. /**
  53561. * Resets the animatable to its original state
  53562. */
  53563. Animatable.prototype.reset = function () {
  53564. var runtimeAnimations = this._runtimeAnimations;
  53565. for (var index = 0; index < runtimeAnimations.length; index++) {
  53566. runtimeAnimations[index].reset(true);
  53567. }
  53568. this._localDelayOffset = null;
  53569. this._pausedDelay = null;
  53570. };
  53571. /**
  53572. * Allows the animatable to blend with current running animations
  53573. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53574. * @param blendingSpeed defines the blending speed to use
  53575. */
  53576. Animatable.prototype.enableBlending = function (blendingSpeed) {
  53577. var runtimeAnimations = this._runtimeAnimations;
  53578. for (var index = 0; index < runtimeAnimations.length; index++) {
  53579. runtimeAnimations[index].animation.enableBlending = true;
  53580. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  53581. }
  53582. };
  53583. /**
  53584. * Disable animation blending
  53585. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53586. */
  53587. Animatable.prototype.disableBlending = function () {
  53588. var runtimeAnimations = this._runtimeAnimations;
  53589. for (var index = 0; index < runtimeAnimations.length; index++) {
  53590. runtimeAnimations[index].animation.enableBlending = false;
  53591. }
  53592. };
  53593. /**
  53594. * Jump directly to a given frame
  53595. * @param frame defines the frame to jump to
  53596. */
  53597. Animatable.prototype.goToFrame = function (frame) {
  53598. var runtimeAnimations = this._runtimeAnimations;
  53599. if (runtimeAnimations[0]) {
  53600. var fps = runtimeAnimations[0].animation.framePerSecond;
  53601. var currentFrame = runtimeAnimations[0].currentFrame;
  53602. var adjustTime = frame - currentFrame;
  53603. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  53604. if (this._localDelayOffset === null) {
  53605. this._localDelayOffset = 0;
  53606. }
  53607. this._localDelayOffset -= delay;
  53608. }
  53609. for (var index = 0; index < runtimeAnimations.length; index++) {
  53610. runtimeAnimations[index].goToFrame(frame);
  53611. }
  53612. };
  53613. /**
  53614. * Pause the animation
  53615. */
  53616. Animatable.prototype.pause = function () {
  53617. if (this._paused) {
  53618. return;
  53619. }
  53620. this._paused = true;
  53621. };
  53622. /**
  53623. * Restart the animation
  53624. */
  53625. Animatable.prototype.restart = function () {
  53626. this._paused = false;
  53627. };
  53628. Animatable.prototype._raiseOnAnimationEnd = function () {
  53629. if (this.onAnimationEnd) {
  53630. this.onAnimationEnd();
  53631. }
  53632. this.onAnimationEndObservable.notifyObservers(this);
  53633. };
  53634. /**
  53635. * Stop and delete the current animation
  53636. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  53637. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  53638. */
  53639. Animatable.prototype.stop = function (animationName, targetMask) {
  53640. if (animationName || targetMask) {
  53641. var idx = this._scene._activeAnimatables.indexOf(this);
  53642. if (idx > -1) {
  53643. var runtimeAnimations = this._runtimeAnimations;
  53644. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  53645. var runtimeAnimation = runtimeAnimations[index];
  53646. if (animationName && runtimeAnimation.animation.name != animationName) {
  53647. continue;
  53648. }
  53649. if (targetMask && !targetMask(runtimeAnimation.target)) {
  53650. continue;
  53651. }
  53652. runtimeAnimation.dispose();
  53653. runtimeAnimations.splice(index, 1);
  53654. }
  53655. if (runtimeAnimations.length == 0) {
  53656. this._scene._activeAnimatables.splice(idx, 1);
  53657. this._raiseOnAnimationEnd();
  53658. }
  53659. }
  53660. }
  53661. else {
  53662. var index = this._scene._activeAnimatables.indexOf(this);
  53663. if (index > -1) {
  53664. this._scene._activeAnimatables.splice(index, 1);
  53665. var runtimeAnimations = this._runtimeAnimations;
  53666. for (var index = 0; index < runtimeAnimations.length; index++) {
  53667. runtimeAnimations[index].dispose();
  53668. }
  53669. this._raiseOnAnimationEnd();
  53670. }
  53671. }
  53672. };
  53673. /**
  53674. * Wait asynchronously for the animation to end
  53675. * @returns a promise which will be fullfilled when the animation ends
  53676. */
  53677. Animatable.prototype.waitAsync = function () {
  53678. var _this = this;
  53679. return new Promise(function (resolve, reject) {
  53680. _this.onAnimationEndObservable.add(function () {
  53681. resolve(_this);
  53682. }, undefined, undefined, _this, true);
  53683. });
  53684. };
  53685. /** @hidden */
  53686. Animatable.prototype._animate = function (delay) {
  53687. if (this._paused) {
  53688. this.animationStarted = false;
  53689. if (this._pausedDelay === null) {
  53690. this._pausedDelay = delay;
  53691. }
  53692. return true;
  53693. }
  53694. if (this._localDelayOffset === null) {
  53695. this._localDelayOffset = delay;
  53696. this._pausedDelay = null;
  53697. }
  53698. else if (this._pausedDelay !== null) {
  53699. this._localDelayOffset += delay - this._pausedDelay;
  53700. this._pausedDelay = null;
  53701. }
  53702. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  53703. return true;
  53704. }
  53705. // Animating
  53706. var running = false;
  53707. var runtimeAnimations = this._runtimeAnimations;
  53708. var index;
  53709. for (index = 0; index < runtimeAnimations.length; index++) {
  53710. var animation = runtimeAnimations[index];
  53711. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  53712. running = running || isRunning;
  53713. }
  53714. this.animationStarted = running;
  53715. if (!running) {
  53716. if (this.disposeOnEnd) {
  53717. // Remove from active animatables
  53718. index = this._scene._activeAnimatables.indexOf(this);
  53719. this._scene._activeAnimatables.splice(index, 1);
  53720. // Dispose all runtime animations
  53721. for (index = 0; index < runtimeAnimations.length; index++) {
  53722. runtimeAnimations[index].dispose();
  53723. }
  53724. }
  53725. this._raiseOnAnimationEnd();
  53726. if (this.disposeOnEnd) {
  53727. this.onAnimationEnd = null;
  53728. this.onAnimationEndObservable.clear();
  53729. }
  53730. }
  53731. return running;
  53732. };
  53733. return Animatable;
  53734. }());
  53735. BABYLON.Animatable = Animatable;
  53736. })(BABYLON || (BABYLON = {}));
  53737. //# sourceMappingURL=babylon.animatable.js.map
  53738. var BABYLON;
  53739. (function (BABYLON) {
  53740. /**
  53741. * Base class used for every default easing function.
  53742. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53743. */
  53744. var EasingFunction = /** @class */ (function () {
  53745. function EasingFunction() {
  53746. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  53747. }
  53748. /**
  53749. * Sets the easing mode of the current function.
  53750. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  53751. */
  53752. EasingFunction.prototype.setEasingMode = function (easingMode) {
  53753. var n = Math.min(Math.max(easingMode, 0), 2);
  53754. this._easingMode = n;
  53755. };
  53756. /**
  53757. * Gets the current easing mode.
  53758. * @returns the easing mode
  53759. */
  53760. EasingFunction.prototype.getEasingMode = function () {
  53761. return this._easingMode;
  53762. };
  53763. /**
  53764. * @hidden
  53765. */
  53766. EasingFunction.prototype.easeInCore = function (gradient) {
  53767. throw new Error('You must implement this method');
  53768. };
  53769. /**
  53770. * Given an input gradient between 0 and 1, this returns the corrseponding value
  53771. * of the easing function.
  53772. * @param gradient Defines the value between 0 and 1 we want the easing value for
  53773. * @returns the corresponding value on the curve defined by the easing function
  53774. */
  53775. EasingFunction.prototype.ease = function (gradient) {
  53776. switch (this._easingMode) {
  53777. case EasingFunction.EASINGMODE_EASEIN:
  53778. return this.easeInCore(gradient);
  53779. case EasingFunction.EASINGMODE_EASEOUT:
  53780. return (1 - this.easeInCore(1 - gradient));
  53781. }
  53782. if (gradient >= 0.5) {
  53783. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53784. }
  53785. return (this.easeInCore(gradient * 2) * 0.5);
  53786. };
  53787. /**
  53788. * Interpolation follows the mathematical formula associated with the easing function.
  53789. */
  53790. EasingFunction.EASINGMODE_EASEIN = 0;
  53791. /**
  53792. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  53793. */
  53794. EasingFunction.EASINGMODE_EASEOUT = 1;
  53795. /**
  53796. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  53797. */
  53798. EasingFunction.EASINGMODE_EASEINOUT = 2;
  53799. return EasingFunction;
  53800. }());
  53801. BABYLON.EasingFunction = EasingFunction;
  53802. /**
  53803. * Easing function with a circle shape (see link below).
  53804. * @see https://easings.net/#easeInCirc
  53805. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53806. */
  53807. var CircleEase = /** @class */ (function (_super) {
  53808. __extends(CircleEase, _super);
  53809. function CircleEase() {
  53810. return _super !== null && _super.apply(this, arguments) || this;
  53811. }
  53812. /** @hidden */
  53813. CircleEase.prototype.easeInCore = function (gradient) {
  53814. gradient = Math.max(0, Math.min(1, gradient));
  53815. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53816. };
  53817. return CircleEase;
  53818. }(EasingFunction));
  53819. BABYLON.CircleEase = CircleEase;
  53820. /**
  53821. * Easing function with a ease back shape (see link below).
  53822. * @see https://easings.net/#easeInBack
  53823. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53824. */
  53825. var BackEase = /** @class */ (function (_super) {
  53826. __extends(BackEase, _super);
  53827. /**
  53828. * Instantiates a back ease easing
  53829. * @see https://easings.net/#easeInBack
  53830. * @param amplitude Defines the amplitude of the function
  53831. */
  53832. function BackEase(
  53833. /** Defines the amplitude of the function */
  53834. amplitude) {
  53835. if (amplitude === void 0) { amplitude = 1; }
  53836. var _this = _super.call(this) || this;
  53837. _this.amplitude = amplitude;
  53838. return _this;
  53839. }
  53840. /** @hidden */
  53841. BackEase.prototype.easeInCore = function (gradient) {
  53842. var num = Math.max(0, this.amplitude);
  53843. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53844. };
  53845. return BackEase;
  53846. }(EasingFunction));
  53847. BABYLON.BackEase = BackEase;
  53848. /**
  53849. * Easing function with a bouncing shape (see link below).
  53850. * @see https://easings.net/#easeInBounce
  53851. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53852. */
  53853. var BounceEase = /** @class */ (function (_super) {
  53854. __extends(BounceEase, _super);
  53855. /**
  53856. * Instantiates a bounce easing
  53857. * @see https://easings.net/#easeInBounce
  53858. * @param bounces Defines the number of bounces
  53859. * @param bounciness Defines the amplitude of the bounce
  53860. */
  53861. function BounceEase(
  53862. /** Defines the number of bounces */
  53863. bounces,
  53864. /** Defines the amplitude of the bounce */
  53865. bounciness) {
  53866. if (bounces === void 0) { bounces = 3; }
  53867. if (bounciness === void 0) { bounciness = 2; }
  53868. var _this = _super.call(this) || this;
  53869. _this.bounces = bounces;
  53870. _this.bounciness = bounciness;
  53871. return _this;
  53872. }
  53873. /** @hidden */
  53874. BounceEase.prototype.easeInCore = function (gradient) {
  53875. var y = Math.max(0.0, this.bounces);
  53876. var bounciness = this.bounciness;
  53877. if (bounciness <= 1.0) {
  53878. bounciness = 1.001;
  53879. }
  53880. var num9 = Math.pow(bounciness, y);
  53881. var num5 = 1.0 - bounciness;
  53882. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53883. var num15 = gradient * num4;
  53884. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53885. var num3 = Math.floor(num65);
  53886. var num13 = num3 + 1.0;
  53887. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53888. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53889. var num7 = (num8 + num12) * 0.5;
  53890. var num6 = gradient - num7;
  53891. var num2 = num7 - num8;
  53892. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53893. };
  53894. return BounceEase;
  53895. }(EasingFunction));
  53896. BABYLON.BounceEase = BounceEase;
  53897. /**
  53898. * Easing function with a power of 3 shape (see link below).
  53899. * @see https://easings.net/#easeInCubic
  53900. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53901. */
  53902. var CubicEase = /** @class */ (function (_super) {
  53903. __extends(CubicEase, _super);
  53904. function CubicEase() {
  53905. return _super !== null && _super.apply(this, arguments) || this;
  53906. }
  53907. /** @hidden */
  53908. CubicEase.prototype.easeInCore = function (gradient) {
  53909. return (gradient * gradient * gradient);
  53910. };
  53911. return CubicEase;
  53912. }(EasingFunction));
  53913. BABYLON.CubicEase = CubicEase;
  53914. /**
  53915. * Easing function with an elastic shape (see link below).
  53916. * @see https://easings.net/#easeInElastic
  53917. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53918. */
  53919. var ElasticEase = /** @class */ (function (_super) {
  53920. __extends(ElasticEase, _super);
  53921. /**
  53922. * Instantiates an elastic easing function
  53923. * @see https://easings.net/#easeInElastic
  53924. * @param oscillations Defines the number of oscillations
  53925. * @param springiness Defines the amplitude of the oscillations
  53926. */
  53927. function ElasticEase(
  53928. /** Defines the number of oscillations*/
  53929. oscillations,
  53930. /** Defines the amplitude of the oscillations*/
  53931. springiness) {
  53932. if (oscillations === void 0) { oscillations = 3; }
  53933. if (springiness === void 0) { springiness = 3; }
  53934. var _this = _super.call(this) || this;
  53935. _this.oscillations = oscillations;
  53936. _this.springiness = springiness;
  53937. return _this;
  53938. }
  53939. /** @hidden */
  53940. ElasticEase.prototype.easeInCore = function (gradient) {
  53941. var num2;
  53942. var num3 = Math.max(0.0, this.oscillations);
  53943. var num = Math.max(0.0, this.springiness);
  53944. if (num == 0) {
  53945. num2 = gradient;
  53946. }
  53947. else {
  53948. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53949. }
  53950. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53951. };
  53952. return ElasticEase;
  53953. }(EasingFunction));
  53954. BABYLON.ElasticEase = ElasticEase;
  53955. /**
  53956. * Easing function with an exponential shape (see link below).
  53957. * @see https://easings.net/#easeInExpo
  53958. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53959. */
  53960. var ExponentialEase = /** @class */ (function (_super) {
  53961. __extends(ExponentialEase, _super);
  53962. /**
  53963. * Instantiates an exponential easing function
  53964. * @see https://easings.net/#easeInExpo
  53965. * @param exponent Defines the exponent of the function
  53966. */
  53967. function ExponentialEase(
  53968. /** Defines the exponent of the function */
  53969. exponent) {
  53970. if (exponent === void 0) { exponent = 2; }
  53971. var _this = _super.call(this) || this;
  53972. _this.exponent = exponent;
  53973. return _this;
  53974. }
  53975. /** @hidden */
  53976. ExponentialEase.prototype.easeInCore = function (gradient) {
  53977. if (this.exponent <= 0) {
  53978. return gradient;
  53979. }
  53980. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53981. };
  53982. return ExponentialEase;
  53983. }(EasingFunction));
  53984. BABYLON.ExponentialEase = ExponentialEase;
  53985. /**
  53986. * Easing function with a power shape (see link below).
  53987. * @see https://easings.net/#easeInQuad
  53988. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53989. */
  53990. var PowerEase = /** @class */ (function (_super) {
  53991. __extends(PowerEase, _super);
  53992. /**
  53993. * Instantiates an power base easing function
  53994. * @see https://easings.net/#easeInQuad
  53995. * @param power Defines the power of the function
  53996. */
  53997. function PowerEase(
  53998. /** Defines the power of the function */
  53999. power) {
  54000. if (power === void 0) { power = 2; }
  54001. var _this = _super.call(this) || this;
  54002. _this.power = power;
  54003. return _this;
  54004. }
  54005. /** @hidden */
  54006. PowerEase.prototype.easeInCore = function (gradient) {
  54007. var y = Math.max(0.0, this.power);
  54008. return Math.pow(gradient, y);
  54009. };
  54010. return PowerEase;
  54011. }(EasingFunction));
  54012. BABYLON.PowerEase = PowerEase;
  54013. /**
  54014. * Easing function with a power of 2 shape (see link below).
  54015. * @see https://easings.net/#easeInQuad
  54016. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54017. */
  54018. var QuadraticEase = /** @class */ (function (_super) {
  54019. __extends(QuadraticEase, _super);
  54020. function QuadraticEase() {
  54021. return _super !== null && _super.apply(this, arguments) || this;
  54022. }
  54023. /** @hidden */
  54024. QuadraticEase.prototype.easeInCore = function (gradient) {
  54025. return (gradient * gradient);
  54026. };
  54027. return QuadraticEase;
  54028. }(EasingFunction));
  54029. BABYLON.QuadraticEase = QuadraticEase;
  54030. /**
  54031. * Easing function with a power of 4 shape (see link below).
  54032. * @see https://easings.net/#easeInQuart
  54033. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54034. */
  54035. var QuarticEase = /** @class */ (function (_super) {
  54036. __extends(QuarticEase, _super);
  54037. function QuarticEase() {
  54038. return _super !== null && _super.apply(this, arguments) || this;
  54039. }
  54040. /** @hidden */
  54041. QuarticEase.prototype.easeInCore = function (gradient) {
  54042. return (gradient * gradient * gradient * gradient);
  54043. };
  54044. return QuarticEase;
  54045. }(EasingFunction));
  54046. BABYLON.QuarticEase = QuarticEase;
  54047. /**
  54048. * Easing function with a power of 5 shape (see link below).
  54049. * @see https://easings.net/#easeInQuint
  54050. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54051. */
  54052. var QuinticEase = /** @class */ (function (_super) {
  54053. __extends(QuinticEase, _super);
  54054. function QuinticEase() {
  54055. return _super !== null && _super.apply(this, arguments) || this;
  54056. }
  54057. /** @hidden */
  54058. QuinticEase.prototype.easeInCore = function (gradient) {
  54059. return (gradient * gradient * gradient * gradient * gradient);
  54060. };
  54061. return QuinticEase;
  54062. }(EasingFunction));
  54063. BABYLON.QuinticEase = QuinticEase;
  54064. /**
  54065. * Easing function with a sin shape (see link below).
  54066. * @see https://easings.net/#easeInSine
  54067. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54068. */
  54069. var SineEase = /** @class */ (function (_super) {
  54070. __extends(SineEase, _super);
  54071. function SineEase() {
  54072. return _super !== null && _super.apply(this, arguments) || this;
  54073. }
  54074. /** @hidden */
  54075. SineEase.prototype.easeInCore = function (gradient) {
  54076. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54077. };
  54078. return SineEase;
  54079. }(EasingFunction));
  54080. BABYLON.SineEase = SineEase;
  54081. /**
  54082. * Easing function with a bezier shape (see link below).
  54083. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54084. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54085. */
  54086. var BezierCurveEase = /** @class */ (function (_super) {
  54087. __extends(BezierCurveEase, _super);
  54088. /**
  54089. * Instantiates a bezier function
  54090. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54091. * @param x1 Defines the x component of the start tangent in the bezier curve
  54092. * @param y1 Defines the y component of the start tangent in the bezier curve
  54093. * @param x2 Defines the x component of the end tangent in the bezier curve
  54094. * @param y2 Defines the y component of the end tangent in the bezier curve
  54095. */
  54096. function BezierCurveEase(
  54097. /** Defines the x component of the start tangent in the bezier curve */
  54098. x1,
  54099. /** Defines the y component of the start tangent in the bezier curve */
  54100. y1,
  54101. /** Defines the x component of the end tangent in the bezier curve */
  54102. x2,
  54103. /** Defines the y component of the end tangent in the bezier curve */
  54104. y2) {
  54105. if (x1 === void 0) { x1 = 0; }
  54106. if (y1 === void 0) { y1 = 0; }
  54107. if (x2 === void 0) { x2 = 1; }
  54108. if (y2 === void 0) { y2 = 1; }
  54109. var _this = _super.call(this) || this;
  54110. _this.x1 = x1;
  54111. _this.y1 = y1;
  54112. _this.x2 = x2;
  54113. _this.y2 = y2;
  54114. return _this;
  54115. }
  54116. /** @hidden */
  54117. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54118. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54119. };
  54120. return BezierCurveEase;
  54121. }(EasingFunction));
  54122. BABYLON.BezierCurveEase = BezierCurveEase;
  54123. })(BABYLON || (BABYLON = {}));
  54124. //# sourceMappingURL=babylon.easing.js.map
  54125. var BABYLON;
  54126. (function (BABYLON) {
  54127. /**
  54128. * A Condition applied to an Action
  54129. */
  54130. var Condition = /** @class */ (function () {
  54131. /**
  54132. * Creates a new Condition
  54133. * @param actionManager the manager of the action the condition is applied to
  54134. */
  54135. function Condition(actionManager) {
  54136. this._actionManager = actionManager;
  54137. }
  54138. /**
  54139. * Check if the current condition is valid
  54140. * @returns a boolean
  54141. */
  54142. Condition.prototype.isValid = function () {
  54143. return true;
  54144. };
  54145. /**
  54146. * Internal only
  54147. * @hidden
  54148. */
  54149. Condition.prototype._getProperty = function (propertyPath) {
  54150. return this._actionManager._getProperty(propertyPath);
  54151. };
  54152. /**
  54153. * Internal only
  54154. * @hidden
  54155. */
  54156. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54157. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54158. };
  54159. /**
  54160. * Serialize placeholder for child classes
  54161. * @returns the serialized object
  54162. */
  54163. Condition.prototype.serialize = function () {
  54164. };
  54165. /**
  54166. * Internal only
  54167. * @hidden
  54168. */
  54169. Condition.prototype._serialize = function (serializedCondition) {
  54170. return {
  54171. type: 2,
  54172. children: [],
  54173. name: serializedCondition.name,
  54174. properties: serializedCondition.properties
  54175. };
  54176. };
  54177. return Condition;
  54178. }());
  54179. BABYLON.Condition = Condition;
  54180. /**
  54181. * Defines specific conditional operators as extensions of Condition
  54182. */
  54183. var ValueCondition = /** @class */ (function (_super) {
  54184. __extends(ValueCondition, _super);
  54185. /**
  54186. * Creates a new ValueCondition
  54187. * @param actionManager manager for the action the condition applies to
  54188. * @param target for the action
  54189. * @param propertyPath path to specify the property of the target the conditional operator uses
  54190. * @param value the value compared by the conditional operator against the current value of the property
  54191. * @param operator the conditional operator, default ValueCondition.IsEqual
  54192. */
  54193. function ValueCondition(actionManager, target,
  54194. /** path to specify the property of the target the conditional operator uses */
  54195. propertyPath,
  54196. /** the value compared by the conditional operator against the current value of the property */
  54197. value,
  54198. /** the conditional operator, default ValueCondition.IsEqual */
  54199. operator) {
  54200. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54201. var _this = _super.call(this, actionManager) || this;
  54202. _this.propertyPath = propertyPath;
  54203. _this.value = value;
  54204. _this.operator = operator;
  54205. _this._target = target;
  54206. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54207. _this._property = _this._getProperty(_this.propertyPath);
  54208. return _this;
  54209. }
  54210. Object.defineProperty(ValueCondition, "IsEqual", {
  54211. /**
  54212. * returns the number for IsEqual
  54213. */
  54214. get: function () {
  54215. return ValueCondition._IsEqual;
  54216. },
  54217. enumerable: true,
  54218. configurable: true
  54219. });
  54220. Object.defineProperty(ValueCondition, "IsDifferent", {
  54221. /**
  54222. * Returns the number for IsDifferent
  54223. */
  54224. get: function () {
  54225. return ValueCondition._IsDifferent;
  54226. },
  54227. enumerable: true,
  54228. configurable: true
  54229. });
  54230. Object.defineProperty(ValueCondition, "IsGreater", {
  54231. /**
  54232. * Returns the number for IsGreater
  54233. */
  54234. get: function () {
  54235. return ValueCondition._IsGreater;
  54236. },
  54237. enumerable: true,
  54238. configurable: true
  54239. });
  54240. Object.defineProperty(ValueCondition, "IsLesser", {
  54241. /**
  54242. * Returns the number for IsLesser
  54243. */
  54244. get: function () {
  54245. return ValueCondition._IsLesser;
  54246. },
  54247. enumerable: true,
  54248. configurable: true
  54249. });
  54250. /**
  54251. * Compares the given value with the property value for the specified conditional operator
  54252. * @returns the result of the comparison
  54253. */
  54254. ValueCondition.prototype.isValid = function () {
  54255. switch (this.operator) {
  54256. case ValueCondition.IsGreater:
  54257. return this._effectiveTarget[this._property] > this.value;
  54258. case ValueCondition.IsLesser:
  54259. return this._effectiveTarget[this._property] < this.value;
  54260. case ValueCondition.IsEqual:
  54261. case ValueCondition.IsDifferent:
  54262. var check;
  54263. if (this.value.equals) {
  54264. check = this.value.equals(this._effectiveTarget[this._property]);
  54265. }
  54266. else {
  54267. check = this.value === this._effectiveTarget[this._property];
  54268. }
  54269. return this.operator === ValueCondition.IsEqual ? check : !check;
  54270. }
  54271. return false;
  54272. };
  54273. /**
  54274. * Serialize the ValueCondition into a JSON compatible object
  54275. * @returns serialization object
  54276. */
  54277. ValueCondition.prototype.serialize = function () {
  54278. return this._serialize({
  54279. name: "ValueCondition",
  54280. properties: [
  54281. BABYLON.Action._GetTargetProperty(this._target),
  54282. { name: "propertyPath", value: this.propertyPath },
  54283. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54284. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54285. ]
  54286. });
  54287. };
  54288. /**
  54289. * Gets the name of the conditional operator for the ValueCondition
  54290. * @param operator the conditional operator
  54291. * @returns the name
  54292. */
  54293. ValueCondition.GetOperatorName = function (operator) {
  54294. switch (operator) {
  54295. case ValueCondition._IsEqual: return "IsEqual";
  54296. case ValueCondition._IsDifferent: return "IsDifferent";
  54297. case ValueCondition._IsGreater: return "IsGreater";
  54298. case ValueCondition._IsLesser: return "IsLesser";
  54299. default: return "";
  54300. }
  54301. };
  54302. /**
  54303. * Internal only
  54304. * @hidden
  54305. */
  54306. ValueCondition._IsEqual = 0;
  54307. /**
  54308. * Internal only
  54309. * @hidden
  54310. */
  54311. ValueCondition._IsDifferent = 1;
  54312. /**
  54313. * Internal only
  54314. * @hidden
  54315. */
  54316. ValueCondition._IsGreater = 2;
  54317. /**
  54318. * Internal only
  54319. * @hidden
  54320. */
  54321. ValueCondition._IsLesser = 3;
  54322. return ValueCondition;
  54323. }(Condition));
  54324. BABYLON.ValueCondition = ValueCondition;
  54325. /**
  54326. * Defines a predicate condition as an extension of Condition
  54327. */
  54328. var PredicateCondition = /** @class */ (function (_super) {
  54329. __extends(PredicateCondition, _super);
  54330. /**
  54331. * Creates a new PredicateCondition
  54332. * @param actionManager manager for the action the condition applies to
  54333. * @param predicate defines the predicate function used to validate the condition
  54334. */
  54335. function PredicateCondition(actionManager,
  54336. /** defines the predicate function used to validate the condition */
  54337. predicate) {
  54338. var _this = _super.call(this, actionManager) || this;
  54339. _this.predicate = predicate;
  54340. return _this;
  54341. }
  54342. /**
  54343. * @returns the validity of the predicate condition
  54344. */
  54345. PredicateCondition.prototype.isValid = function () {
  54346. return this.predicate();
  54347. };
  54348. return PredicateCondition;
  54349. }(Condition));
  54350. BABYLON.PredicateCondition = PredicateCondition;
  54351. /**
  54352. * Defines a state condition as an extension of Condition
  54353. */
  54354. var StateCondition = /** @class */ (function (_super) {
  54355. __extends(StateCondition, _super);
  54356. /**
  54357. * Creates a new StateCondition
  54358. * @param actionManager manager for the action the condition applies to
  54359. * @param target of the condition
  54360. * @param value to compare with target state
  54361. */
  54362. function StateCondition(actionManager, target, value) {
  54363. var _this = _super.call(this, actionManager) || this;
  54364. _this.value = value;
  54365. _this._target = target;
  54366. return _this;
  54367. }
  54368. /**
  54369. * @returns the validity of the state
  54370. */
  54371. StateCondition.prototype.isValid = function () {
  54372. return this._target.state === this.value;
  54373. };
  54374. /**
  54375. * Serialize the StateCondition into a JSON compatible object
  54376. * @returns serialization object
  54377. */
  54378. StateCondition.prototype.serialize = function () {
  54379. return this._serialize({
  54380. name: "StateCondition",
  54381. properties: [
  54382. BABYLON.Action._GetTargetProperty(this._target),
  54383. { name: "value", value: this.value }
  54384. ]
  54385. });
  54386. };
  54387. return StateCondition;
  54388. }(Condition));
  54389. BABYLON.StateCondition = StateCondition;
  54390. })(BABYLON || (BABYLON = {}));
  54391. //# sourceMappingURL=babylon.condition.js.map
  54392. var BABYLON;
  54393. (function (BABYLON) {
  54394. /**
  54395. * The action to be carried out following a trigger
  54396. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54397. */
  54398. var Action = /** @class */ (function () {
  54399. /**
  54400. * Creates a new Action
  54401. * @param triggerOptions the trigger, with or without parameters, for the action
  54402. * @param condition an optional determinant of action
  54403. */
  54404. function Action(
  54405. /** the trigger, with or without parameters, for the action */
  54406. triggerOptions, condition) {
  54407. this.triggerOptions = triggerOptions;
  54408. /**
  54409. * An event triggered prior to action being executed.
  54410. */
  54411. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54412. if (triggerOptions.parameter) {
  54413. this.trigger = triggerOptions.trigger;
  54414. this._triggerParameter = triggerOptions.parameter;
  54415. }
  54416. else if (triggerOptions.trigger) {
  54417. this.trigger = triggerOptions.trigger;
  54418. }
  54419. else {
  54420. this.trigger = triggerOptions;
  54421. }
  54422. this._nextActiveAction = this;
  54423. this._condition = condition;
  54424. }
  54425. /**
  54426. * Internal only
  54427. * @hidden
  54428. */
  54429. Action.prototype._prepare = function () {
  54430. };
  54431. /**
  54432. * Gets the trigger parameters
  54433. * @returns the trigger parameters
  54434. */
  54435. Action.prototype.getTriggerParameter = function () {
  54436. return this._triggerParameter;
  54437. };
  54438. /**
  54439. * Internal only - executes current action event
  54440. * @hidden
  54441. */
  54442. Action.prototype._executeCurrent = function (evt) {
  54443. if (this._nextActiveAction._condition) {
  54444. var condition = this._nextActiveAction._condition;
  54445. var currentRenderId = this._actionManager.getScene().getRenderId();
  54446. // We cache the current evaluation for the current frame
  54447. if (condition._evaluationId === currentRenderId) {
  54448. if (!condition._currentResult) {
  54449. return;
  54450. }
  54451. }
  54452. else {
  54453. condition._evaluationId = currentRenderId;
  54454. if (!condition.isValid()) {
  54455. condition._currentResult = false;
  54456. return;
  54457. }
  54458. condition._currentResult = true;
  54459. }
  54460. }
  54461. this.onBeforeExecuteObservable.notifyObservers(this);
  54462. this._nextActiveAction.execute(evt);
  54463. this.skipToNextActiveAction();
  54464. };
  54465. /**
  54466. * Execute placeholder for child classes
  54467. * @param evt optional action event
  54468. */
  54469. Action.prototype.execute = function (evt) {
  54470. };
  54471. /**
  54472. * Skips to next active action
  54473. */
  54474. Action.prototype.skipToNextActiveAction = function () {
  54475. if (this._nextActiveAction._child) {
  54476. if (!this._nextActiveAction._child._actionManager) {
  54477. this._nextActiveAction._child._actionManager = this._actionManager;
  54478. }
  54479. this._nextActiveAction = this._nextActiveAction._child;
  54480. }
  54481. else {
  54482. this._nextActiveAction = this;
  54483. }
  54484. };
  54485. /**
  54486. * Adds action to chain of actions, may be a DoNothingAction
  54487. * @param action defines the next action to execute
  54488. * @returns The action passed in
  54489. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54490. */
  54491. Action.prototype.then = function (action) {
  54492. this._child = action;
  54493. action._actionManager = this._actionManager;
  54494. action._prepare();
  54495. return action;
  54496. };
  54497. /**
  54498. * Internal only
  54499. * @hidden
  54500. */
  54501. Action.prototype._getProperty = function (propertyPath) {
  54502. return this._actionManager._getProperty(propertyPath);
  54503. };
  54504. /**
  54505. * Internal only
  54506. * @hidden
  54507. */
  54508. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54509. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54510. };
  54511. /**
  54512. * Serialize placeholder for child classes
  54513. * @param parent of child
  54514. * @returns the serialized object
  54515. */
  54516. Action.prototype.serialize = function (parent) {
  54517. };
  54518. /**
  54519. * Internal only called by serialize
  54520. * @hidden
  54521. */
  54522. Action.prototype._serialize = function (serializedAction, parent) {
  54523. var serializationObject = {
  54524. type: 1,
  54525. children: [],
  54526. name: serializedAction.name,
  54527. properties: serializedAction.properties || []
  54528. };
  54529. // Serialize child
  54530. if (this._child) {
  54531. this._child.serialize(serializationObject);
  54532. }
  54533. // Check if "this" has a condition
  54534. if (this._condition) {
  54535. var serializedCondition = this._condition.serialize();
  54536. serializedCondition.children.push(serializationObject);
  54537. if (parent) {
  54538. parent.children.push(serializedCondition);
  54539. }
  54540. return serializedCondition;
  54541. }
  54542. if (parent) {
  54543. parent.children.push(serializationObject);
  54544. }
  54545. return serializationObject;
  54546. };
  54547. /**
  54548. * Internal only
  54549. * @hidden
  54550. */
  54551. Action._SerializeValueAsString = function (value) {
  54552. if (typeof value === "number") {
  54553. return value.toString();
  54554. }
  54555. if (typeof value === "boolean") {
  54556. return value ? "true" : "false";
  54557. }
  54558. if (value instanceof BABYLON.Vector2) {
  54559. return value.x + ", " + value.y;
  54560. }
  54561. if (value instanceof BABYLON.Vector3) {
  54562. return value.x + ", " + value.y + ", " + value.z;
  54563. }
  54564. if (value instanceof BABYLON.Color3) {
  54565. return value.r + ", " + value.g + ", " + value.b;
  54566. }
  54567. if (value instanceof BABYLON.Color4) {
  54568. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  54569. }
  54570. return value; // string
  54571. };
  54572. /**
  54573. * Internal only
  54574. * @hidden
  54575. */
  54576. Action._GetTargetProperty = function (target) {
  54577. return {
  54578. name: "target",
  54579. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  54580. : target instanceof BABYLON.Light ? "LightProperties"
  54581. : target instanceof BABYLON.Camera ? "CameraProperties"
  54582. : "SceneProperties",
  54583. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  54584. };
  54585. };
  54586. return Action;
  54587. }());
  54588. BABYLON.Action = Action;
  54589. })(BABYLON || (BABYLON = {}));
  54590. //# sourceMappingURL=babylon.action.js.map
  54591. var BABYLON;
  54592. (function (BABYLON) {
  54593. /**
  54594. * ActionEvent is the event being sent when an action is triggered.
  54595. */
  54596. var ActionEvent = /** @class */ (function () {
  54597. /**
  54598. * Creates a new ActionEvent
  54599. * @param source The mesh or sprite that triggered the action
  54600. * @param pointerX The X mouse cursor position at the time of the event
  54601. * @param pointerY The Y mouse cursor position at the time of the event
  54602. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  54603. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  54604. * @param additionalData additional data for the event
  54605. */
  54606. function ActionEvent(
  54607. /** The mesh or sprite that triggered the action */
  54608. source,
  54609. /** The X mouse cursor position at the time of the event */
  54610. pointerX,
  54611. /** The Y mouse cursor position at the time of the event */
  54612. pointerY,
  54613. /** The mesh that is currently pointed at (can be null) */
  54614. meshUnderPointer,
  54615. /** the original (browser) event that triggered the ActionEvent */
  54616. sourceEvent,
  54617. /** additional data for the event */
  54618. additionalData) {
  54619. this.source = source;
  54620. this.pointerX = pointerX;
  54621. this.pointerY = pointerY;
  54622. this.meshUnderPointer = meshUnderPointer;
  54623. this.sourceEvent = sourceEvent;
  54624. this.additionalData = additionalData;
  54625. }
  54626. /**
  54627. * Helper function to auto-create an ActionEvent from a source mesh.
  54628. * @param source The source mesh that triggered the event
  54629. * @param evt The original (browser) event
  54630. * @param additionalData additional data for the event
  54631. * @returns the new ActionEvent
  54632. */
  54633. ActionEvent.CreateNew = function (source, evt, additionalData) {
  54634. var scene = source.getScene();
  54635. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54636. };
  54637. /**
  54638. * Helper function to auto-create an ActionEvent from a source sprite
  54639. * @param source The source sprite that triggered the event
  54640. * @param scene Scene associated with the sprite
  54641. * @param evt The original (browser) event
  54642. * @param additionalData additional data for the event
  54643. * @returns the new ActionEvent
  54644. */
  54645. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  54646. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54647. };
  54648. /**
  54649. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  54650. * @param scene the scene where the event occurred
  54651. * @param evt The original (browser) event
  54652. * @returns the new ActionEvent
  54653. */
  54654. ActionEvent.CreateNewFromScene = function (scene, evt) {
  54655. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  54656. };
  54657. /**
  54658. * Helper function to auto-create an ActionEvent from a primitive
  54659. * @param prim defines the target primitive
  54660. * @param pointerPos defines the pointer position
  54661. * @param evt The original (browser) event
  54662. * @param additionalData additional data for the event
  54663. * @returns the new ActionEvent
  54664. */
  54665. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  54666. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  54667. };
  54668. return ActionEvent;
  54669. }());
  54670. BABYLON.ActionEvent = ActionEvent;
  54671. /**
  54672. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  54673. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  54674. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54675. */
  54676. var ActionManager = /** @class */ (function () {
  54677. /**
  54678. * Creates a new action manager
  54679. * @param scene defines the hosting scene
  54680. */
  54681. function ActionManager(scene) {
  54682. // Members
  54683. /** Gets the list of actions */
  54684. this.actions = new Array();
  54685. /** Gets the cursor to use when hovering items */
  54686. this.hoverCursor = '';
  54687. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54688. scene.actionManagers.push(this);
  54689. }
  54690. // Methods
  54691. /**
  54692. * Releases all associated resources
  54693. */
  54694. ActionManager.prototype.dispose = function () {
  54695. var index = this._scene.actionManagers.indexOf(this);
  54696. for (var i = 0; i < this.actions.length; i++) {
  54697. var action = this.actions[i];
  54698. ActionManager.Triggers[action.trigger]--;
  54699. if (ActionManager.Triggers[action.trigger] === 0) {
  54700. delete ActionManager.Triggers[action.trigger];
  54701. }
  54702. }
  54703. if (index > -1) {
  54704. this._scene.actionManagers.splice(index, 1);
  54705. }
  54706. };
  54707. /**
  54708. * Gets hosting scene
  54709. * @returns the hosting scene
  54710. */
  54711. ActionManager.prototype.getScene = function () {
  54712. return this._scene;
  54713. };
  54714. /**
  54715. * Does this action manager handles actions of any of the given triggers
  54716. * @param triggers defines the triggers to be tested
  54717. * @return a boolean indicating whether one (or more) of the triggers is handled
  54718. */
  54719. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  54720. for (var index = 0; index < this.actions.length; index++) {
  54721. var action = this.actions[index];
  54722. if (triggers.indexOf(action.trigger) > -1) {
  54723. return true;
  54724. }
  54725. }
  54726. return false;
  54727. };
  54728. /**
  54729. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  54730. * speed.
  54731. * @param triggerA defines the trigger to be tested
  54732. * @param triggerB defines the trigger to be tested
  54733. * @return a boolean indicating whether one (or more) of the triggers is handled
  54734. */
  54735. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  54736. for (var index = 0; index < this.actions.length; index++) {
  54737. var action = this.actions[index];
  54738. if (triggerA == action.trigger || triggerB == action.trigger) {
  54739. return true;
  54740. }
  54741. }
  54742. return false;
  54743. };
  54744. /**
  54745. * Does this action manager handles actions of a given trigger
  54746. * @param trigger defines the trigger to be tested
  54747. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  54748. * @return whether the trigger is handled
  54749. */
  54750. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54751. for (var index = 0; index < this.actions.length; index++) {
  54752. var action = this.actions[index];
  54753. if (action.trigger === trigger) {
  54754. if (parameterPredicate) {
  54755. if (parameterPredicate(action.getTriggerParameter())) {
  54756. return true;
  54757. }
  54758. }
  54759. else {
  54760. return true;
  54761. }
  54762. }
  54763. }
  54764. return false;
  54765. };
  54766. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54767. /**
  54768. * Does this action manager has pointer triggers
  54769. */
  54770. get: function () {
  54771. for (var index = 0; index < this.actions.length; index++) {
  54772. var action = this.actions[index];
  54773. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  54774. return true;
  54775. }
  54776. }
  54777. return false;
  54778. },
  54779. enumerable: true,
  54780. configurable: true
  54781. });
  54782. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54783. /**
  54784. * Does this action manager has pick triggers
  54785. */
  54786. get: function () {
  54787. for (var index = 0; index < this.actions.length; index++) {
  54788. var action = this.actions[index];
  54789. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  54790. return true;
  54791. }
  54792. }
  54793. return false;
  54794. },
  54795. enumerable: true,
  54796. configurable: true
  54797. });
  54798. Object.defineProperty(ActionManager, "HasTriggers", {
  54799. /**
  54800. * Does exist one action manager with at least one trigger
  54801. **/
  54802. get: function () {
  54803. for (var t in ActionManager.Triggers) {
  54804. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54805. return true;
  54806. }
  54807. }
  54808. return false;
  54809. },
  54810. enumerable: true,
  54811. configurable: true
  54812. });
  54813. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54814. /**
  54815. * Does exist one action manager with at least one pick trigger
  54816. **/
  54817. get: function () {
  54818. for (var t in ActionManager.Triggers) {
  54819. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54820. var t_int = parseInt(t);
  54821. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  54822. return true;
  54823. }
  54824. }
  54825. }
  54826. return false;
  54827. },
  54828. enumerable: true,
  54829. configurable: true
  54830. });
  54831. /**
  54832. * Does exist one action manager that handles actions of a given trigger
  54833. * @param trigger defines the trigger to be tested
  54834. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54835. **/
  54836. ActionManager.HasSpecificTrigger = function (trigger) {
  54837. for (var t in ActionManager.Triggers) {
  54838. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54839. var t_int = parseInt(t);
  54840. if (t_int === trigger) {
  54841. return true;
  54842. }
  54843. }
  54844. }
  54845. return false;
  54846. };
  54847. /**
  54848. * Registers an action to this action manager
  54849. * @param action defines the action to be registered
  54850. * @return the action amended (prepared) after registration
  54851. */
  54852. ActionManager.prototype.registerAction = function (action) {
  54853. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54854. if (this.getScene().actionManager !== this) {
  54855. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54856. return null;
  54857. }
  54858. }
  54859. this.actions.push(action);
  54860. if (ActionManager.Triggers[action.trigger]) {
  54861. ActionManager.Triggers[action.trigger]++;
  54862. }
  54863. else {
  54864. ActionManager.Triggers[action.trigger] = 1;
  54865. }
  54866. action._actionManager = this;
  54867. action._prepare();
  54868. return action;
  54869. };
  54870. /**
  54871. * Unregisters an action to this action manager
  54872. * @param action defines the action to be unregistered
  54873. * @return a boolean indicating whether the action has been unregistered
  54874. */
  54875. ActionManager.prototype.unregisterAction = function (action) {
  54876. var index = this.actions.indexOf(action);
  54877. if (index !== -1) {
  54878. this.actions.splice(index, 1);
  54879. ActionManager.Triggers[action.trigger] -= 1;
  54880. if (ActionManager.Triggers[action.trigger] === 0) {
  54881. delete ActionManager.Triggers[action.trigger];
  54882. }
  54883. delete action._actionManager;
  54884. return true;
  54885. }
  54886. return false;
  54887. };
  54888. /**
  54889. * Process a specific trigger
  54890. * @param trigger defines the trigger to process
  54891. * @param evt defines the event details to be processed
  54892. */
  54893. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54894. for (var index = 0; index < this.actions.length; index++) {
  54895. var action = this.actions[index];
  54896. if (action.trigger === trigger) {
  54897. if (evt) {
  54898. if (trigger === ActionManager.OnKeyUpTrigger
  54899. || trigger === ActionManager.OnKeyDownTrigger) {
  54900. var parameter = action.getTriggerParameter();
  54901. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54902. if (!parameter.toLowerCase) {
  54903. continue;
  54904. }
  54905. var lowerCase = parameter.toLowerCase();
  54906. if (lowerCase !== evt.sourceEvent.key) {
  54907. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54908. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54909. if (actualkey !== lowerCase) {
  54910. continue;
  54911. }
  54912. }
  54913. }
  54914. }
  54915. }
  54916. action._executeCurrent(evt);
  54917. }
  54918. }
  54919. };
  54920. /** @hidden */
  54921. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54922. var properties = propertyPath.split(".");
  54923. for (var index = 0; index < properties.length - 1; index++) {
  54924. target = target[properties[index]];
  54925. }
  54926. return target;
  54927. };
  54928. /** @hidden */
  54929. ActionManager.prototype._getProperty = function (propertyPath) {
  54930. var properties = propertyPath.split(".");
  54931. return properties[properties.length - 1];
  54932. };
  54933. /**
  54934. * Serialize this manager to a JSON object
  54935. * @param name defines the property name to store this manager
  54936. * @returns a JSON representation of this manager
  54937. */
  54938. ActionManager.prototype.serialize = function (name) {
  54939. var root = {
  54940. children: new Array(),
  54941. name: name,
  54942. type: 3,
  54943. properties: new Array() // Empty for root but required
  54944. };
  54945. for (var i = 0; i < this.actions.length; i++) {
  54946. var triggerObject = {
  54947. type: 0,
  54948. children: new Array(),
  54949. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54950. properties: new Array()
  54951. };
  54952. var triggerOptions = this.actions[i].triggerOptions;
  54953. if (triggerOptions && typeof triggerOptions !== "number") {
  54954. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54955. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54956. }
  54957. else {
  54958. var parameter = {};
  54959. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54960. if (triggerOptions.parameter.mesh) {
  54961. parameter._meshId = triggerOptions.parameter.mesh.id;
  54962. }
  54963. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54964. }
  54965. }
  54966. // Serialize child action, recursively
  54967. this.actions[i].serialize(triggerObject);
  54968. // Add serialized trigger
  54969. root.children.push(triggerObject);
  54970. }
  54971. return root;
  54972. };
  54973. /**
  54974. * Creates a new ActionManager from a JSON data
  54975. * @param parsedActions defines the JSON data to read from
  54976. * @param object defines the hosting mesh
  54977. * @param scene defines the hosting scene
  54978. */
  54979. ActionManager.Parse = function (parsedActions, object, scene) {
  54980. var actionManager = new ActionManager(scene);
  54981. if (object === null)
  54982. scene.actionManager = actionManager;
  54983. else
  54984. object.actionManager = actionManager;
  54985. // instanciate a new object
  54986. var instanciate = function (name, params) {
  54987. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54988. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54989. newInstance.constructor.apply(newInstance, params);
  54990. return newInstance;
  54991. };
  54992. var parseParameter = function (name, value, target, propertyPath) {
  54993. if (propertyPath === null) {
  54994. // String, boolean or float
  54995. var floatValue = parseFloat(value);
  54996. if (value === "true" || value === "false")
  54997. return value === "true";
  54998. else
  54999. return isNaN(floatValue) ? value : floatValue;
  55000. }
  55001. var effectiveTarget = propertyPath.split(".");
  55002. var values = value.split(",");
  55003. // Get effective Target
  55004. for (var i = 0; i < effectiveTarget.length; i++) {
  55005. target = target[effectiveTarget[i]];
  55006. }
  55007. // Return appropriate value with its type
  55008. if (typeof (target) === "boolean")
  55009. return values[0] === "true";
  55010. if (typeof (target) === "string")
  55011. return values[0];
  55012. // Parameters with multiple values such as Vector3 etc.
  55013. var split = new Array();
  55014. for (var i = 0; i < values.length; i++)
  55015. split.push(parseFloat(values[i]));
  55016. if (target instanceof BABYLON.Vector3)
  55017. return BABYLON.Vector3.FromArray(split);
  55018. if (target instanceof BABYLON.Vector4)
  55019. return BABYLON.Vector4.FromArray(split);
  55020. if (target instanceof BABYLON.Color3)
  55021. return BABYLON.Color3.FromArray(split);
  55022. if (target instanceof BABYLON.Color4)
  55023. return BABYLON.Color4.FromArray(split);
  55024. return parseFloat(values[0]);
  55025. };
  55026. // traverse graph per trigger
  55027. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55028. if (combineArray === void 0) { combineArray = null; }
  55029. if (parsedAction.detached)
  55030. return;
  55031. var parameters = new Array();
  55032. var target = null;
  55033. var propertyPath = null;
  55034. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55035. // Parameters
  55036. if (parsedAction.type === 2)
  55037. parameters.push(actionManager);
  55038. else
  55039. parameters.push(trigger);
  55040. if (combine) {
  55041. var actions = new Array();
  55042. for (var j = 0; j < parsedAction.combine.length; j++) {
  55043. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55044. }
  55045. parameters.push(actions);
  55046. }
  55047. else {
  55048. for (var i = 0; i < parsedAction.properties.length; i++) {
  55049. var value = parsedAction.properties[i].value;
  55050. var name = parsedAction.properties[i].name;
  55051. var targetType = parsedAction.properties[i].targetType;
  55052. if (name === "target")
  55053. if (targetType !== null && targetType === "SceneProperties")
  55054. value = target = scene;
  55055. else
  55056. value = target = scene.getNodeByName(value);
  55057. else if (name === "parent")
  55058. value = scene.getNodeByName(value);
  55059. else if (name === "sound") {
  55060. // Can not externalize to component, so only checks for the presence off the API.
  55061. if (scene.getSoundByName) {
  55062. value = scene.getSoundByName(value);
  55063. }
  55064. }
  55065. else if (name !== "propertyPath") {
  55066. if (parsedAction.type === 2 && name === "operator")
  55067. value = BABYLON.ValueCondition[value];
  55068. else
  55069. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55070. }
  55071. else {
  55072. propertyPath = value;
  55073. }
  55074. parameters.push(value);
  55075. }
  55076. }
  55077. if (combineArray === null) {
  55078. parameters.push(condition);
  55079. }
  55080. else {
  55081. parameters.push(null);
  55082. }
  55083. // If interpolate value action
  55084. if (parsedAction.name === "InterpolateValueAction") {
  55085. var param = parameters[parameters.length - 2];
  55086. parameters[parameters.length - 1] = param;
  55087. parameters[parameters.length - 2] = condition;
  55088. }
  55089. // Action or condition(s) and not CombineAction
  55090. var newAction = instanciate(parsedAction.name, parameters);
  55091. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55092. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55093. if (action)
  55094. action.then(nothing);
  55095. else
  55096. actionManager.registerAction(nothing);
  55097. action = nothing;
  55098. }
  55099. if (combineArray === null) {
  55100. if (newAction instanceof BABYLON.Condition) {
  55101. condition = newAction;
  55102. newAction = action;
  55103. }
  55104. else {
  55105. condition = null;
  55106. if (action)
  55107. action.then(newAction);
  55108. else
  55109. actionManager.registerAction(newAction);
  55110. }
  55111. }
  55112. else {
  55113. combineArray.push(newAction);
  55114. }
  55115. for (var i = 0; i < parsedAction.children.length; i++)
  55116. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55117. };
  55118. // triggers
  55119. for (var i = 0; i < parsedActions.children.length; i++) {
  55120. var triggerParams;
  55121. var trigger = parsedActions.children[i];
  55122. if (trigger.properties.length > 0) {
  55123. var param = trigger.properties[0].value;
  55124. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55125. if (value._meshId) {
  55126. value.mesh = scene.getMeshByID(value._meshId);
  55127. }
  55128. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55129. }
  55130. else
  55131. triggerParams = ActionManager[trigger.name];
  55132. for (var j = 0; j < trigger.children.length; j++) {
  55133. if (!trigger.detached)
  55134. traverse(trigger.children[j], triggerParams, null, null);
  55135. }
  55136. }
  55137. };
  55138. /**
  55139. * Get a trigger name by index
  55140. * @param trigger defines the trigger index
  55141. * @returns a trigger name
  55142. */
  55143. ActionManager.GetTriggerName = function (trigger) {
  55144. switch (trigger) {
  55145. case 0: return "NothingTrigger";
  55146. case 1: return "OnPickTrigger";
  55147. case 2: return "OnLeftPickTrigger";
  55148. case 3: return "OnRightPickTrigger";
  55149. case 4: return "OnCenterPickTrigger";
  55150. case 5: return "OnPickDownTrigger";
  55151. case 6: return "OnPickUpTrigger";
  55152. case 7: return "OnLongPressTrigger";
  55153. case 8: return "OnPointerOverTrigger";
  55154. case 9: return "OnPointerOutTrigger";
  55155. case 10: return "OnEveryFrameTrigger";
  55156. case 11: return "OnIntersectionEnterTrigger";
  55157. case 12: return "OnIntersectionExitTrigger";
  55158. case 13: return "OnKeyDownTrigger";
  55159. case 14: return "OnKeyUpTrigger";
  55160. case 15: return "OnPickOutTrigger";
  55161. default: return "";
  55162. }
  55163. };
  55164. /**
  55165. * Nothing
  55166. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55167. */
  55168. ActionManager.NothingTrigger = 0;
  55169. /**
  55170. * On pick
  55171. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55172. */
  55173. ActionManager.OnPickTrigger = 1;
  55174. /**
  55175. * On left pick
  55176. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55177. */
  55178. ActionManager.OnLeftPickTrigger = 2;
  55179. /**
  55180. * On right pick
  55181. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55182. */
  55183. ActionManager.OnRightPickTrigger = 3;
  55184. /**
  55185. * On center pick
  55186. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55187. */
  55188. ActionManager.OnCenterPickTrigger = 4;
  55189. /**
  55190. * On pick down
  55191. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55192. */
  55193. ActionManager.OnPickDownTrigger = 5;
  55194. /**
  55195. * On double pick
  55196. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55197. */
  55198. ActionManager.OnDoublePickTrigger = 6;
  55199. /**
  55200. * On pick up
  55201. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55202. */
  55203. ActionManager.OnPickUpTrigger = 7;
  55204. /**
  55205. * On pick out.
  55206. * This trigger will only be raised if you also declared a OnPickDown
  55207. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55208. */
  55209. ActionManager.OnPickOutTrigger = 16;
  55210. /**
  55211. * On long press
  55212. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55213. */
  55214. ActionManager.OnLongPressTrigger = 8;
  55215. /**
  55216. * On pointer over
  55217. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55218. */
  55219. ActionManager.OnPointerOverTrigger = 9;
  55220. /**
  55221. * On pointer out
  55222. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55223. */
  55224. ActionManager.OnPointerOutTrigger = 10;
  55225. /**
  55226. * On every frame
  55227. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55228. */
  55229. ActionManager.OnEveryFrameTrigger = 11;
  55230. /**
  55231. * On intersection enter
  55232. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55233. */
  55234. ActionManager.OnIntersectionEnterTrigger = 12;
  55235. /**
  55236. * On intersection exit
  55237. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55238. */
  55239. ActionManager.OnIntersectionExitTrigger = 13;
  55240. /**
  55241. * On key down
  55242. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55243. */
  55244. ActionManager.OnKeyDownTrigger = 14;
  55245. /**
  55246. * On key up
  55247. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55248. */
  55249. ActionManager.OnKeyUpTrigger = 15;
  55250. /** Gets the list of active triggers */
  55251. ActionManager.Triggers = {};
  55252. return ActionManager;
  55253. }());
  55254. BABYLON.ActionManager = ActionManager;
  55255. })(BABYLON || (BABYLON = {}));
  55256. //# sourceMappingURL=babylon.actionManager.js.map
  55257. var BABYLON;
  55258. (function (BABYLON) {
  55259. /**
  55260. * This defines an action responsible to change the value of a property
  55261. * by interpolating between its current value and the newly set one once triggered.
  55262. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55263. */
  55264. var InterpolateValueAction = /** @class */ (function (_super) {
  55265. __extends(InterpolateValueAction, _super);
  55266. /**
  55267. * Instantiate the action
  55268. * @param triggerOptions defines the trigger options
  55269. * @param target defines the object containing the value to interpolate
  55270. * @param propertyPath defines the path to the property in the target object
  55271. * @param value defines the target value at the end of the interpolation
  55272. * @param duration deines the time it will take for the property to interpolate to the value.
  55273. * @param condition defines the trigger related conditions
  55274. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55275. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55276. */
  55277. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55278. if (duration === void 0) { duration = 1000; }
  55279. var _this = _super.call(this, triggerOptions, condition) || this;
  55280. /**
  55281. * Defines the time it will take for the property to interpolate to the value.
  55282. */
  55283. _this.duration = 1000;
  55284. /**
  55285. * Observable triggered once the interpolation animation has been done.
  55286. */
  55287. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55288. _this.propertyPath = propertyPath;
  55289. _this.value = value;
  55290. _this.duration = duration;
  55291. _this.stopOtherAnimations = stopOtherAnimations;
  55292. _this.onInterpolationDone = onInterpolationDone;
  55293. _this._target = _this._effectiveTarget = target;
  55294. return _this;
  55295. }
  55296. /** @hidden */
  55297. InterpolateValueAction.prototype._prepare = function () {
  55298. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55299. this._property = this._getProperty(this.propertyPath);
  55300. };
  55301. /**
  55302. * Execute the action starts the value interpolation.
  55303. */
  55304. InterpolateValueAction.prototype.execute = function () {
  55305. var _this = this;
  55306. var scene = this._actionManager.getScene();
  55307. var keys = [
  55308. {
  55309. frame: 0,
  55310. value: this._effectiveTarget[this._property]
  55311. }, {
  55312. frame: 100,
  55313. value: this.value
  55314. }
  55315. ];
  55316. var dataType;
  55317. if (typeof this.value === "number") {
  55318. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55319. }
  55320. else if (this.value instanceof BABYLON.Color3) {
  55321. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55322. }
  55323. else if (this.value instanceof BABYLON.Vector3) {
  55324. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55325. }
  55326. else if (this.value instanceof BABYLON.Matrix) {
  55327. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55328. }
  55329. else if (this.value instanceof BABYLON.Quaternion) {
  55330. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55331. }
  55332. else {
  55333. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55334. return;
  55335. }
  55336. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55337. animation.setKeys(keys);
  55338. if (this.stopOtherAnimations) {
  55339. scene.stopAnimation(this._effectiveTarget);
  55340. }
  55341. var wrapper = function () {
  55342. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55343. if (_this.onInterpolationDone) {
  55344. _this.onInterpolationDone();
  55345. }
  55346. };
  55347. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55348. };
  55349. /**
  55350. * Serializes the actions and its related information.
  55351. * @param parent defines the object to serialize in
  55352. * @returns the serialized object
  55353. */
  55354. InterpolateValueAction.prototype.serialize = function (parent) {
  55355. return _super.prototype._serialize.call(this, {
  55356. name: "InterpolateValueAction",
  55357. properties: [
  55358. BABYLON.Action._GetTargetProperty(this._target),
  55359. { name: "propertyPath", value: this.propertyPath },
  55360. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55361. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55362. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55363. ]
  55364. }, parent);
  55365. };
  55366. return InterpolateValueAction;
  55367. }(BABYLON.Action));
  55368. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55369. })(BABYLON || (BABYLON = {}));
  55370. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55371. var BABYLON;
  55372. (function (BABYLON) {
  55373. /**
  55374. * This defines an action responsible to toggle a boolean once triggered.
  55375. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55376. */
  55377. var SwitchBooleanAction = /** @class */ (function (_super) {
  55378. __extends(SwitchBooleanAction, _super);
  55379. /**
  55380. * Instantiate the action
  55381. * @param triggerOptions defines the trigger options
  55382. * @param target defines the object containing the boolean
  55383. * @param propertyPath defines the path to the boolean property in the target object
  55384. * @param condition defines the trigger related conditions
  55385. */
  55386. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55387. var _this = _super.call(this, triggerOptions, condition) || this;
  55388. _this.propertyPath = propertyPath;
  55389. _this._target = _this._effectiveTarget = target;
  55390. return _this;
  55391. }
  55392. /** @hidden */
  55393. SwitchBooleanAction.prototype._prepare = function () {
  55394. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55395. this._property = this._getProperty(this.propertyPath);
  55396. };
  55397. /**
  55398. * Execute the action toggle the boolean value.
  55399. */
  55400. SwitchBooleanAction.prototype.execute = function () {
  55401. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55402. };
  55403. /**
  55404. * Serializes the actions and its related information.
  55405. * @param parent defines the object to serialize in
  55406. * @returns the serialized object
  55407. */
  55408. SwitchBooleanAction.prototype.serialize = function (parent) {
  55409. return _super.prototype._serialize.call(this, {
  55410. name: "SwitchBooleanAction",
  55411. properties: [
  55412. BABYLON.Action._GetTargetProperty(this._target),
  55413. { name: "propertyPath", value: this.propertyPath }
  55414. ]
  55415. }, parent);
  55416. };
  55417. return SwitchBooleanAction;
  55418. }(BABYLON.Action));
  55419. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55420. /**
  55421. * This defines an action responsible to set a the state field of the target
  55422. * to a desired value once triggered.
  55423. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55424. */
  55425. var SetStateAction = /** @class */ (function (_super) {
  55426. __extends(SetStateAction, _super);
  55427. /**
  55428. * Instantiate the action
  55429. * @param triggerOptions defines the trigger options
  55430. * @param target defines the object containing the state property
  55431. * @param value defines the value to store in the state field
  55432. * @param condition defines the trigger related conditions
  55433. */
  55434. function SetStateAction(triggerOptions, target, value, condition) {
  55435. var _this = _super.call(this, triggerOptions, condition) || this;
  55436. _this.value = value;
  55437. _this._target = target;
  55438. return _this;
  55439. }
  55440. /**
  55441. * Execute the action and store the value on the target state property.
  55442. */
  55443. SetStateAction.prototype.execute = function () {
  55444. this._target.state = this.value;
  55445. };
  55446. /**
  55447. * Serializes the actions and its related information.
  55448. * @param parent defines the object to serialize in
  55449. * @returns the serialized object
  55450. */
  55451. SetStateAction.prototype.serialize = function (parent) {
  55452. return _super.prototype._serialize.call(this, {
  55453. name: "SetStateAction",
  55454. properties: [
  55455. BABYLON.Action._GetTargetProperty(this._target),
  55456. { name: "value", value: this.value }
  55457. ]
  55458. }, parent);
  55459. };
  55460. return SetStateAction;
  55461. }(BABYLON.Action));
  55462. BABYLON.SetStateAction = SetStateAction;
  55463. /**
  55464. * This defines an action responsible to set a property of the target
  55465. * to a desired value once triggered.
  55466. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55467. */
  55468. var SetValueAction = /** @class */ (function (_super) {
  55469. __extends(SetValueAction, _super);
  55470. /**
  55471. * Instantiate the action
  55472. * @param triggerOptions defines the trigger options
  55473. * @param target defines the object containing the property
  55474. * @param propertyPath defines the path of the property to set in the target
  55475. * @param value defines the value to set in the property
  55476. * @param condition defines the trigger related conditions
  55477. */
  55478. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55479. var _this = _super.call(this, triggerOptions, condition) || this;
  55480. _this.propertyPath = propertyPath;
  55481. _this.value = value;
  55482. _this._target = _this._effectiveTarget = target;
  55483. return _this;
  55484. }
  55485. /** @hidden */
  55486. SetValueAction.prototype._prepare = function () {
  55487. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55488. this._property = this._getProperty(this.propertyPath);
  55489. };
  55490. /**
  55491. * Execute the action and set the targetted property to the desired value.
  55492. */
  55493. SetValueAction.prototype.execute = function () {
  55494. this._effectiveTarget[this._property] = this.value;
  55495. if (this._target.markAsDirty) {
  55496. this._target.markAsDirty(this._property);
  55497. }
  55498. };
  55499. /**
  55500. * Serializes the actions and its related information.
  55501. * @param parent defines the object to serialize in
  55502. * @returns the serialized object
  55503. */
  55504. SetValueAction.prototype.serialize = function (parent) {
  55505. return _super.prototype._serialize.call(this, {
  55506. name: "SetValueAction",
  55507. properties: [
  55508. BABYLON.Action._GetTargetProperty(this._target),
  55509. { name: "propertyPath", value: this.propertyPath },
  55510. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55511. ]
  55512. }, parent);
  55513. };
  55514. return SetValueAction;
  55515. }(BABYLON.Action));
  55516. BABYLON.SetValueAction = SetValueAction;
  55517. /**
  55518. * This defines an action responsible to increment the target value
  55519. * to a desired value once triggered.
  55520. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55521. */
  55522. var IncrementValueAction = /** @class */ (function (_super) {
  55523. __extends(IncrementValueAction, _super);
  55524. /**
  55525. * Instantiate the action
  55526. * @param triggerOptions defines the trigger options
  55527. * @param target defines the object containing the property
  55528. * @param propertyPath defines the path of the property to increment in the target
  55529. * @param value defines the value value we should increment the property by
  55530. * @param condition defines the trigger related conditions
  55531. */
  55532. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  55533. var _this = _super.call(this, triggerOptions, condition) || this;
  55534. _this.propertyPath = propertyPath;
  55535. _this.value = value;
  55536. _this._target = _this._effectiveTarget = target;
  55537. return _this;
  55538. }
  55539. /** @hidden */
  55540. IncrementValueAction.prototype._prepare = function () {
  55541. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55542. this._property = this._getProperty(this.propertyPath);
  55543. if (typeof this._effectiveTarget[this._property] !== "number") {
  55544. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  55545. }
  55546. };
  55547. /**
  55548. * Execute the action and increment the target of the value amount.
  55549. */
  55550. IncrementValueAction.prototype.execute = function () {
  55551. this._effectiveTarget[this._property] += this.value;
  55552. if (this._target.markAsDirty) {
  55553. this._target.markAsDirty(this._property);
  55554. }
  55555. };
  55556. /**
  55557. * Serializes the actions and its related information.
  55558. * @param parent defines the object to serialize in
  55559. * @returns the serialized object
  55560. */
  55561. IncrementValueAction.prototype.serialize = function (parent) {
  55562. return _super.prototype._serialize.call(this, {
  55563. name: "IncrementValueAction",
  55564. properties: [
  55565. BABYLON.Action._GetTargetProperty(this._target),
  55566. { name: "propertyPath", value: this.propertyPath },
  55567. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55568. ]
  55569. }, parent);
  55570. };
  55571. return IncrementValueAction;
  55572. }(BABYLON.Action));
  55573. BABYLON.IncrementValueAction = IncrementValueAction;
  55574. /**
  55575. * This defines an action responsible to start an animation once triggered.
  55576. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55577. */
  55578. var PlayAnimationAction = /** @class */ (function (_super) {
  55579. __extends(PlayAnimationAction, _super);
  55580. /**
  55581. * Instantiate the action
  55582. * @param triggerOptions defines the trigger options
  55583. * @param target defines the target animation or animation name
  55584. * @param from defines from where the animation should start (animation frame)
  55585. * @param end defines where the animation should stop (animation frame)
  55586. * @param loop defines if the animation should loop or stop after the first play
  55587. * @param condition defines the trigger related conditions
  55588. */
  55589. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  55590. var _this = _super.call(this, triggerOptions, condition) || this;
  55591. _this.from = from;
  55592. _this.to = to;
  55593. _this.loop = loop;
  55594. _this._target = target;
  55595. return _this;
  55596. }
  55597. /** @hidden */
  55598. PlayAnimationAction.prototype._prepare = function () {
  55599. };
  55600. /**
  55601. * Execute the action and play the animation.
  55602. */
  55603. PlayAnimationAction.prototype.execute = function () {
  55604. var scene = this._actionManager.getScene();
  55605. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  55606. };
  55607. /**
  55608. * Serializes the actions and its related information.
  55609. * @param parent defines the object to serialize in
  55610. * @returns the serialized object
  55611. */
  55612. PlayAnimationAction.prototype.serialize = function (parent) {
  55613. return _super.prototype._serialize.call(this, {
  55614. name: "PlayAnimationAction",
  55615. properties: [
  55616. BABYLON.Action._GetTargetProperty(this._target),
  55617. { name: "from", value: String(this.from) },
  55618. { name: "to", value: String(this.to) },
  55619. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  55620. ]
  55621. }, parent);
  55622. };
  55623. return PlayAnimationAction;
  55624. }(BABYLON.Action));
  55625. BABYLON.PlayAnimationAction = PlayAnimationAction;
  55626. /**
  55627. * This defines an action responsible to stop an animation once triggered.
  55628. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55629. */
  55630. var StopAnimationAction = /** @class */ (function (_super) {
  55631. __extends(StopAnimationAction, _super);
  55632. /**
  55633. * Instantiate the action
  55634. * @param triggerOptions defines the trigger options
  55635. * @param target defines the target animation or animation name
  55636. * @param condition defines the trigger related conditions
  55637. */
  55638. function StopAnimationAction(triggerOptions, target, condition) {
  55639. var _this = _super.call(this, triggerOptions, condition) || this;
  55640. _this._target = target;
  55641. return _this;
  55642. }
  55643. /** @hidden */
  55644. StopAnimationAction.prototype._prepare = function () {
  55645. };
  55646. /**
  55647. * Execute the action and stop the animation.
  55648. */
  55649. StopAnimationAction.prototype.execute = function () {
  55650. var scene = this._actionManager.getScene();
  55651. scene.stopAnimation(this._target);
  55652. };
  55653. /**
  55654. * Serializes the actions and its related information.
  55655. * @param parent defines the object to serialize in
  55656. * @returns the serialized object
  55657. */
  55658. StopAnimationAction.prototype.serialize = function (parent) {
  55659. return _super.prototype._serialize.call(this, {
  55660. name: "StopAnimationAction",
  55661. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  55662. }, parent);
  55663. };
  55664. return StopAnimationAction;
  55665. }(BABYLON.Action));
  55666. BABYLON.StopAnimationAction = StopAnimationAction;
  55667. /**
  55668. * This defines an action responsible that does nothing once triggered.
  55669. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55670. */
  55671. var DoNothingAction = /** @class */ (function (_super) {
  55672. __extends(DoNothingAction, _super);
  55673. /**
  55674. * Instantiate the action
  55675. * @param triggerOptions defines the trigger options
  55676. * @param condition defines the trigger related conditions
  55677. */
  55678. function DoNothingAction(triggerOptions, condition) {
  55679. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  55680. return _super.call(this, triggerOptions, condition) || this;
  55681. }
  55682. /**
  55683. * Execute the action and do nothing.
  55684. */
  55685. DoNothingAction.prototype.execute = function () {
  55686. };
  55687. /**
  55688. * Serializes the actions and its related information.
  55689. * @param parent defines the object to serialize in
  55690. * @returns the serialized object
  55691. */
  55692. DoNothingAction.prototype.serialize = function (parent) {
  55693. return _super.prototype._serialize.call(this, {
  55694. name: "DoNothingAction",
  55695. properties: []
  55696. }, parent);
  55697. };
  55698. return DoNothingAction;
  55699. }(BABYLON.Action));
  55700. BABYLON.DoNothingAction = DoNothingAction;
  55701. /**
  55702. * This defines an action responsible to trigger several actions once triggered.
  55703. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55704. */
  55705. var CombineAction = /** @class */ (function (_super) {
  55706. __extends(CombineAction, _super);
  55707. /**
  55708. * Instantiate the action
  55709. * @param triggerOptions defines the trigger options
  55710. * @param children defines the list of aggregated animations to run
  55711. * @param condition defines the trigger related conditions
  55712. */
  55713. function CombineAction(triggerOptions, children, condition) {
  55714. var _this = _super.call(this, triggerOptions, condition) || this;
  55715. _this.children = children;
  55716. return _this;
  55717. }
  55718. /** @hidden */
  55719. CombineAction.prototype._prepare = function () {
  55720. for (var index = 0; index < this.children.length; index++) {
  55721. this.children[index]._actionManager = this._actionManager;
  55722. this.children[index]._prepare();
  55723. }
  55724. };
  55725. /**
  55726. * Execute the action and executes all the aggregated actions.
  55727. */
  55728. CombineAction.prototype.execute = function (evt) {
  55729. for (var index = 0; index < this.children.length; index++) {
  55730. this.children[index].execute(evt);
  55731. }
  55732. };
  55733. /**
  55734. * Serializes the actions and its related information.
  55735. * @param parent defines the object to serialize in
  55736. * @returns the serialized object
  55737. */
  55738. CombineAction.prototype.serialize = function (parent) {
  55739. var serializationObject = _super.prototype._serialize.call(this, {
  55740. name: "CombineAction",
  55741. properties: [],
  55742. combine: []
  55743. }, parent);
  55744. for (var i = 0; i < this.children.length; i++) {
  55745. serializationObject.combine.push(this.children[i].serialize(null));
  55746. }
  55747. return serializationObject;
  55748. };
  55749. return CombineAction;
  55750. }(BABYLON.Action));
  55751. BABYLON.CombineAction = CombineAction;
  55752. /**
  55753. * This defines an action responsible to run code (external event) once triggered.
  55754. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55755. */
  55756. var ExecuteCodeAction = /** @class */ (function (_super) {
  55757. __extends(ExecuteCodeAction, _super);
  55758. /**
  55759. * Instantiate the action
  55760. * @param triggerOptions defines the trigger options
  55761. * @param func defines the callback function to run
  55762. * @param condition defines the trigger related conditions
  55763. */
  55764. function ExecuteCodeAction(triggerOptions, func, condition) {
  55765. var _this = _super.call(this, triggerOptions, condition) || this;
  55766. _this.func = func;
  55767. return _this;
  55768. }
  55769. /**
  55770. * Execute the action and run the attached code.
  55771. */
  55772. ExecuteCodeAction.prototype.execute = function (evt) {
  55773. this.func(evt);
  55774. };
  55775. return ExecuteCodeAction;
  55776. }(BABYLON.Action));
  55777. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  55778. /**
  55779. * This defines an action responsible to set the parent property of the target once triggered.
  55780. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55781. */
  55782. var SetParentAction = /** @class */ (function (_super) {
  55783. __extends(SetParentAction, _super);
  55784. /**
  55785. * Instantiate the action
  55786. * @param triggerOptions defines the trigger options
  55787. * @param target defines the target containing the parent property
  55788. * @param parent defines from where the animation should start (animation frame)
  55789. * @param condition defines the trigger related conditions
  55790. */
  55791. function SetParentAction(triggerOptions, target, parent, condition) {
  55792. var _this = _super.call(this, triggerOptions, condition) || this;
  55793. _this._target = target;
  55794. _this._parent = parent;
  55795. return _this;
  55796. }
  55797. /** @hidden */
  55798. SetParentAction.prototype._prepare = function () {
  55799. };
  55800. /**
  55801. * Execute the action and set the parent property.
  55802. */
  55803. SetParentAction.prototype.execute = function () {
  55804. if (this._target.parent === this._parent) {
  55805. return;
  55806. }
  55807. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  55808. invertParentWorldMatrix.invert();
  55809. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  55810. this._target.parent = this._parent;
  55811. };
  55812. /**
  55813. * Serializes the actions and its related information.
  55814. * @param parent defines the object to serialize in
  55815. * @returns the serialized object
  55816. */
  55817. SetParentAction.prototype.serialize = function (parent) {
  55818. return _super.prototype._serialize.call(this, {
  55819. name: "SetParentAction",
  55820. properties: [
  55821. BABYLON.Action._GetTargetProperty(this._target),
  55822. BABYLON.Action._GetTargetProperty(this._parent),
  55823. ]
  55824. }, parent);
  55825. };
  55826. return SetParentAction;
  55827. }(BABYLON.Action));
  55828. BABYLON.SetParentAction = SetParentAction;
  55829. })(BABYLON || (BABYLON = {}));
  55830. //# sourceMappingURL=babylon.directActions.js.map
  55831. var BABYLON;
  55832. (function (BABYLON) {
  55833. var SpriteManager = /** @class */ (function () {
  55834. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  55835. if (epsilon === void 0) { epsilon = 0.01; }
  55836. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55837. this.name = name;
  55838. this.sprites = new Array();
  55839. this.renderingGroupId = 0;
  55840. this.layerMask = 0x0FFFFFFF;
  55841. this.fogEnabled = true;
  55842. this.isPickable = false;
  55843. /**
  55844. * An event triggered when the manager is disposed.
  55845. */
  55846. this.onDisposeObservable = new BABYLON.Observable();
  55847. this._vertexBuffers = {};
  55848. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  55849. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  55850. }
  55851. this._capacity = capacity;
  55852. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  55853. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55854. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55855. if (cellSize.width && cellSize.height) {
  55856. this.cellWidth = cellSize.width;
  55857. this.cellHeight = cellSize.height;
  55858. }
  55859. else if (cellSize !== undefined) {
  55860. this.cellWidth = cellSize;
  55861. this.cellHeight = cellSize;
  55862. }
  55863. else {
  55864. return;
  55865. }
  55866. this._epsilon = epsilon;
  55867. this._scene = scene;
  55868. this._scene.spriteManagers.push(this);
  55869. var indices = [];
  55870. var index = 0;
  55871. for (var count = 0; count < capacity; count++) {
  55872. indices.push(index);
  55873. indices.push(index + 1);
  55874. indices.push(index + 2);
  55875. indices.push(index);
  55876. indices.push(index + 2);
  55877. indices.push(index + 3);
  55878. index += 4;
  55879. }
  55880. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  55881. // VBO
  55882. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  55883. this._vertexData = new Float32Array(capacity * 16 * 4);
  55884. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  55885. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  55886. var options = this._buffer.createVertexBuffer("options", 4, 4);
  55887. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  55888. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  55889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55890. this._vertexBuffers["options"] = options;
  55891. this._vertexBuffers["cellInfo"] = cellInfo;
  55892. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55893. // Effects
  55894. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  55895. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  55896. }
  55897. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  55898. set: function (callback) {
  55899. if (this._onDisposeObserver) {
  55900. this.onDisposeObservable.remove(this._onDisposeObserver);
  55901. }
  55902. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55903. },
  55904. enumerable: true,
  55905. configurable: true
  55906. });
  55907. Object.defineProperty(SpriteManager.prototype, "texture", {
  55908. get: function () {
  55909. return this._spriteTexture;
  55910. },
  55911. set: function (value) {
  55912. this._spriteTexture = value;
  55913. },
  55914. enumerable: true,
  55915. configurable: true
  55916. });
  55917. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  55918. var arrayOffset = index * 16;
  55919. if (offsetX === 0)
  55920. offsetX = this._epsilon;
  55921. else if (offsetX === 1)
  55922. offsetX = 1 - this._epsilon;
  55923. if (offsetY === 0)
  55924. offsetY = this._epsilon;
  55925. else if (offsetY === 1)
  55926. offsetY = 1 - this._epsilon;
  55927. this._vertexData[arrayOffset] = sprite.position.x;
  55928. this._vertexData[arrayOffset + 1] = sprite.position.y;
  55929. this._vertexData[arrayOffset + 2] = sprite.position.z;
  55930. this._vertexData[arrayOffset + 3] = sprite.angle;
  55931. this._vertexData[arrayOffset + 4] = sprite.width;
  55932. this._vertexData[arrayOffset + 5] = sprite.height;
  55933. this._vertexData[arrayOffset + 6] = offsetX;
  55934. this._vertexData[arrayOffset + 7] = offsetY;
  55935. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  55936. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  55937. var offset = (sprite.cellIndex / rowSize) >> 0;
  55938. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  55939. this._vertexData[arrayOffset + 11] = offset;
  55940. // Color
  55941. this._vertexData[arrayOffset + 12] = sprite.color.r;
  55942. this._vertexData[arrayOffset + 13] = sprite.color.g;
  55943. this._vertexData[arrayOffset + 14] = sprite.color.b;
  55944. this._vertexData[arrayOffset + 15] = sprite.color.a;
  55945. };
  55946. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  55947. var count = Math.min(this._capacity, this.sprites.length);
  55948. var min = BABYLON.Vector3.Zero();
  55949. var max = BABYLON.Vector3.Zero();
  55950. var distance = Number.MAX_VALUE;
  55951. var currentSprite = null;
  55952. var cameraSpacePosition = BABYLON.Vector3.Zero();
  55953. var cameraView = camera.getViewMatrix();
  55954. for (var index = 0; index < count; index++) {
  55955. var sprite = this.sprites[index];
  55956. if (!sprite) {
  55957. continue;
  55958. }
  55959. if (predicate) {
  55960. if (!predicate(sprite)) {
  55961. continue;
  55962. }
  55963. }
  55964. else if (!sprite.isPickable) {
  55965. continue;
  55966. }
  55967. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55968. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55969. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55970. if (ray.intersectsBoxMinMax(min, max)) {
  55971. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  55972. if (distance > currentDistance) {
  55973. distance = currentDistance;
  55974. currentSprite = sprite;
  55975. if (fastCheck) {
  55976. break;
  55977. }
  55978. }
  55979. }
  55980. }
  55981. if (currentSprite) {
  55982. var result = new BABYLON.PickingInfo();
  55983. result.hit = true;
  55984. result.pickedSprite = currentSprite;
  55985. result.distance = distance;
  55986. return result;
  55987. }
  55988. return null;
  55989. };
  55990. SpriteManager.prototype.render = function () {
  55991. // Check
  55992. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55993. return;
  55994. var engine = this._scene.getEngine();
  55995. var baseSize = this._spriteTexture.getBaseSize();
  55996. // Sprites
  55997. var deltaTime = engine.getDeltaTime();
  55998. var max = Math.min(this._capacity, this.sprites.length);
  55999. var rowSize = baseSize.width / this.cellWidth;
  56000. var offset = 0;
  56001. for (var index = 0; index < max; index++) {
  56002. var sprite = this.sprites[index];
  56003. if (!sprite || !sprite.isVisible) {
  56004. continue;
  56005. }
  56006. sprite._animate(deltaTime);
  56007. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56008. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56009. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56010. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56011. }
  56012. this._buffer.update(this._vertexData);
  56013. // Render
  56014. var effect = this._effectBase;
  56015. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56016. effect = this._effectFog;
  56017. }
  56018. engine.enableEffect(effect);
  56019. var viewMatrix = this._scene.getViewMatrix();
  56020. effect.setTexture("diffuseSampler", this._spriteTexture);
  56021. effect.setMatrix("view", viewMatrix);
  56022. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56023. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56024. // Fog
  56025. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56026. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56027. effect.setColor3("vFogColor", this._scene.fogColor);
  56028. }
  56029. // VBOs
  56030. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56031. // Draw order
  56032. engine.setDepthFunctionToLessOrEqual();
  56033. effect.setBool("alphaTest", true);
  56034. engine.setColorWrite(false);
  56035. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56036. engine.setColorWrite(true);
  56037. effect.setBool("alphaTest", false);
  56038. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56039. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56040. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56041. };
  56042. SpriteManager.prototype.dispose = function () {
  56043. if (this._buffer) {
  56044. this._buffer.dispose();
  56045. this._buffer = null;
  56046. }
  56047. if (this._indexBuffer) {
  56048. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56049. this._indexBuffer = null;
  56050. }
  56051. if (this._spriteTexture) {
  56052. this._spriteTexture.dispose();
  56053. this._spriteTexture = null;
  56054. }
  56055. // Remove from scene
  56056. var index = this._scene.spriteManagers.indexOf(this);
  56057. this._scene.spriteManagers.splice(index, 1);
  56058. // Callback
  56059. this.onDisposeObservable.notifyObservers(this);
  56060. this.onDisposeObservable.clear();
  56061. };
  56062. return SpriteManager;
  56063. }());
  56064. BABYLON.SpriteManager = SpriteManager;
  56065. })(BABYLON || (BABYLON = {}));
  56066. //# sourceMappingURL=babylon.spriteManager.js.map
  56067. var BABYLON;
  56068. (function (BABYLON) {
  56069. var Sprite = /** @class */ (function () {
  56070. function Sprite(name, manager) {
  56071. this.name = name;
  56072. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56073. this.width = 1.0;
  56074. this.height = 1.0;
  56075. this.angle = 0;
  56076. this.cellIndex = 0;
  56077. this.invertU = 0;
  56078. this.invertV = 0;
  56079. this.animations = new Array();
  56080. this.isPickable = false;
  56081. this._animationStarted = false;
  56082. this._loopAnimation = false;
  56083. this._fromIndex = 0;
  56084. this._toIndex = 0;
  56085. this._delay = 0;
  56086. this._direction = 1;
  56087. this._time = 0;
  56088. /**
  56089. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56090. */
  56091. this.isVisible = true;
  56092. this._manager = manager;
  56093. this._manager.sprites.push(this);
  56094. this.position = BABYLON.Vector3.Zero();
  56095. }
  56096. Object.defineProperty(Sprite.prototype, "size", {
  56097. get: function () {
  56098. return this.width;
  56099. },
  56100. set: function (value) {
  56101. this.width = value;
  56102. this.height = value;
  56103. },
  56104. enumerable: true,
  56105. configurable: true
  56106. });
  56107. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56108. this._fromIndex = from;
  56109. this._toIndex = to;
  56110. this._loopAnimation = loop;
  56111. this._delay = delay;
  56112. this._animationStarted = true;
  56113. this._direction = from < to ? 1 : -1;
  56114. this.cellIndex = from;
  56115. this._time = 0;
  56116. this._onAnimationEnd = onAnimationEnd;
  56117. };
  56118. Sprite.prototype.stopAnimation = function () {
  56119. this._animationStarted = false;
  56120. };
  56121. /** @hidden */
  56122. Sprite.prototype._animate = function (deltaTime) {
  56123. if (!this._animationStarted)
  56124. return;
  56125. this._time += deltaTime;
  56126. if (this._time > this._delay) {
  56127. this._time = this._time % this._delay;
  56128. this.cellIndex += this._direction;
  56129. if (this.cellIndex > this._toIndex) {
  56130. if (this._loopAnimation) {
  56131. this.cellIndex = this._fromIndex;
  56132. }
  56133. else {
  56134. this.cellIndex = this._toIndex;
  56135. this._animationStarted = false;
  56136. if (this._onAnimationEnd) {
  56137. this._onAnimationEnd();
  56138. }
  56139. if (this.disposeWhenFinishedAnimating) {
  56140. this.dispose();
  56141. }
  56142. }
  56143. }
  56144. }
  56145. };
  56146. Sprite.prototype.dispose = function () {
  56147. for (var i = 0; i < this._manager.sprites.length; i++) {
  56148. if (this._manager.sprites[i] == this) {
  56149. this._manager.sprites.splice(i, 1);
  56150. }
  56151. }
  56152. };
  56153. return Sprite;
  56154. }());
  56155. BABYLON.Sprite = Sprite;
  56156. })(BABYLON || (BABYLON = {}));
  56157. //# sourceMappingURL=babylon.sprite.js.map
  56158. var BABYLON;
  56159. (function (BABYLON) {
  56160. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56161. if (!BABYLON.PickingInfo) {
  56162. return null;
  56163. }
  56164. var pickingInfo = null;
  56165. if (!camera) {
  56166. if (!this.activeCamera) {
  56167. return null;
  56168. }
  56169. camera = this.activeCamera;
  56170. }
  56171. if (this.spriteManagers.length > 0) {
  56172. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56173. var spriteManager = this.spriteManagers[spriteIndex];
  56174. if (!spriteManager.isPickable) {
  56175. continue;
  56176. }
  56177. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56178. if (!result || !result.hit)
  56179. continue;
  56180. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  56181. continue;
  56182. pickingInfo = result;
  56183. if (fastCheck) {
  56184. break;
  56185. }
  56186. }
  56187. }
  56188. return pickingInfo || new BABYLON.PickingInfo();
  56189. };
  56190. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56191. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56192. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56193. };
  56194. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56195. if (!this._tempSpritePickingRay) {
  56196. return null;
  56197. }
  56198. if (!camera) {
  56199. if (!this.activeCamera) {
  56200. return null;
  56201. }
  56202. camera = this.activeCamera;
  56203. }
  56204. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56205. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56206. };
  56207. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56208. if (this._pointerOverSprite === sprite) {
  56209. return;
  56210. }
  56211. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56212. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56213. }
  56214. this._pointerOverSprite = sprite;
  56215. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56216. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56217. }
  56218. };
  56219. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56220. return this._pointerOverSprite;
  56221. };
  56222. /**
  56223. * Defines the sprite scene component responsible to manage sprites
  56224. * in a given scene.
  56225. */
  56226. var SpriteSceneComponent = /** @class */ (function () {
  56227. /**
  56228. * Creates a new instance of the component for the given scene
  56229. * @param scene Defines the scene to register the component in
  56230. */
  56231. function SpriteSceneComponent(scene) {
  56232. /**
  56233. * The component name helpfull to identify the component in the list of scene components.
  56234. */
  56235. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56236. this.scene = scene;
  56237. this.scene.spriteManagers = new Array();
  56238. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56239. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56240. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56241. this._spritePredicate = function (sprite) {
  56242. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  56243. };
  56244. }
  56245. /**
  56246. * Registers the component in a given scene
  56247. */
  56248. SpriteSceneComponent.prototype.register = function () {
  56249. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56250. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56251. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56252. };
  56253. /**
  56254. * Rebuilds the elements related to this component in case of
  56255. * context lost for instance.
  56256. */
  56257. SpriteSceneComponent.prototype.rebuild = function () {
  56258. /** Nothing to do for sprites */
  56259. };
  56260. /**
  56261. * Disposes the component and the associated ressources.
  56262. */
  56263. SpriteSceneComponent.prototype.dispose = function () {
  56264. this.scene.onBeforeSpritesRenderingObservable.clear();
  56265. this.scene.onAfterSpritesRenderingObservable.clear();
  56266. var spriteManagers = this.scene.spriteManagers;
  56267. while (spriteManagers.length) {
  56268. spriteManagers[0].dispose();
  56269. }
  56270. };
  56271. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56272. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56273. if (result) {
  56274. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56275. }
  56276. return result;
  56277. };
  56278. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56279. var scene = this.scene;
  56280. if (isMeshPicked) {
  56281. scene.setPointerOverSprite(null);
  56282. }
  56283. else {
  56284. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56285. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56286. scene.setPointerOverSprite(pickResult.pickedSprite);
  56287. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56288. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56289. }
  56290. else {
  56291. canvas.style.cursor = scene.hoverCursor;
  56292. }
  56293. }
  56294. else {
  56295. scene.setPointerOverSprite(null);
  56296. }
  56297. }
  56298. return pickResult;
  56299. };
  56300. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56301. var scene = this.scene;
  56302. scene._pickedDownSprite = null;
  56303. if (scene.spriteManagers.length > 0) {
  56304. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56305. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56306. if (pickResult.pickedSprite.actionManager) {
  56307. scene._pickedDownSprite = pickResult.pickedSprite;
  56308. switch (evt.button) {
  56309. case 0:
  56310. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56311. break;
  56312. case 1:
  56313. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56314. break;
  56315. case 2:
  56316. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56317. break;
  56318. }
  56319. if (pickResult.pickedSprite.actionManager) {
  56320. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56321. }
  56322. }
  56323. }
  56324. }
  56325. return pickResult;
  56326. };
  56327. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56328. var scene = this.scene;
  56329. if (scene.spriteManagers.length > 0) {
  56330. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56331. if (spritePickResult) {
  56332. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56333. if (spritePickResult.pickedSprite.actionManager) {
  56334. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56335. if (spritePickResult.pickedSprite.actionManager) {
  56336. if (!this.scene._isPointerSwiping()) {
  56337. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56338. }
  56339. }
  56340. }
  56341. }
  56342. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56343. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56344. }
  56345. }
  56346. }
  56347. return pickResult;
  56348. };
  56349. return SpriteSceneComponent;
  56350. }());
  56351. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56352. })(BABYLON || (BABYLON = {}));
  56353. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56354. var BABYLON;
  56355. (function (BABYLON) {
  56356. /**
  56357. * @hidden
  56358. */
  56359. var IntersectionInfo = /** @class */ (function () {
  56360. function IntersectionInfo(bu, bv, distance) {
  56361. this.bu = bu;
  56362. this.bv = bv;
  56363. this.distance = distance;
  56364. this.faceId = 0;
  56365. this.subMeshId = 0;
  56366. }
  56367. return IntersectionInfo;
  56368. }());
  56369. BABYLON.IntersectionInfo = IntersectionInfo;
  56370. /**
  56371. * Information about the result of picking within a scene
  56372. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56373. */
  56374. var PickingInfo = /** @class */ (function () {
  56375. function PickingInfo() {
  56376. /**
  56377. * If the pick collided with an object
  56378. */
  56379. this.hit = false;
  56380. /**
  56381. * Distance away where the pick collided
  56382. */
  56383. this.distance = 0;
  56384. /**
  56385. * The location of pick collision
  56386. */
  56387. this.pickedPoint = null;
  56388. /**
  56389. * The mesh corresponding the the pick collision
  56390. */
  56391. this.pickedMesh = null;
  56392. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56393. this.bu = 0;
  56394. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56395. this.bv = 0;
  56396. /** The id of the face on the mesh that was picked */
  56397. this.faceId = -1;
  56398. /** Id of the the submesh that was picked */
  56399. this.subMeshId = 0;
  56400. /** If a sprite was picked, this will be the sprite the pick collided with */
  56401. this.pickedSprite = null;
  56402. /**
  56403. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56404. */
  56405. this.originMesh = null;
  56406. /**
  56407. * The ray that was used to perform the picking.
  56408. */
  56409. this.ray = null;
  56410. }
  56411. /**
  56412. * Gets the normal correspodning to the face the pick collided with
  56413. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56414. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56415. * @returns The normal correspodning to the face the pick collided with
  56416. */
  56417. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56418. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56419. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56420. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56421. return null;
  56422. }
  56423. var indices = this.pickedMesh.getIndices();
  56424. if (!indices) {
  56425. return null;
  56426. }
  56427. var result;
  56428. if (useVerticesNormals) {
  56429. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56430. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56431. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56432. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56433. normal0 = normal0.scale(this.bu);
  56434. normal1 = normal1.scale(this.bv);
  56435. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56436. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56437. }
  56438. else {
  56439. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56440. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56441. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56442. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56443. var p1p2 = vertex1.subtract(vertex2);
  56444. var p3p2 = vertex3.subtract(vertex2);
  56445. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56446. }
  56447. if (useWorldCoordinates) {
  56448. var wm = this.pickedMesh.getWorldMatrix();
  56449. if (this.pickedMesh.nonUniformScaling) {
  56450. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  56451. wm = BABYLON.Tmp.Matrix[0];
  56452. wm.setTranslationFromFloats(0, 0, 0);
  56453. wm.invert();
  56454. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  56455. wm = BABYLON.Tmp.Matrix[1];
  56456. }
  56457. result = BABYLON.Vector3.TransformNormal(result, wm);
  56458. }
  56459. result.normalize();
  56460. return result;
  56461. };
  56462. /**
  56463. * Gets the texture coordinates of where the pick occured
  56464. * @returns the vector containing the coordnates of the texture
  56465. */
  56466. PickingInfo.prototype.getTextureCoordinates = function () {
  56467. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56468. return null;
  56469. }
  56470. var indices = this.pickedMesh.getIndices();
  56471. if (!indices) {
  56472. return null;
  56473. }
  56474. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56475. if (!uvs) {
  56476. return null;
  56477. }
  56478. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  56479. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  56480. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  56481. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  56482. uv1 = uv1.scale(this.bu);
  56483. uv2 = uv2.scale(this.bv);
  56484. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  56485. };
  56486. return PickingInfo;
  56487. }());
  56488. BABYLON.PickingInfo = PickingInfo;
  56489. })(BABYLON || (BABYLON = {}));
  56490. //# sourceMappingURL=babylon.pickingInfo.js.map
  56491. var BABYLON;
  56492. (function (BABYLON) {
  56493. var Ray = /** @class */ (function () {
  56494. function Ray(origin, direction, length) {
  56495. if (length === void 0) { length = Number.MAX_VALUE; }
  56496. this.origin = origin;
  56497. this.direction = direction;
  56498. this.length = length;
  56499. }
  56500. // Methods
  56501. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  56502. var d = 0.0;
  56503. var maxValue = Number.MAX_VALUE;
  56504. var inv;
  56505. var min;
  56506. var max;
  56507. var temp;
  56508. if (Math.abs(this.direction.x) < 0.0000001) {
  56509. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  56510. return false;
  56511. }
  56512. }
  56513. else {
  56514. inv = 1.0 / this.direction.x;
  56515. min = (minimum.x - this.origin.x) * inv;
  56516. max = (maximum.x - this.origin.x) * inv;
  56517. if (max === -Infinity) {
  56518. max = Infinity;
  56519. }
  56520. if (min > max) {
  56521. temp = min;
  56522. min = max;
  56523. max = temp;
  56524. }
  56525. d = Math.max(min, d);
  56526. maxValue = Math.min(max, maxValue);
  56527. if (d > maxValue) {
  56528. return false;
  56529. }
  56530. }
  56531. if (Math.abs(this.direction.y) < 0.0000001) {
  56532. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  56533. return false;
  56534. }
  56535. }
  56536. else {
  56537. inv = 1.0 / this.direction.y;
  56538. min = (minimum.y - this.origin.y) * inv;
  56539. max = (maximum.y - this.origin.y) * inv;
  56540. if (max === -Infinity) {
  56541. max = Infinity;
  56542. }
  56543. if (min > max) {
  56544. temp = min;
  56545. min = max;
  56546. max = temp;
  56547. }
  56548. d = Math.max(min, d);
  56549. maxValue = Math.min(max, maxValue);
  56550. if (d > maxValue) {
  56551. return false;
  56552. }
  56553. }
  56554. if (Math.abs(this.direction.z) < 0.0000001) {
  56555. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  56556. return false;
  56557. }
  56558. }
  56559. else {
  56560. inv = 1.0 / this.direction.z;
  56561. min = (minimum.z - this.origin.z) * inv;
  56562. max = (maximum.z - this.origin.z) * inv;
  56563. if (max === -Infinity) {
  56564. max = Infinity;
  56565. }
  56566. if (min > max) {
  56567. temp = min;
  56568. min = max;
  56569. max = temp;
  56570. }
  56571. d = Math.max(min, d);
  56572. maxValue = Math.min(max, maxValue);
  56573. if (d > maxValue) {
  56574. return false;
  56575. }
  56576. }
  56577. return true;
  56578. };
  56579. Ray.prototype.intersectsBox = function (box) {
  56580. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  56581. };
  56582. Ray.prototype.intersectsSphere = function (sphere) {
  56583. var x = sphere.center.x - this.origin.x;
  56584. var y = sphere.center.y - this.origin.y;
  56585. var z = sphere.center.z - this.origin.z;
  56586. var pyth = (x * x) + (y * y) + (z * z);
  56587. var rr = sphere.radius * sphere.radius;
  56588. if (pyth <= rr) {
  56589. return true;
  56590. }
  56591. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  56592. if (dot < 0.0) {
  56593. return false;
  56594. }
  56595. var temp = pyth - (dot * dot);
  56596. return temp <= rr;
  56597. };
  56598. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  56599. if (!this._edge1) {
  56600. this._edge1 = BABYLON.Vector3.Zero();
  56601. this._edge2 = BABYLON.Vector3.Zero();
  56602. this._pvec = BABYLON.Vector3.Zero();
  56603. this._tvec = BABYLON.Vector3.Zero();
  56604. this._qvec = BABYLON.Vector3.Zero();
  56605. }
  56606. vertex1.subtractToRef(vertex0, this._edge1);
  56607. vertex2.subtractToRef(vertex0, this._edge2);
  56608. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  56609. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  56610. if (det === 0) {
  56611. return null;
  56612. }
  56613. var invdet = 1 / det;
  56614. this.origin.subtractToRef(vertex0, this._tvec);
  56615. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  56616. if (bu < 0 || bu > 1.0) {
  56617. return null;
  56618. }
  56619. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  56620. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  56621. if (bv < 0 || bu + bv > 1.0) {
  56622. return null;
  56623. }
  56624. //check if the distance is longer than the predefined length.
  56625. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  56626. if (distance > this.length) {
  56627. return null;
  56628. }
  56629. return new BABYLON.IntersectionInfo(bu, bv, distance);
  56630. };
  56631. Ray.prototype.intersectsPlane = function (plane) {
  56632. var distance;
  56633. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  56634. if (Math.abs(result1) < 9.99999997475243E-07) {
  56635. return null;
  56636. }
  56637. else {
  56638. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  56639. distance = (-plane.d - result2) / result1;
  56640. if (distance < 0.0) {
  56641. if (distance < -9.99999997475243E-07) {
  56642. return null;
  56643. }
  56644. else {
  56645. return 0;
  56646. }
  56647. }
  56648. return distance;
  56649. }
  56650. };
  56651. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  56652. var tm = BABYLON.Tmp.Matrix[0];
  56653. mesh.getWorldMatrix().invertToRef(tm);
  56654. if (this._tmpRay) {
  56655. Ray.TransformToRef(this, tm, this._tmpRay);
  56656. }
  56657. else {
  56658. this._tmpRay = Ray.Transform(this, tm);
  56659. }
  56660. return mesh.intersects(this._tmpRay, fastCheck);
  56661. };
  56662. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  56663. if (results) {
  56664. results.length = 0;
  56665. }
  56666. else {
  56667. results = [];
  56668. }
  56669. for (var i = 0; i < meshes.length; i++) {
  56670. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  56671. if (pickInfo.hit) {
  56672. results.push(pickInfo);
  56673. }
  56674. }
  56675. results.sort(this._comparePickingInfo);
  56676. return results;
  56677. };
  56678. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  56679. if (pickingInfoA.distance < pickingInfoB.distance) {
  56680. return -1;
  56681. }
  56682. else if (pickingInfoA.distance > pickingInfoB.distance) {
  56683. return 1;
  56684. }
  56685. else {
  56686. return 0;
  56687. }
  56688. };
  56689. /**
  56690. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  56691. * @param sega the first point of the segment to test the intersection against
  56692. * @param segb the second point of the segment to test the intersection against
  56693. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  56694. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  56695. */
  56696. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  56697. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  56698. var u = segb.subtract(sega);
  56699. var v = rsegb.subtract(this.origin);
  56700. var w = sega.subtract(this.origin);
  56701. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  56702. var b = BABYLON.Vector3.Dot(u, v);
  56703. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  56704. var d = BABYLON.Vector3.Dot(u, w);
  56705. var e = BABYLON.Vector3.Dot(v, w);
  56706. var D = a * c - b * b; // always >= 0
  56707. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  56708. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  56709. // compute the line parameters of the two closest points
  56710. if (D < Ray.smallnum) { // the lines are almost parallel
  56711. sN = 0.0; // force using point P0 on segment S1
  56712. sD = 1.0; // to prevent possible division by 0.0 later
  56713. tN = e;
  56714. tD = c;
  56715. }
  56716. else { // get the closest points on the infinite lines
  56717. sN = (b * e - c * d);
  56718. tN = (a * e - b * d);
  56719. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  56720. sN = 0.0;
  56721. tN = e;
  56722. tD = c;
  56723. }
  56724. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  56725. sN = sD;
  56726. tN = e + b;
  56727. tD = c;
  56728. }
  56729. }
  56730. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  56731. tN = 0.0;
  56732. // recompute sc for this edge
  56733. if (-d < 0.0) {
  56734. sN = 0.0;
  56735. }
  56736. else if (-d > a)
  56737. sN = sD;
  56738. else {
  56739. sN = -d;
  56740. sD = a;
  56741. }
  56742. }
  56743. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  56744. tN = tD;
  56745. // recompute sc for this edge
  56746. if ((-d + b) < 0.0) {
  56747. sN = 0;
  56748. }
  56749. else if ((-d + b) > a) {
  56750. sN = sD;
  56751. }
  56752. else {
  56753. sN = (-d + b);
  56754. sD = a;
  56755. }
  56756. }
  56757. // finally do the division to get sc and tc
  56758. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  56759. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  56760. // get the difference of the two closest points
  56761. var qtc = v.multiplyByFloats(tc, tc, tc);
  56762. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  56763. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  56764. if (isIntersected) {
  56765. return qtc.length();
  56766. }
  56767. return -1;
  56768. };
  56769. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56770. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  56771. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  56772. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  56773. this.direction.normalize();
  56774. return this;
  56775. };
  56776. // Statics
  56777. Ray.Zero = function () {
  56778. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  56779. };
  56780. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56781. var result = Ray.Zero();
  56782. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  56783. };
  56784. /**
  56785. * 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
  56786. * transformed to the given world matrix.
  56787. * @param origin The origin point
  56788. * @param end The end point
  56789. * @param world a matrix to transform the ray to. Default is the identity matrix.
  56790. */
  56791. Ray.CreateNewFromTo = function (origin, end, world) {
  56792. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  56793. var direction = end.subtract(origin);
  56794. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  56795. direction.normalize();
  56796. return Ray.Transform(new Ray(origin, direction, length), world);
  56797. };
  56798. Ray.Transform = function (ray, matrix) {
  56799. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  56800. Ray.TransformToRef(ray, matrix, result);
  56801. return result;
  56802. };
  56803. Ray.TransformToRef = function (ray, matrix, result) {
  56804. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  56805. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  56806. result.length = ray.length;
  56807. var dir = result.direction;
  56808. var len = dir.length();
  56809. if (!(len === 0 || len === 1)) {
  56810. var num = 1.0 / len;
  56811. dir.x *= num;
  56812. dir.y *= num;
  56813. dir.z *= num;
  56814. result.length *= len;
  56815. }
  56816. };
  56817. Ray.smallnum = 0.00000001;
  56818. Ray.rayl = 10e8;
  56819. return Ray;
  56820. }());
  56821. BABYLON.Ray = Ray;
  56822. })(BABYLON || (BABYLON = {}));
  56823. //# sourceMappingURL=babylon.ray.js.map
  56824. var BABYLON;
  56825. (function (BABYLON) {
  56826. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  56827. if (boxMin.x > sphereCenter.x + sphereRadius)
  56828. return false;
  56829. if (sphereCenter.x - sphereRadius > boxMax.x)
  56830. return false;
  56831. if (boxMin.y > sphereCenter.y + sphereRadius)
  56832. return false;
  56833. if (sphereCenter.y - sphereRadius > boxMax.y)
  56834. return false;
  56835. if (boxMin.z > sphereCenter.z + sphereRadius)
  56836. return false;
  56837. if (sphereCenter.z - sphereRadius > boxMax.z)
  56838. return false;
  56839. return true;
  56840. };
  56841. var getLowestRoot = (function () {
  56842. var result = { root: 0, found: false };
  56843. return function (a, b, c, maxR) {
  56844. result.root = 0;
  56845. result.found = false;
  56846. var determinant = b * b - 4.0 * a * c;
  56847. if (determinant < 0)
  56848. return result;
  56849. var sqrtD = Math.sqrt(determinant);
  56850. var r1 = (-b - sqrtD) / (2.0 * a);
  56851. var r2 = (-b + sqrtD) / (2.0 * a);
  56852. if (r1 > r2) {
  56853. var temp = r2;
  56854. r2 = r1;
  56855. r1 = temp;
  56856. }
  56857. if (r1 > 0 && r1 < maxR) {
  56858. result.root = r1;
  56859. result.found = true;
  56860. return result;
  56861. }
  56862. if (r2 > 0 && r2 < maxR) {
  56863. result.root = r2;
  56864. result.found = true;
  56865. return result;
  56866. }
  56867. return result;
  56868. };
  56869. })();
  56870. /** @hidden */
  56871. var Collider = /** @class */ (function () {
  56872. function Collider() {
  56873. this._collisionPoint = BABYLON.Vector3.Zero();
  56874. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  56875. this._tempVector = BABYLON.Vector3.Zero();
  56876. this._tempVector2 = BABYLON.Vector3.Zero();
  56877. this._tempVector3 = BABYLON.Vector3.Zero();
  56878. this._tempVector4 = BABYLON.Vector3.Zero();
  56879. this._edge = BABYLON.Vector3.Zero();
  56880. this._baseToVertex = BABYLON.Vector3.Zero();
  56881. this._destinationPoint = BABYLON.Vector3.Zero();
  56882. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  56883. this._displacementVector = BABYLON.Vector3.Zero();
  56884. /** @hidden */
  56885. this._radius = BABYLON.Vector3.One();
  56886. /** @hidden */
  56887. this._retry = 0;
  56888. /** @hidden */
  56889. this._basePointWorld = BABYLON.Vector3.Zero();
  56890. this._velocityWorld = BABYLON.Vector3.Zero();
  56891. this._normalizedVelocity = BABYLON.Vector3.Zero();
  56892. this._collisionMask = -1;
  56893. }
  56894. Object.defineProperty(Collider.prototype, "collisionMask", {
  56895. get: function () {
  56896. return this._collisionMask;
  56897. },
  56898. set: function (mask) {
  56899. this._collisionMask = !isNaN(mask) ? mask : -1;
  56900. },
  56901. enumerable: true,
  56902. configurable: true
  56903. });
  56904. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  56905. /**
  56906. * Gets the plane normal used to compute the sliding response (in local space)
  56907. */
  56908. get: function () {
  56909. return this._slidePlaneNormal;
  56910. },
  56911. enumerable: true,
  56912. configurable: true
  56913. });
  56914. // Methods
  56915. /** @hidden */
  56916. Collider.prototype._initialize = function (source, dir, e) {
  56917. this._velocity = dir;
  56918. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  56919. this._basePoint = source;
  56920. source.multiplyToRef(this._radius, this._basePointWorld);
  56921. dir.multiplyToRef(this._radius, this._velocityWorld);
  56922. this._velocityWorldLength = this._velocityWorld.length();
  56923. this._epsilon = e;
  56924. this.collisionFound = false;
  56925. };
  56926. /** @hidden */
  56927. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  56928. pa.subtractToRef(point, this._tempVector);
  56929. pb.subtractToRef(point, this._tempVector2);
  56930. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  56931. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56932. if (d < 0)
  56933. return false;
  56934. pc.subtractToRef(point, this._tempVector3);
  56935. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  56936. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56937. if (d < 0)
  56938. return false;
  56939. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  56940. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56941. return d >= 0;
  56942. };
  56943. /** @hidden */
  56944. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  56945. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  56946. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  56947. if (distance > this._velocityWorldLength + max + sphereRadius) {
  56948. return false;
  56949. }
  56950. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  56951. return false;
  56952. return true;
  56953. };
  56954. /** @hidden */
  56955. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56956. var t0;
  56957. var embeddedInPlane = false;
  56958. //defensive programming, actually not needed.
  56959. if (!trianglePlaneArray) {
  56960. trianglePlaneArray = [];
  56961. }
  56962. if (!trianglePlaneArray[faceIndex]) {
  56963. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56964. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56965. }
  56966. var trianglePlane = trianglePlaneArray[faceIndex];
  56967. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56968. return;
  56969. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56970. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56971. if (normalDotVelocity == 0) {
  56972. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  56973. return;
  56974. embeddedInPlane = true;
  56975. t0 = 0;
  56976. }
  56977. else {
  56978. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56979. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56980. if (t0 > t1) {
  56981. var temp = t1;
  56982. t1 = t0;
  56983. t0 = temp;
  56984. }
  56985. if (t0 > 1.0 || t1 < 0.0)
  56986. return;
  56987. if (t0 < 0)
  56988. t0 = 0;
  56989. if (t0 > 1.0)
  56990. t0 = 1.0;
  56991. }
  56992. this._collisionPoint.copyFromFloats(0, 0, 0);
  56993. var found = false;
  56994. var t = 1.0;
  56995. if (!embeddedInPlane) {
  56996. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56997. this._velocity.scaleToRef(t0, this._tempVector);
  56998. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56999. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57000. found = true;
  57001. t = t0;
  57002. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57003. }
  57004. }
  57005. if (!found) {
  57006. var velocitySquaredLength = this._velocity.lengthSquared();
  57007. var a = velocitySquaredLength;
  57008. this._basePoint.subtractToRef(p1, this._tempVector);
  57009. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57010. var c = this._tempVector.lengthSquared() - 1.0;
  57011. var lowestRoot = getLowestRoot(a, b, c, t);
  57012. if (lowestRoot.found) {
  57013. t = lowestRoot.root;
  57014. found = true;
  57015. this._collisionPoint.copyFrom(p1);
  57016. }
  57017. this._basePoint.subtractToRef(p2, this._tempVector);
  57018. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57019. c = this._tempVector.lengthSquared() - 1.0;
  57020. lowestRoot = getLowestRoot(a, b, c, t);
  57021. if (lowestRoot.found) {
  57022. t = lowestRoot.root;
  57023. found = true;
  57024. this._collisionPoint.copyFrom(p2);
  57025. }
  57026. this._basePoint.subtractToRef(p3, this._tempVector);
  57027. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57028. c = this._tempVector.lengthSquared() - 1.0;
  57029. lowestRoot = getLowestRoot(a, b, c, t);
  57030. if (lowestRoot.found) {
  57031. t = lowestRoot.root;
  57032. found = true;
  57033. this._collisionPoint.copyFrom(p3);
  57034. }
  57035. p2.subtractToRef(p1, this._edge);
  57036. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57037. var edgeSquaredLength = this._edge.lengthSquared();
  57038. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57039. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57040. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57041. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57042. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57043. lowestRoot = getLowestRoot(a, b, c, t);
  57044. if (lowestRoot.found) {
  57045. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57046. if (f >= 0.0 && f <= 1.0) {
  57047. t = lowestRoot.root;
  57048. found = true;
  57049. this._edge.scaleInPlace(f);
  57050. p1.addToRef(this._edge, this._collisionPoint);
  57051. }
  57052. }
  57053. p3.subtractToRef(p2, this._edge);
  57054. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57055. edgeSquaredLength = this._edge.lengthSquared();
  57056. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57057. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57058. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57059. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57060. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57061. lowestRoot = getLowestRoot(a, b, c, t);
  57062. if (lowestRoot.found) {
  57063. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57064. if (f >= 0.0 && f <= 1.0) {
  57065. t = lowestRoot.root;
  57066. found = true;
  57067. this._edge.scaleInPlace(f);
  57068. p2.addToRef(this._edge, this._collisionPoint);
  57069. }
  57070. }
  57071. p1.subtractToRef(p3, this._edge);
  57072. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57073. edgeSquaredLength = this._edge.lengthSquared();
  57074. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57075. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57076. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57077. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57078. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57079. lowestRoot = getLowestRoot(a, b, c, t);
  57080. if (lowestRoot.found) {
  57081. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57082. if (f >= 0.0 && f <= 1.0) {
  57083. t = lowestRoot.root;
  57084. found = true;
  57085. this._edge.scaleInPlace(f);
  57086. p3.addToRef(this._edge, this._collisionPoint);
  57087. }
  57088. }
  57089. }
  57090. if (found) {
  57091. var distToCollision = t * this._velocity.length();
  57092. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57093. if (!this.intersectionPoint) {
  57094. this.intersectionPoint = this._collisionPoint.clone();
  57095. }
  57096. else {
  57097. this.intersectionPoint.copyFrom(this._collisionPoint);
  57098. }
  57099. this._nearestDistance = distToCollision;
  57100. this.collisionFound = true;
  57101. }
  57102. }
  57103. };
  57104. /** @hidden */
  57105. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57106. for (var i = indexStart; i < indexEnd; i += 3) {
  57107. var p1 = pts[indices[i] - decal];
  57108. var p2 = pts[indices[i + 1] - decal];
  57109. var p3 = pts[indices[i + 2] - decal];
  57110. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57111. }
  57112. };
  57113. /** @hidden */
  57114. Collider.prototype._getResponse = function (pos, vel) {
  57115. pos.addToRef(vel, this._destinationPoint);
  57116. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57117. this._basePoint.addToRef(vel, pos);
  57118. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57119. this._slidePlaneNormal.normalize();
  57120. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57121. pos.addInPlace(this._displacementVector);
  57122. this.intersectionPoint.addInPlace(this._displacementVector);
  57123. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57124. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57125. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57126. };
  57127. return Collider;
  57128. }());
  57129. BABYLON.Collider = Collider;
  57130. })(BABYLON || (BABYLON = {}));
  57131. //# sourceMappingURL=babylon.collider.js.map
  57132. var BABYLON;
  57133. (function (BABYLON) {
  57134. //WebWorker code will be inserted to this variable.
  57135. /** @hidden */
  57136. BABYLON.CollisionWorker = "";
  57137. /** Defines supported task for worker process */
  57138. var WorkerTaskType;
  57139. (function (WorkerTaskType) {
  57140. /** Initialization */
  57141. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  57142. /** Update of geometry */
  57143. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  57144. /** Evaluate collision */
  57145. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  57146. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  57147. /** Defines kind of replies returned by worker */
  57148. var WorkerReplyType;
  57149. (function (WorkerReplyType) {
  57150. /** Success */
  57151. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  57152. /** Unkown error */
  57153. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  57154. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  57155. /** @hidden */
  57156. var CollisionCoordinatorWorker = /** @class */ (function () {
  57157. function CollisionCoordinatorWorker() {
  57158. var _this = this;
  57159. this._scaledPosition = BABYLON.Vector3.Zero();
  57160. this._scaledVelocity = BABYLON.Vector3.Zero();
  57161. this.onMeshUpdated = function (transformNode) {
  57162. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  57163. };
  57164. this.onGeometryUpdated = function (geometry) {
  57165. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  57166. };
  57167. this._afterRender = function () {
  57168. if (!_this._init)
  57169. return;
  57170. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  57171. return;
  57172. }
  57173. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  57174. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  57175. if (_this._runningUpdated > 4) {
  57176. return;
  57177. }
  57178. ++_this._runningUpdated;
  57179. var payload = {
  57180. updatedMeshes: _this._addUpdateMeshesList,
  57181. updatedGeometries: _this._addUpdateGeometriesList,
  57182. removedGeometries: _this._toRemoveGeometryArray,
  57183. removedMeshes: _this._toRemoveMeshesArray
  57184. };
  57185. var message = {
  57186. payload: payload,
  57187. taskType: WorkerTaskType.UPDATE
  57188. };
  57189. var serializable = [];
  57190. for (var id in payload.updatedGeometries) {
  57191. if (payload.updatedGeometries.hasOwnProperty(id)) {
  57192. //prepare transferables
  57193. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  57194. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  57195. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  57196. }
  57197. }
  57198. _this._worker.postMessage(message, serializable);
  57199. _this._addUpdateMeshesList = {};
  57200. _this._addUpdateGeometriesList = {};
  57201. _this._toRemoveGeometryArray = [];
  57202. _this._toRemoveMeshesArray = [];
  57203. };
  57204. this._onMessageFromWorker = function (e) {
  57205. var returnData = e.data;
  57206. if (returnData.error != WorkerReplyType.SUCCESS) {
  57207. //TODO what errors can be returned from the worker?
  57208. BABYLON.Tools.Warn("error returned from worker!");
  57209. return;
  57210. }
  57211. switch (returnData.taskType) {
  57212. case WorkerTaskType.INIT:
  57213. _this._init = true;
  57214. //Update the worked with ALL of the scene's current state
  57215. _this._scene.meshes.forEach(function (mesh) {
  57216. _this.onMeshAdded(mesh);
  57217. });
  57218. _this._scene.getGeometries().forEach(function (geometry) {
  57219. _this.onGeometryAdded(geometry);
  57220. });
  57221. break;
  57222. case WorkerTaskType.UPDATE:
  57223. _this._runningUpdated--;
  57224. break;
  57225. case WorkerTaskType.COLLIDE:
  57226. var returnPayload = returnData.payload;
  57227. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  57228. return;
  57229. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  57230. if (callback) {
  57231. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57232. if (mesh) {
  57233. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57234. }
  57235. }
  57236. //cleanup
  57237. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57238. break;
  57239. }
  57240. };
  57241. this._collisionsCallbackArray = [];
  57242. this._init = false;
  57243. this._runningUpdated = 0;
  57244. this._addUpdateMeshesList = {};
  57245. this._addUpdateGeometriesList = {};
  57246. this._toRemoveGeometryArray = [];
  57247. this._toRemoveMeshesArray = [];
  57248. }
  57249. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57250. if (!this._init)
  57251. return;
  57252. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57253. return;
  57254. position.divideToRef(collider._radius, this._scaledPosition);
  57255. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57256. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57257. var payload = {
  57258. collider: {
  57259. position: this._scaledPosition.asArray(),
  57260. velocity: this._scaledVelocity.asArray(),
  57261. radius: collider._radius.asArray()
  57262. },
  57263. collisionId: collisionIndex,
  57264. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57265. maximumRetry: maximumRetry
  57266. };
  57267. var message = {
  57268. payload: payload,
  57269. taskType: WorkerTaskType.COLLIDE
  57270. };
  57271. this._worker.postMessage(message);
  57272. };
  57273. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57274. this._scene = scene;
  57275. this._scene.registerAfterRender(this._afterRender);
  57276. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57277. this._worker = new Worker(workerUrl);
  57278. this._worker.onmessage = this._onMessageFromWorker;
  57279. var message = {
  57280. payload: {},
  57281. taskType: WorkerTaskType.INIT
  57282. };
  57283. this._worker.postMessage(message);
  57284. };
  57285. CollisionCoordinatorWorker.prototype.destroy = function () {
  57286. this._scene.unregisterAfterRender(this._afterRender);
  57287. this._worker.terminate();
  57288. };
  57289. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57290. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57291. this.onMeshUpdated(mesh);
  57292. };
  57293. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57294. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57295. };
  57296. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57297. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57298. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57299. this.onGeometryUpdated(geometry);
  57300. };
  57301. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57302. this._toRemoveGeometryArray.push(geometry.id);
  57303. };
  57304. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57305. var submeshes = [];
  57306. if (mesh.subMeshes) {
  57307. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57308. var boundingInfo = sm.getBoundingInfo();
  57309. return {
  57310. position: idx,
  57311. verticesStart: sm.verticesStart,
  57312. verticesCount: sm.verticesCount,
  57313. indexStart: sm.indexStart,
  57314. indexCount: sm.indexCount,
  57315. hasMaterial: !!sm.getMaterial(),
  57316. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57317. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57318. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57319. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57320. };
  57321. });
  57322. }
  57323. var geometryId = null;
  57324. if (mesh instanceof BABYLON.Mesh) {
  57325. var geometry = mesh.geometry;
  57326. geometryId = geometry ? geometry.id : null;
  57327. }
  57328. else if (mesh instanceof BABYLON.InstancedMesh) {
  57329. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57330. geometryId = geometry ? geometry.id : null;
  57331. }
  57332. var boundingInfo = mesh.getBoundingInfo();
  57333. return {
  57334. uniqueId: mesh.uniqueId,
  57335. id: mesh.id,
  57336. name: mesh.name,
  57337. geometryId: geometryId,
  57338. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57339. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57340. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57341. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57342. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57343. subMeshes: submeshes,
  57344. checkCollisions: mesh.checkCollisions
  57345. };
  57346. };
  57347. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57348. return {
  57349. id: geometry.id,
  57350. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57351. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  57352. indices: new Uint32Array(geometry.getIndices() || []),
  57353. };
  57354. };
  57355. return CollisionCoordinatorWorker;
  57356. }());
  57357. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  57358. /** @hidden */
  57359. var CollisionCoordinatorLegacy = /** @class */ (function () {
  57360. function CollisionCoordinatorLegacy() {
  57361. this._scaledPosition = BABYLON.Vector3.Zero();
  57362. this._scaledVelocity = BABYLON.Vector3.Zero();
  57363. this._finalPosition = BABYLON.Vector3.Zero();
  57364. }
  57365. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57366. position.divideToRef(collider._radius, this._scaledPosition);
  57367. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57368. collider.collidedMesh = null;
  57369. collider._retry = 0;
  57370. collider._initialVelocity = this._scaledVelocity;
  57371. collider._initialPosition = this._scaledPosition;
  57372. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  57373. this._finalPosition.multiplyInPlace(collider._radius);
  57374. //run the callback
  57375. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  57376. };
  57377. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  57378. this._scene = scene;
  57379. };
  57380. CollisionCoordinatorLegacy.prototype.destroy = function () {
  57381. //Legacy need no destruction method.
  57382. };
  57383. //No update in legacy mode
  57384. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  57385. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  57386. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  57387. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  57388. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  57389. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  57390. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  57391. if (excludedMesh === void 0) { excludedMesh = null; }
  57392. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  57393. if (collider._retry >= maximumRetry) {
  57394. finalPosition.copyFrom(position);
  57395. return;
  57396. }
  57397. // Check if this is a mesh else camera or -1
  57398. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  57399. collider._initialize(position, velocity, closeDistance);
  57400. // Check all meshes
  57401. for (var index = 0; index < this._scene.meshes.length; index++) {
  57402. var mesh = this._scene.meshes[index];
  57403. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  57404. mesh._checkCollision(collider);
  57405. }
  57406. }
  57407. if (!collider.collisionFound) {
  57408. position.addToRef(velocity, finalPosition);
  57409. return;
  57410. }
  57411. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  57412. collider._getResponse(position, velocity);
  57413. }
  57414. if (velocity.length() <= closeDistance) {
  57415. finalPosition.copyFrom(position);
  57416. return;
  57417. }
  57418. collider._retry++;
  57419. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  57420. };
  57421. return CollisionCoordinatorLegacy;
  57422. }());
  57423. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  57424. })(BABYLON || (BABYLON = {}));
  57425. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  57426. var BABYLON;
  57427. (function (BABYLON) {
  57428. /**
  57429. * A particle represents one of the element emitted by a particle system.
  57430. * This is mainly define by its coordinates, direction, velocity and age.
  57431. */
  57432. var Particle = /** @class */ (function () {
  57433. /**
  57434. * Creates a new instance Particle
  57435. * @param particleSystem the particle system the particle belongs to
  57436. */
  57437. function Particle(
  57438. /**
  57439. * The particle system the particle belongs to.
  57440. */
  57441. particleSystem) {
  57442. this.particleSystem = particleSystem;
  57443. /**
  57444. * The world position of the particle in the scene.
  57445. */
  57446. this.position = BABYLON.Vector3.Zero();
  57447. /**
  57448. * The world direction of the particle in the scene.
  57449. */
  57450. this.direction = BABYLON.Vector3.Zero();
  57451. /**
  57452. * The color of the particle.
  57453. */
  57454. this.color = new BABYLON.Color4(0, 0, 0, 0);
  57455. /**
  57456. * The color change of the particle per step.
  57457. */
  57458. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  57459. /**
  57460. * Defines how long will the life of the particle be.
  57461. */
  57462. this.lifeTime = 1.0;
  57463. /**
  57464. * The current age of the particle.
  57465. */
  57466. this.age = 0;
  57467. /**
  57468. * The current size of the particle.
  57469. */
  57470. this.size = 0;
  57471. /**
  57472. * The current scale of the particle.
  57473. */
  57474. this.scale = new BABYLON.Vector2(1, 1);
  57475. /**
  57476. * The current angle of the particle.
  57477. */
  57478. this.angle = 0;
  57479. /**
  57480. * Defines how fast is the angle changing.
  57481. */
  57482. this.angularSpeed = 0;
  57483. /**
  57484. * Defines the cell index used by the particle to be rendered from a sprite.
  57485. */
  57486. this.cellIndex = 0;
  57487. /** @hidden */
  57488. this._attachedSubEmitters = null;
  57489. /** @hidden */
  57490. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  57491. /** @hidden */
  57492. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  57493. /** @hidden */
  57494. this._currentSize1 = 0;
  57495. /** @hidden */
  57496. this._currentSize2 = 0;
  57497. /** @hidden */
  57498. this._currentAngularSpeed1 = 0;
  57499. /** @hidden */
  57500. this._currentAngularSpeed2 = 0;
  57501. /** @hidden */
  57502. this._currentVelocity1 = 0;
  57503. /** @hidden */
  57504. this._currentVelocity2 = 0;
  57505. /** @hidden */
  57506. this._currentLimitVelocity1 = 0;
  57507. /** @hidden */
  57508. this._currentLimitVelocity2 = 0;
  57509. /** @hidden */
  57510. this._currentDrag1 = 0;
  57511. /** @hidden */
  57512. this._currentDrag2 = 0;
  57513. this.id = Particle._Count++;
  57514. if (!this.particleSystem.isAnimationSheetEnabled) {
  57515. return;
  57516. }
  57517. this.updateCellInfoFromSystem();
  57518. }
  57519. Particle.prototype.updateCellInfoFromSystem = function () {
  57520. this.cellIndex = this.particleSystem.startSpriteCellID;
  57521. };
  57522. /**
  57523. * Defines how the sprite cell index is updated for the particle
  57524. */
  57525. Particle.prototype.updateCellIndex = function () {
  57526. var offsetAge = this.age;
  57527. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  57528. if (this.particleSystem.spriteRandomStartCell) {
  57529. if (this._randomCellOffset === undefined) {
  57530. this._randomCellOffset = Math.random() * this.lifeTime;
  57531. }
  57532. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  57533. changeSpeed = 1;
  57534. offsetAge = this._randomCellOffset;
  57535. }
  57536. else {
  57537. offsetAge += this._randomCellOffset;
  57538. }
  57539. }
  57540. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  57541. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  57542. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  57543. };
  57544. /** @hidden */
  57545. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  57546. if (subEmitter.particleSystem.emitter.position) {
  57547. var emitterMesh = subEmitter.particleSystem.emitter;
  57548. emitterMesh.position.copyFrom(this.position);
  57549. if (subEmitter.inheritDirection) {
  57550. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  57551. // Look at using Y as forward
  57552. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  57553. }
  57554. }
  57555. else {
  57556. var emitterPosition = subEmitter.particleSystem.emitter;
  57557. emitterPosition.copyFrom(this.position);
  57558. }
  57559. // Set inheritedVelocityOffset to be used when new particles are created
  57560. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  57561. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  57562. };
  57563. /** @hidden */
  57564. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  57565. var _this = this;
  57566. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  57567. this._attachedSubEmitters.forEach(function (subEmitter) {
  57568. _this._inheritParticleInfoToSubEmitter(subEmitter);
  57569. });
  57570. }
  57571. };
  57572. /** @hidden */
  57573. Particle.prototype._reset = function () {
  57574. this.age = 0;
  57575. this._currentColorGradient = null;
  57576. this._currentSizeGradient = null;
  57577. this._currentAngularSpeedGradient = null;
  57578. this._currentVelocityGradient = null;
  57579. this._currentLimitVelocityGradient = null;
  57580. this._currentDragGradient = null;
  57581. this.cellIndex = this.particleSystem.startSpriteCellID;
  57582. this._randomCellOffset = undefined;
  57583. };
  57584. /**
  57585. * Copy the properties of particle to another one.
  57586. * @param other the particle to copy the information to.
  57587. */
  57588. Particle.prototype.copyTo = function (other) {
  57589. other.position.copyFrom(this.position);
  57590. if (this._initialDirection) {
  57591. if (other._initialDirection) {
  57592. other._initialDirection.copyFrom(this._initialDirection);
  57593. }
  57594. else {
  57595. other._initialDirection = this._initialDirection.clone();
  57596. }
  57597. }
  57598. else {
  57599. other._initialDirection = null;
  57600. }
  57601. other.direction.copyFrom(this.direction);
  57602. other.color.copyFrom(this.color);
  57603. other.colorStep.copyFrom(this.colorStep);
  57604. other.lifeTime = this.lifeTime;
  57605. other.age = this.age;
  57606. other._randomCellOffset = this._randomCellOffset;
  57607. other.size = this.size;
  57608. other.scale.copyFrom(this.scale);
  57609. other.angle = this.angle;
  57610. other.angularSpeed = this.angularSpeed;
  57611. other.particleSystem = this.particleSystem;
  57612. other.cellIndex = this.cellIndex;
  57613. other.id = this.id;
  57614. other._attachedSubEmitters = this._attachedSubEmitters;
  57615. if (this._currentColorGradient) {
  57616. other._currentColorGradient = this._currentColorGradient;
  57617. other._currentColor1.copyFrom(this._currentColor1);
  57618. other._currentColor2.copyFrom(this._currentColor2);
  57619. }
  57620. if (this._currentSizeGradient) {
  57621. other._currentSizeGradient = this._currentSizeGradient;
  57622. other._currentSize1 = this._currentSize1;
  57623. other._currentSize2 = this._currentSize2;
  57624. }
  57625. if (this._currentAngularSpeedGradient) {
  57626. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  57627. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  57628. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  57629. }
  57630. if (this._currentVelocityGradient) {
  57631. other._currentVelocityGradient = this._currentVelocityGradient;
  57632. other._currentVelocity1 = this._currentVelocity1;
  57633. other._currentVelocity2 = this._currentVelocity2;
  57634. }
  57635. if (this._currentLimitVelocityGradient) {
  57636. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  57637. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  57638. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  57639. }
  57640. if (this._currentDragGradient) {
  57641. other._currentDragGradient = this._currentDragGradient;
  57642. other._currentDrag1 = this._currentDrag1;
  57643. other._currentDrag2 = this._currentDrag2;
  57644. }
  57645. if (this.particleSystem.isAnimationSheetEnabled) {
  57646. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  57647. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  57648. }
  57649. if (this.particleSystem.useRampGradients) {
  57650. other.remapData.copyFrom(this.remapData);
  57651. }
  57652. if (this._randomNoiseCoordinates1) {
  57653. if (other._randomNoiseCoordinates1) {
  57654. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  57655. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  57656. }
  57657. else {
  57658. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  57659. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  57660. }
  57661. }
  57662. };
  57663. Particle._Count = 0;
  57664. return Particle;
  57665. }());
  57666. BABYLON.Particle = Particle;
  57667. })(BABYLON || (BABYLON = {}));
  57668. //# sourceMappingURL=babylon.particle.js.map
  57669. var BABYLON;
  57670. (function (BABYLON) {
  57671. /**
  57672. * This represents the base class for particle system in Babylon.
  57673. * 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.
  57674. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57675. * @example https://doc.babylonjs.com/babylon101/particles
  57676. */
  57677. var BaseParticleSystem = /** @class */ (function () {
  57678. /**
  57679. * Instantiates a particle system.
  57680. * 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.
  57681. * @param name The name of the particle system
  57682. */
  57683. function BaseParticleSystem(name) {
  57684. /**
  57685. * List of animations used by the particle system.
  57686. */
  57687. this.animations = [];
  57688. /**
  57689. * The rendering group used by the Particle system to chose when to render.
  57690. */
  57691. this.renderingGroupId = 0;
  57692. /**
  57693. * The emitter represents the Mesh or position we are attaching the particle system to.
  57694. */
  57695. this.emitter = null;
  57696. /**
  57697. * The maximum number of particles to emit per frame
  57698. */
  57699. this.emitRate = 10;
  57700. /**
  57701. * If you want to launch only a few particles at once, that can be done, as well.
  57702. */
  57703. this.manualEmitCount = -1;
  57704. /**
  57705. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57706. */
  57707. this.updateSpeed = 0.01;
  57708. /**
  57709. * The amount of time the particle system is running (depends of the overall update speed).
  57710. */
  57711. this.targetStopDuration = 0;
  57712. /**
  57713. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  57714. */
  57715. this.disposeOnStop = false;
  57716. /**
  57717. * Minimum power of emitting particles.
  57718. */
  57719. this.minEmitPower = 1;
  57720. /**
  57721. * Maximum power of emitting particles.
  57722. */
  57723. this.maxEmitPower = 1;
  57724. /**
  57725. * Minimum life time of emitting particles.
  57726. */
  57727. this.minLifeTime = 1;
  57728. /**
  57729. * Maximum life time of emitting particles.
  57730. */
  57731. this.maxLifeTime = 1;
  57732. /**
  57733. * Minimum Size of emitting particles.
  57734. */
  57735. this.minSize = 1;
  57736. /**
  57737. * Maximum Size of emitting particles.
  57738. */
  57739. this.maxSize = 1;
  57740. /**
  57741. * Minimum scale of emitting particles on X axis.
  57742. */
  57743. this.minScaleX = 1;
  57744. /**
  57745. * Maximum scale of emitting particles on X axis.
  57746. */
  57747. this.maxScaleX = 1;
  57748. /**
  57749. * Minimum scale of emitting particles on Y axis.
  57750. */
  57751. this.minScaleY = 1;
  57752. /**
  57753. * Maximum scale of emitting particles on Y axis.
  57754. */
  57755. this.maxScaleY = 1;
  57756. /**
  57757. * Gets or sets the minimal initial rotation in radians.
  57758. */
  57759. this.minInitialRotation = 0;
  57760. /**
  57761. * Gets or sets the maximal initial rotation in radians.
  57762. */
  57763. this.maxInitialRotation = 0;
  57764. /**
  57765. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57766. */
  57767. this.minAngularSpeed = 0;
  57768. /**
  57769. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57770. */
  57771. this.maxAngularSpeed = 0;
  57772. /**
  57773. * The layer mask we are rendering the particles through.
  57774. */
  57775. this.layerMask = 0x0FFFFFFF;
  57776. /**
  57777. * This can help using your own shader to render the particle system.
  57778. * The according effect will be created
  57779. */
  57780. this.customShader = null;
  57781. /**
  57782. * By default particle system starts as soon as they are created. This prevents the
  57783. * automatic start to happen and let you decide when to start emitting particles.
  57784. */
  57785. this.preventAutoStart = false;
  57786. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  57787. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  57788. /**
  57789. * Callback triggered when the particle animation is ending.
  57790. */
  57791. this.onAnimationEnd = null;
  57792. /**
  57793. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57794. */
  57795. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57796. /**
  57797. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57798. * to override the particles.
  57799. */
  57800. this.forceDepthWrite = false;
  57801. /** 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 */
  57802. this.preWarmCycles = 0;
  57803. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57804. this.preWarmStepOffset = 1;
  57805. /**
  57806. * 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)
  57807. */
  57808. this.spriteCellChangeSpeed = 1;
  57809. /**
  57810. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57811. */
  57812. this.startSpriteCellID = 0;
  57813. /**
  57814. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57815. */
  57816. this.endSpriteCellID = 0;
  57817. /**
  57818. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57819. */
  57820. this.spriteCellWidth = 0;
  57821. /**
  57822. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57823. */
  57824. this.spriteCellHeight = 0;
  57825. /**
  57826. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  57827. */
  57828. this.spriteRandomStartCell = false;
  57829. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57830. this.translationPivot = new BABYLON.Vector2(0, 0);
  57831. /**
  57832. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  57833. */
  57834. this.beginAnimationOnStart = false;
  57835. /**
  57836. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  57837. */
  57838. this.beginAnimationFrom = 0;
  57839. /**
  57840. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  57841. */
  57842. this.beginAnimationTo = 60;
  57843. /**
  57844. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  57845. */
  57846. this.beginAnimationLoop = false;
  57847. /**
  57848. * You can use gravity if you want to give an orientation to your particles.
  57849. */
  57850. this.gravity = BABYLON.Vector3.Zero();
  57851. this._colorGradients = null;
  57852. this._sizeGradients = null;
  57853. this._lifeTimeGradients = null;
  57854. this._angularSpeedGradients = null;
  57855. this._velocityGradients = null;
  57856. this._limitVelocityGradients = null;
  57857. this._dragGradients = null;
  57858. this._emitRateGradients = null;
  57859. this._startSizeGradients = null;
  57860. this._rampGradients = null;
  57861. this._colorRemapGradients = null;
  57862. this._alphaRemapGradients = null;
  57863. /**
  57864. * Defines the delay in milliseconds before starting the system (0 by default)
  57865. */
  57866. this.startDelay = 0;
  57867. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  57868. this.limitVelocityDamping = 0.4;
  57869. /**
  57870. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57871. */
  57872. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57873. /**
  57874. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57875. */
  57876. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57877. /**
  57878. * Color the particle will have at the end of its lifetime
  57879. */
  57880. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  57881. /**
  57882. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  57883. */
  57884. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57885. /** @hidden */
  57886. this._isSubEmitter = false;
  57887. /**
  57888. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57889. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  57890. */
  57891. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  57892. this._isBillboardBased = true;
  57893. /**
  57894. * Local cache of defines for image processing.
  57895. */
  57896. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  57897. this.id = name;
  57898. this.name = name;
  57899. }
  57900. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  57901. /**
  57902. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  57903. */
  57904. get: function () {
  57905. return this._isAnimationSheetEnabled;
  57906. },
  57907. set: function (value) {
  57908. if (this._isAnimationSheetEnabled == value) {
  57909. return;
  57910. }
  57911. this._isAnimationSheetEnabled = value;
  57912. this._reset();
  57913. },
  57914. enumerable: true,
  57915. configurable: true
  57916. });
  57917. /**
  57918. * Get hosting scene
  57919. * @returns the scene
  57920. */
  57921. BaseParticleSystem.prototype.getScene = function () {
  57922. return this._scene;
  57923. };
  57924. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  57925. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  57926. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  57927. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  57928. };
  57929. /**
  57930. * Gets the current list of drag gradients.
  57931. * You must use addDragGradient and removeDragGradient to udpate this list
  57932. * @returns the list of drag gradients
  57933. */
  57934. BaseParticleSystem.prototype.getDragGradients = function () {
  57935. return this._dragGradients;
  57936. };
  57937. /**
  57938. * Gets the current list of limit velocity gradients.
  57939. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  57940. * @returns the list of limit velocity gradients
  57941. */
  57942. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  57943. return this._limitVelocityGradients;
  57944. };
  57945. /**
  57946. * Gets the current list of color gradients.
  57947. * You must use addColorGradient and removeColorGradient to udpate this list
  57948. * @returns the list of color gradients
  57949. */
  57950. BaseParticleSystem.prototype.getColorGradients = function () {
  57951. return this._colorGradients;
  57952. };
  57953. /**
  57954. * Gets the current list of size gradients.
  57955. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57956. * @returns the list of size gradients
  57957. */
  57958. BaseParticleSystem.prototype.getSizeGradients = function () {
  57959. return this._sizeGradients;
  57960. };
  57961. /**
  57962. * Gets the current list of color remap gradients.
  57963. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57964. * @returns the list of color remap gradients
  57965. */
  57966. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57967. return this._colorRemapGradients;
  57968. };
  57969. /**
  57970. * Gets the current list of alpha remap gradients.
  57971. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  57972. * @returns the list of alpha remap gradients
  57973. */
  57974. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  57975. return this._alphaRemapGradients;
  57976. };
  57977. /**
  57978. * Gets the current list of life time gradients.
  57979. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  57980. * @returns the list of life time gradients
  57981. */
  57982. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57983. return this._lifeTimeGradients;
  57984. };
  57985. /**
  57986. * Gets the current list of angular speed gradients.
  57987. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57988. * @returns the list of angular speed gradients
  57989. */
  57990. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57991. return this._angularSpeedGradients;
  57992. };
  57993. /**
  57994. * Gets the current list of velocity gradients.
  57995. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57996. * @returns the list of velocity gradients
  57997. */
  57998. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57999. return this._velocityGradients;
  58000. };
  58001. /**
  58002. * Gets the current list of start size gradients.
  58003. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58004. * @returns the list of start size gradients
  58005. */
  58006. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58007. return this._startSizeGradients;
  58008. };
  58009. /**
  58010. * Gets the current list of emit rate gradients.
  58011. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58012. * @returns the list of emit rate gradients
  58013. */
  58014. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58015. return this._emitRateGradients;
  58016. };
  58017. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58018. /**
  58019. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58020. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58021. */
  58022. get: function () {
  58023. if (this.particleEmitterType.direction1) {
  58024. return this.particleEmitterType.direction1;
  58025. }
  58026. return BABYLON.Vector3.Zero();
  58027. },
  58028. set: function (value) {
  58029. if (this.particleEmitterType.direction1) {
  58030. this.particleEmitterType.direction1 = value;
  58031. }
  58032. },
  58033. enumerable: true,
  58034. configurable: true
  58035. });
  58036. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58037. /**
  58038. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58039. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58040. */
  58041. get: function () {
  58042. if (this.particleEmitterType.direction2) {
  58043. return this.particleEmitterType.direction2;
  58044. }
  58045. return BABYLON.Vector3.Zero();
  58046. },
  58047. set: function (value) {
  58048. if (this.particleEmitterType.direction2) {
  58049. this.particleEmitterType.direction2 = value;
  58050. }
  58051. },
  58052. enumerable: true,
  58053. configurable: true
  58054. });
  58055. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58056. /**
  58057. * 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.
  58058. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58059. */
  58060. get: function () {
  58061. if (this.particleEmitterType.minEmitBox) {
  58062. return this.particleEmitterType.minEmitBox;
  58063. }
  58064. return BABYLON.Vector3.Zero();
  58065. },
  58066. set: function (value) {
  58067. if (this.particleEmitterType.minEmitBox) {
  58068. this.particleEmitterType.minEmitBox = value;
  58069. }
  58070. },
  58071. enumerable: true,
  58072. configurable: true
  58073. });
  58074. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58075. /**
  58076. * 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.
  58077. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58078. */
  58079. get: function () {
  58080. if (this.particleEmitterType.maxEmitBox) {
  58081. return this.particleEmitterType.maxEmitBox;
  58082. }
  58083. return BABYLON.Vector3.Zero();
  58084. },
  58085. set: function (value) {
  58086. if (this.particleEmitterType.maxEmitBox) {
  58087. this.particleEmitterType.maxEmitBox = value;
  58088. }
  58089. },
  58090. enumerable: true,
  58091. configurable: true
  58092. });
  58093. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58094. /**
  58095. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58096. */
  58097. get: function () {
  58098. return this._isBillboardBased;
  58099. },
  58100. set: function (value) {
  58101. if (this._isBillboardBased === value) {
  58102. return;
  58103. }
  58104. this._isBillboardBased = value;
  58105. this._reset();
  58106. },
  58107. enumerable: true,
  58108. configurable: true
  58109. });
  58110. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58111. /**
  58112. * Gets the image processing configuration used either in this material.
  58113. */
  58114. get: function () {
  58115. return this._imageProcessingConfiguration;
  58116. },
  58117. /**
  58118. * Sets the Default image processing configuration used either in the this material.
  58119. *
  58120. * If sets to null, the scene one is in use.
  58121. */
  58122. set: function (value) {
  58123. this._attachImageProcessingConfiguration(value);
  58124. },
  58125. enumerable: true,
  58126. configurable: true
  58127. });
  58128. /**
  58129. * Attaches a new image processing configuration to the Standard Material.
  58130. * @param configuration
  58131. */
  58132. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  58133. if (configuration === this._imageProcessingConfiguration) {
  58134. return;
  58135. }
  58136. // Pick the scene configuration if needed.
  58137. if (!configuration) {
  58138. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  58139. }
  58140. else {
  58141. this._imageProcessingConfiguration = configuration;
  58142. }
  58143. };
  58144. /** @hidden */
  58145. BaseParticleSystem.prototype._reset = function () {
  58146. };
  58147. /** @hidden */
  58148. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  58149. if (!gradients) {
  58150. return this;
  58151. }
  58152. var index = 0;
  58153. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  58154. var valueGradient = gradients_1[_i];
  58155. if (valueGradient.gradient === gradient) {
  58156. gradients.splice(index, 1);
  58157. break;
  58158. }
  58159. index++;
  58160. }
  58161. if (texture) {
  58162. texture.dispose();
  58163. }
  58164. return this;
  58165. };
  58166. /**
  58167. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  58168. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58169. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58170. * @returns the emitter
  58171. */
  58172. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  58173. var particleEmitter = new BABYLON.PointParticleEmitter();
  58174. particleEmitter.direction1 = direction1;
  58175. particleEmitter.direction2 = direction2;
  58176. this.particleEmitterType = particleEmitter;
  58177. return particleEmitter;
  58178. };
  58179. /**
  58180. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  58181. * @param radius The radius of the hemisphere to emit from
  58182. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58183. * @returns the emitter
  58184. */
  58185. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  58186. if (radius === void 0) { radius = 1; }
  58187. if (radiusRange === void 0) { radiusRange = 1; }
  58188. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  58189. this.particleEmitterType = particleEmitter;
  58190. return particleEmitter;
  58191. };
  58192. /**
  58193. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  58194. * @param radius The radius of the sphere to emit from
  58195. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58196. * @returns the emitter
  58197. */
  58198. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  58199. if (radius === void 0) { radius = 1; }
  58200. if (radiusRange === void 0) { radiusRange = 1; }
  58201. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  58202. this.particleEmitterType = particleEmitter;
  58203. return particleEmitter;
  58204. };
  58205. /**
  58206. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  58207. * @param radius The radius of the sphere to emit from
  58208. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  58209. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  58210. * @returns the emitter
  58211. */
  58212. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  58213. if (radius === void 0) { radius = 1; }
  58214. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58215. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58216. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  58217. this.particleEmitterType = particleEmitter;
  58218. return particleEmitter;
  58219. };
  58220. /**
  58221. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  58222. * @param radius The radius of the emission cylinder
  58223. * @param height The height of the emission cylinder
  58224. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  58225. * @param directionRandomizer How much to randomize the particle direction [0-1]
  58226. * @returns the emitter
  58227. */
  58228. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  58229. if (radius === void 0) { radius = 1; }
  58230. if (height === void 0) { height = 1; }
  58231. if (radiusRange === void 0) { radiusRange = 1; }
  58232. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58233. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58234. this.particleEmitterType = particleEmitter;
  58235. return particleEmitter;
  58236. };
  58237. /**
  58238. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58239. * @param radius The radius of the cylinder to emit from
  58240. * @param height The height of the emission cylinder
  58241. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58242. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58243. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58244. * @returns the emitter
  58245. */
  58246. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58247. if (radius === void 0) { radius = 1; }
  58248. if (height === void 0) { height = 1; }
  58249. if (radiusRange === void 0) { radiusRange = 1; }
  58250. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58251. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58252. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58253. this.particleEmitterType = particleEmitter;
  58254. return particleEmitter;
  58255. };
  58256. /**
  58257. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58258. * @param radius The radius of the cone to emit from
  58259. * @param angle The base angle of the cone
  58260. * @returns the emitter
  58261. */
  58262. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58263. if (radius === void 0) { radius = 1; }
  58264. if (angle === void 0) { angle = Math.PI / 4; }
  58265. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58266. this.particleEmitterType = particleEmitter;
  58267. return particleEmitter;
  58268. };
  58269. /**
  58270. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58271. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58272. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58273. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58274. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58275. * @returns the emitter
  58276. */
  58277. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58278. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58279. this.particleEmitterType = particleEmitter;
  58280. this.direction1 = direction1;
  58281. this.direction2 = direction2;
  58282. this.minEmitBox = minEmitBox;
  58283. this.maxEmitBox = maxEmitBox;
  58284. return particleEmitter;
  58285. };
  58286. /**
  58287. * Source color is added to the destination color without alpha affecting the result
  58288. */
  58289. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58290. /**
  58291. * Blend current color and particle color using particle’s alpha
  58292. */
  58293. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58294. /**
  58295. * Add current color and particle color multiplied by particle’s alpha
  58296. */
  58297. BaseParticleSystem.BLENDMODE_ADD = 2;
  58298. /**
  58299. * Multiply current color with particle color
  58300. */
  58301. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58302. /**
  58303. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58304. */
  58305. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58306. return BaseParticleSystem;
  58307. }());
  58308. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58309. })(BABYLON || (BABYLON = {}));
  58310. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58311. var BABYLON;
  58312. (function (BABYLON) {
  58313. /**
  58314. * This represents a particle system in Babylon.
  58315. * 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.
  58316. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58317. * @example https://doc.babylonjs.com/babylon101/particles
  58318. */
  58319. var ParticleSystem = /** @class */ (function (_super) {
  58320. __extends(ParticleSystem, _super);
  58321. /**
  58322. * Instantiates a particle system.
  58323. * 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.
  58324. * @param name The name of the particle system
  58325. * @param capacity The max number of particles alive at the same time
  58326. * @param scene The scene the particle system belongs to
  58327. * @param customEffect a custom effect used to change the way particles are rendered by default
  58328. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58329. * @param epsilon Offset used to render the particles
  58330. */
  58331. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58332. if (customEffect === void 0) { customEffect = null; }
  58333. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58334. if (epsilon === void 0) { epsilon = 0.01; }
  58335. var _this = _super.call(this, name) || this;
  58336. /**
  58337. * @hidden
  58338. */
  58339. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58340. /**
  58341. * An event triggered when the system is disposed
  58342. */
  58343. _this.onDisposeObservable = new BABYLON.Observable();
  58344. _this._particles = new Array();
  58345. _this._stockParticles = new Array();
  58346. _this._newPartsExcess = 0;
  58347. _this._vertexBuffers = {};
  58348. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58349. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58350. _this._scaledDirection = BABYLON.Vector3.Zero();
  58351. _this._scaledGravity = BABYLON.Vector3.Zero();
  58352. _this._currentRenderId = -1;
  58353. _this._useInstancing = false;
  58354. _this._started = false;
  58355. _this._stopped = false;
  58356. _this._actualFrame = 0;
  58357. /** @hidden */
  58358. _this._currentEmitRate1 = 0;
  58359. /** @hidden */
  58360. _this._currentEmitRate2 = 0;
  58361. /** @hidden */
  58362. _this._currentStartSize1 = 0;
  58363. /** @hidden */
  58364. _this._currentStartSize2 = 0;
  58365. _this._rawTextureWidth = 256;
  58366. _this._useRampGradients = false;
  58367. /**
  58368. * @hidden
  58369. * If the particle systems emitter should be disposed when the particle system is disposed
  58370. */
  58371. _this._disposeEmitterOnDispose = false;
  58372. // start of sub system methods
  58373. /**
  58374. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  58375. * Its lifetime will start back at 0.
  58376. */
  58377. _this.recycleParticle = function (particle) {
  58378. // move particle from activeParticle list to stock particles
  58379. var lastParticle = _this._particles.pop();
  58380. if (lastParticle !== particle) {
  58381. lastParticle.copyTo(particle);
  58382. }
  58383. _this._stockParticles.push(lastParticle);
  58384. };
  58385. _this._createParticle = function () {
  58386. var particle;
  58387. if (_this._stockParticles.length !== 0) {
  58388. particle = _this._stockParticles.pop();
  58389. particle._reset();
  58390. }
  58391. else {
  58392. particle = new BABYLON.Particle(_this);
  58393. }
  58394. // Attach emitters
  58395. if (_this._subEmitters && _this._subEmitters.length > 0) {
  58396. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  58397. particle._attachedSubEmitters = [];
  58398. subEmitters.forEach(function (subEmitter) {
  58399. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  58400. var newEmitter = subEmitter.clone();
  58401. particle._attachedSubEmitters.push(newEmitter);
  58402. newEmitter.particleSystem.start();
  58403. }
  58404. });
  58405. }
  58406. return particle;
  58407. };
  58408. _this._emitFromParticle = function (particle) {
  58409. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  58410. return;
  58411. }
  58412. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  58413. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  58414. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  58415. var subSystem = subEmitter.clone();
  58416. particle._inheritParticleInfoToSubEmitter(subSystem);
  58417. subSystem.particleSystem._rootParticleSystem = _this;
  58418. _this.activeSubSystems.push(subSystem.particleSystem);
  58419. subSystem.particleSystem.start();
  58420. }
  58421. });
  58422. };
  58423. _this._capacity = capacity;
  58424. _this._epsilon = epsilon;
  58425. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  58426. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58427. // Setup the default processing configuration to the scene.
  58428. _this._attachImageProcessingConfiguration(null);
  58429. _this._customEffect = customEffect;
  58430. _this._scene.particleSystems.push(_this);
  58431. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  58432. _this._createIndexBuffer();
  58433. _this._createVertexBuffers();
  58434. // Default emitter type
  58435. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  58436. // Update
  58437. _this.updateFunction = function (particles) {
  58438. var noiseTextureSize = null;
  58439. var noiseTextureData = null;
  58440. if (_this.noiseTexture) { // We need to get texture data back to CPU
  58441. noiseTextureSize = _this.noiseTexture.getSize();
  58442. noiseTextureData = (_this.noiseTexture.getContent());
  58443. }
  58444. var _loop_1 = function () {
  58445. particle = particles[index];
  58446. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  58447. var previousAge = particle.age;
  58448. particle.age += scaledUpdateSpeed;
  58449. // Evaluate step to death
  58450. if (particle.age > particle.lifeTime) {
  58451. var diff = particle.age - previousAge;
  58452. var oldDiff = particle.lifeTime - previousAge;
  58453. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  58454. particle.age = particle.lifeTime;
  58455. }
  58456. var ratio = particle.age / particle.lifeTime;
  58457. // Color
  58458. if (_this._colorGradients && _this._colorGradients.length > 0) {
  58459. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  58460. if (currentGradient !== particle._currentColorGradient) {
  58461. particle._currentColor1.copyFrom(particle._currentColor2);
  58462. nextGradient.getColorToRef(particle._currentColor2);
  58463. particle._currentColorGradient = currentGradient;
  58464. }
  58465. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  58466. });
  58467. }
  58468. else {
  58469. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  58470. particle.color.addInPlace(_this._scaledColorStep);
  58471. if (particle.color.a < 0) {
  58472. particle.color.a = 0;
  58473. }
  58474. }
  58475. // Angular speed
  58476. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  58477. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  58478. if (currentGradient !== particle._currentAngularSpeedGradient) {
  58479. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  58480. particle._currentAngularSpeed2 = nextGradient.getFactor();
  58481. particle._currentAngularSpeedGradient = currentGradient;
  58482. }
  58483. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  58484. });
  58485. }
  58486. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  58487. // Direction
  58488. var directionScale = scaledUpdateSpeed;
  58489. /// Velocity
  58490. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  58491. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  58492. if (currentGradient !== particle._currentVelocityGradient) {
  58493. particle._currentVelocity1 = particle._currentVelocity2;
  58494. particle._currentVelocity2 = nextGradient.getFactor();
  58495. particle._currentVelocityGradient = currentGradient;
  58496. }
  58497. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  58498. });
  58499. }
  58500. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  58501. /// Limit velocity
  58502. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  58503. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  58504. if (currentGradient !== particle._currentLimitVelocityGradient) {
  58505. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  58506. particle._currentLimitVelocity2 = nextGradient.getFactor();
  58507. particle._currentLimitVelocityGradient = currentGradient;
  58508. }
  58509. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  58510. var currentVelocity = particle.direction.length();
  58511. if (currentVelocity > limitVelocity) {
  58512. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  58513. }
  58514. });
  58515. }
  58516. /// Drag
  58517. if (_this._dragGradients && _this._dragGradients.length > 0) {
  58518. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  58519. if (currentGradient !== particle._currentDragGradient) {
  58520. particle._currentDrag1 = particle._currentDrag2;
  58521. particle._currentDrag2 = nextGradient.getFactor();
  58522. particle._currentDragGradient = currentGradient;
  58523. }
  58524. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  58525. _this._scaledDirection.scaleInPlace(1.0 - drag);
  58526. });
  58527. }
  58528. particle.position.addInPlace(_this._scaledDirection);
  58529. // Noise
  58530. if (noiseTextureData && noiseTextureSize) {
  58531. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58532. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58533. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58534. var force = BABYLON.Tmp.Vector3[0];
  58535. var scaledForce = BABYLON.Tmp.Vector3[1];
  58536. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  58537. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  58538. particle.direction.addInPlace(scaledForce);
  58539. }
  58540. // Gravity
  58541. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  58542. particle.direction.addInPlace(_this._scaledGravity);
  58543. // Size
  58544. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  58545. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  58546. if (currentGradient !== particle._currentSizeGradient) {
  58547. particle._currentSize1 = particle._currentSize2;
  58548. particle._currentSize2 = nextGradient.getFactor();
  58549. particle._currentSizeGradient = currentGradient;
  58550. }
  58551. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  58552. });
  58553. }
  58554. // Remap data
  58555. if (_this._useRampGradients) {
  58556. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  58557. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  58558. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58559. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58560. particle.remapData.x = min;
  58561. particle.remapData.y = max - min;
  58562. });
  58563. }
  58564. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  58565. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  58566. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58567. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58568. particle.remapData.z = min;
  58569. particle.remapData.w = max - min;
  58570. });
  58571. }
  58572. }
  58573. if (_this._isAnimationSheetEnabled) {
  58574. particle.updateCellIndex();
  58575. }
  58576. // Update the position of the attached sub-emitters to match their attached particle
  58577. particle._inheritParticleInfoToSubEmitters();
  58578. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  58579. _this._emitFromParticle(particle);
  58580. if (particle._attachedSubEmitters) {
  58581. particle._attachedSubEmitters.forEach(function (subEmitter) {
  58582. subEmitter.particleSystem.disposeOnStop = true;
  58583. subEmitter.particleSystem.stop();
  58584. });
  58585. particle._attachedSubEmitters = null;
  58586. }
  58587. _this.recycleParticle(particle);
  58588. index--;
  58589. return "continue";
  58590. }
  58591. };
  58592. var particle;
  58593. for (var index = 0; index < particles.length; index++) {
  58594. _loop_1();
  58595. }
  58596. };
  58597. return _this;
  58598. }
  58599. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  58600. /**
  58601. * Sets a callback that will be triggered when the system is disposed
  58602. */
  58603. set: function (callback) {
  58604. if (this._onDisposeObserver) {
  58605. this.onDisposeObservable.remove(this._onDisposeObserver);
  58606. }
  58607. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  58608. },
  58609. enumerable: true,
  58610. configurable: true
  58611. });
  58612. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  58613. /** Gets or sets a boolean indicating that ramp gradients must be used
  58614. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  58615. */
  58616. get: function () {
  58617. return this._useRampGradients;
  58618. },
  58619. set: function (value) {
  58620. if (this._useRampGradients === value) {
  58621. return;
  58622. }
  58623. this._useRampGradients = value;
  58624. this._resetEffect();
  58625. },
  58626. enumerable: true,
  58627. configurable: true
  58628. });
  58629. Object.defineProperty(ParticleSystem.prototype, "particles", {
  58630. //end of Sub-emitter
  58631. /**
  58632. * Gets the current list of active particles
  58633. */
  58634. get: function () {
  58635. return this._particles;
  58636. },
  58637. enumerable: true,
  58638. configurable: true
  58639. });
  58640. /**
  58641. * Returns the string "ParticleSystem"
  58642. * @returns a string containing the class name
  58643. */
  58644. ParticleSystem.prototype.getClassName = function () {
  58645. return "ParticleSystem";
  58646. };
  58647. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  58648. var newGradient = new BABYLON.FactorGradient();
  58649. newGradient.gradient = gradient;
  58650. newGradient.factor1 = factor;
  58651. newGradient.factor2 = factor2;
  58652. factorGradients.push(newGradient);
  58653. factorGradients.sort(function (a, b) {
  58654. if (a.gradient < b.gradient) {
  58655. return -1;
  58656. }
  58657. else if (a.gradient > b.gradient) {
  58658. return 1;
  58659. }
  58660. return 0;
  58661. });
  58662. };
  58663. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  58664. if (!factorGradients) {
  58665. return;
  58666. }
  58667. var index = 0;
  58668. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  58669. var factorGradient = factorGradients_1[_i];
  58670. if (factorGradient.gradient === gradient) {
  58671. factorGradients.splice(index, 1);
  58672. break;
  58673. }
  58674. index++;
  58675. }
  58676. };
  58677. /**
  58678. * Adds a new life time gradient
  58679. * @param gradient defines the gradient to use (between 0 and 1)
  58680. * @param factor defines the life time factor to affect to the specified gradient
  58681. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58682. * @returns the current particle system
  58683. */
  58684. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  58685. if (!this._lifeTimeGradients) {
  58686. this._lifeTimeGradients = [];
  58687. }
  58688. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  58689. return this;
  58690. };
  58691. /**
  58692. * Remove a specific life time gradient
  58693. * @param gradient defines the gradient to remove
  58694. * @returns the current particle system
  58695. */
  58696. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  58697. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  58698. return this;
  58699. };
  58700. /**
  58701. * Adds a new size gradient
  58702. * @param gradient defines the gradient to use (between 0 and 1)
  58703. * @param factor defines the size factor to affect to the specified gradient
  58704. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58705. * @returns the current particle system
  58706. */
  58707. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  58708. if (!this._sizeGradients) {
  58709. this._sizeGradients = [];
  58710. }
  58711. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  58712. return this;
  58713. };
  58714. /**
  58715. * Remove a specific size gradient
  58716. * @param gradient defines the gradient to remove
  58717. * @returns the current particle system
  58718. */
  58719. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  58720. this._removeFactorGradient(this._sizeGradients, gradient);
  58721. return this;
  58722. };
  58723. /**
  58724. * Adds a new color remap gradient
  58725. * @param gradient defines the gradient to use (between 0 and 1)
  58726. * @param min defines the color remap minimal range
  58727. * @param max defines the color remap maximal range
  58728. * @returns the current particle system
  58729. */
  58730. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  58731. if (!this._colorRemapGradients) {
  58732. this._colorRemapGradients = [];
  58733. }
  58734. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  58735. return this;
  58736. };
  58737. /**
  58738. * Remove a specific color remap gradient
  58739. * @param gradient defines the gradient to remove
  58740. * @returns the current particle system
  58741. */
  58742. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  58743. this._removeFactorGradient(this._colorRemapGradients, gradient);
  58744. return this;
  58745. };
  58746. /**
  58747. * Adds a new alpha remap gradient
  58748. * @param gradient defines the gradient to use (between 0 and 1)
  58749. * @param min defines the alpha remap minimal range
  58750. * @param max defines the alpha remap maximal range
  58751. * @returns the current particle system
  58752. */
  58753. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  58754. if (!this._alphaRemapGradients) {
  58755. this._alphaRemapGradients = [];
  58756. }
  58757. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  58758. return this;
  58759. };
  58760. /**
  58761. * Remove a specific alpha remap gradient
  58762. * @param gradient defines the gradient to remove
  58763. * @returns the current particle system
  58764. */
  58765. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  58766. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  58767. return this;
  58768. };
  58769. /**
  58770. * Adds a new angular speed gradient
  58771. * @param gradient defines the gradient to use (between 0 and 1)
  58772. * @param factor defines the angular speed to affect to the specified gradient
  58773. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58774. * @returns the current particle system
  58775. */
  58776. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  58777. if (!this._angularSpeedGradients) {
  58778. this._angularSpeedGradients = [];
  58779. }
  58780. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  58781. return this;
  58782. };
  58783. /**
  58784. * Remove a specific angular speed gradient
  58785. * @param gradient defines the gradient to remove
  58786. * @returns the current particle system
  58787. */
  58788. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  58789. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  58790. return this;
  58791. };
  58792. /**
  58793. * Adds a new velocity gradient
  58794. * @param gradient defines the gradient to use (between 0 and 1)
  58795. * @param factor defines the velocity to affect to the specified gradient
  58796. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58797. * @returns the current particle system
  58798. */
  58799. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  58800. if (!this._velocityGradients) {
  58801. this._velocityGradients = [];
  58802. }
  58803. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  58804. return this;
  58805. };
  58806. /**
  58807. * Remove a specific velocity gradient
  58808. * @param gradient defines the gradient to remove
  58809. * @returns the current particle system
  58810. */
  58811. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  58812. this._removeFactorGradient(this._velocityGradients, gradient);
  58813. return this;
  58814. };
  58815. /**
  58816. * Adds a new limit velocity gradient
  58817. * @param gradient defines the gradient to use (between 0 and 1)
  58818. * @param factor defines the limit velocity value to affect to the specified gradient
  58819. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58820. * @returns the current particle system
  58821. */
  58822. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  58823. if (!this._limitVelocityGradients) {
  58824. this._limitVelocityGradients = [];
  58825. }
  58826. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  58827. return this;
  58828. };
  58829. /**
  58830. * Remove a specific limit velocity gradient
  58831. * @param gradient defines the gradient to remove
  58832. * @returns the current particle system
  58833. */
  58834. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  58835. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  58836. return this;
  58837. };
  58838. /**
  58839. * Adds a new drag gradient
  58840. * @param gradient defines the gradient to use (between 0 and 1)
  58841. * @param factor defines the drag value to affect to the specified gradient
  58842. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58843. * @returns the current particle system
  58844. */
  58845. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  58846. if (!this._dragGradients) {
  58847. this._dragGradients = [];
  58848. }
  58849. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  58850. return this;
  58851. };
  58852. /**
  58853. * Remove a specific drag gradient
  58854. * @param gradient defines the gradient to remove
  58855. * @returns the current particle system
  58856. */
  58857. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  58858. this._removeFactorGradient(this._dragGradients, gradient);
  58859. return this;
  58860. };
  58861. /**
  58862. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  58863. * @param gradient defines the gradient to use (between 0 and 1)
  58864. * @param factor defines the emit rate value to affect to the specified gradient
  58865. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58866. * @returns the current particle system
  58867. */
  58868. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  58869. if (!this._emitRateGradients) {
  58870. this._emitRateGradients = [];
  58871. }
  58872. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  58873. if (!this._currentEmitRateGradient) {
  58874. this._currentEmitRateGradient = this._emitRateGradients[0];
  58875. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  58876. this._currentEmitRate2 = this._currentEmitRate1;
  58877. }
  58878. if (this._emitRateGradients.length === 2) {
  58879. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  58880. }
  58881. return this;
  58882. };
  58883. /**
  58884. * Remove a specific emit rate gradient
  58885. * @param gradient defines the gradient to remove
  58886. * @returns the current particle system
  58887. */
  58888. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  58889. this._removeFactorGradient(this._emitRateGradients, gradient);
  58890. return this;
  58891. };
  58892. /**
  58893. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  58894. * @param gradient defines the gradient to use (between 0 and 1)
  58895. * @param factor defines the start size value to affect to the specified gradient
  58896. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58897. * @returns the current particle system
  58898. */
  58899. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  58900. if (!this._startSizeGradients) {
  58901. this._startSizeGradients = [];
  58902. }
  58903. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  58904. if (!this._currentStartSizeGradient) {
  58905. this._currentStartSizeGradient = this._startSizeGradients[0];
  58906. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  58907. this._currentStartSize2 = this._currentStartSize1;
  58908. }
  58909. if (this._startSizeGradients.length === 2) {
  58910. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  58911. }
  58912. return this;
  58913. };
  58914. /**
  58915. * Remove a specific start size gradient
  58916. * @param gradient defines the gradient to remove
  58917. * @returns the current particle system
  58918. */
  58919. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  58920. this._removeFactorGradient(this._emitRateGradients, gradient);
  58921. return this;
  58922. };
  58923. ParticleSystem.prototype._createRampGradientTexture = function () {
  58924. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  58925. return;
  58926. }
  58927. var data = new Uint8Array(this._rawTextureWidth * 4);
  58928. var tmpColor = BABYLON.Tmp.Color3[0];
  58929. for (var x = 0; x < this._rawTextureWidth; x++) {
  58930. var ratio = x / this._rawTextureWidth;
  58931. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  58932. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  58933. data[x * 4] = tmpColor.r * 255;
  58934. data[x * 4 + 1] = tmpColor.g * 255;
  58935. data[x * 4 + 2] = tmpColor.b * 255;
  58936. data[x * 4 + 3] = 255;
  58937. });
  58938. }
  58939. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58940. };
  58941. /**
  58942. * Gets the current list of ramp gradients.
  58943. * You must use addRampGradient and removeRampGradient to udpate this list
  58944. * @returns the list of ramp gradients
  58945. */
  58946. ParticleSystem.prototype.getRampGradients = function () {
  58947. return this._rampGradients;
  58948. };
  58949. /**
  58950. * Adds a new ramp gradient used to remap particle colors
  58951. * @param gradient defines the gradient to use (between 0 and 1)
  58952. * @param color defines the color to affect to the specified gradient
  58953. * @returns the current particle system
  58954. */
  58955. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58956. if (!this._rampGradients) {
  58957. this._rampGradients = [];
  58958. }
  58959. var rampGradient = new BABYLON.Color3Gradient();
  58960. rampGradient.gradient = gradient;
  58961. rampGradient.color = color;
  58962. this._rampGradients.push(rampGradient);
  58963. this._rampGradients.sort(function (a, b) {
  58964. if (a.gradient < b.gradient) {
  58965. return -1;
  58966. }
  58967. else if (a.gradient > b.gradient) {
  58968. return 1;
  58969. }
  58970. return 0;
  58971. });
  58972. if (this._rampGradientsTexture) {
  58973. this._rampGradientsTexture.dispose();
  58974. this._rampGradientsTexture = null;
  58975. }
  58976. this._createRampGradientTexture();
  58977. return this;
  58978. };
  58979. /**
  58980. * Remove a specific ramp gradient
  58981. * @param gradient defines the gradient to remove
  58982. * @returns the current particle system
  58983. */
  58984. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58985. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58986. this._rampGradientsTexture = null;
  58987. if (this._rampGradients && this._rampGradients.length > 0) {
  58988. this._createRampGradientTexture();
  58989. }
  58990. return this;
  58991. };
  58992. /**
  58993. * Adds a new color gradient
  58994. * @param gradient defines the gradient to use (between 0 and 1)
  58995. * @param color1 defines the color to affect to the specified gradient
  58996. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58997. * @returns this particle system
  58998. */
  58999. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59000. if (!this._colorGradients) {
  59001. this._colorGradients = [];
  59002. }
  59003. var colorGradient = new BABYLON.ColorGradient();
  59004. colorGradient.gradient = gradient;
  59005. colorGradient.color1 = color1;
  59006. colorGradient.color2 = color2;
  59007. this._colorGradients.push(colorGradient);
  59008. this._colorGradients.sort(function (a, b) {
  59009. if (a.gradient < b.gradient) {
  59010. return -1;
  59011. }
  59012. else if (a.gradient > b.gradient) {
  59013. return 1;
  59014. }
  59015. return 0;
  59016. });
  59017. return this;
  59018. };
  59019. /**
  59020. * Remove a specific color gradient
  59021. * @param gradient defines the gradient to remove
  59022. * @returns this particle system
  59023. */
  59024. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59025. if (!this._colorGradients) {
  59026. return this;
  59027. }
  59028. var index = 0;
  59029. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59030. var colorGradient = _a[_i];
  59031. if (colorGradient.gradient === gradient) {
  59032. this._colorGradients.splice(index, 1);
  59033. break;
  59034. }
  59035. index++;
  59036. }
  59037. return this;
  59038. };
  59039. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59040. u = Math.abs(u) * 0.5 + 0.5;
  59041. v = Math.abs(v) * 0.5 + 0.5;
  59042. var wrappedU = ((u * width) % width) | 0;
  59043. var wrappedV = ((v * height) % height) | 0;
  59044. var position = (wrappedU + wrappedV * width) * 4;
  59045. return pixels[position] / 255;
  59046. };
  59047. ParticleSystem.prototype._reset = function () {
  59048. this._resetEffect();
  59049. };
  59050. ParticleSystem.prototype._resetEffect = function () {
  59051. if (this._vertexBuffer) {
  59052. this._vertexBuffer.dispose();
  59053. this._vertexBuffer = null;
  59054. }
  59055. if (this._spriteBuffer) {
  59056. this._spriteBuffer.dispose();
  59057. this._spriteBuffer = null;
  59058. }
  59059. this._createVertexBuffers();
  59060. };
  59061. ParticleSystem.prototype._createVertexBuffers = function () {
  59062. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59063. if (this._isAnimationSheetEnabled) {
  59064. this._vertexBufferSize += 1;
  59065. }
  59066. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59067. this._vertexBufferSize += 3;
  59068. }
  59069. if (this._useRampGradients) {
  59070. this._vertexBufferSize += 4;
  59071. }
  59072. var engine = this._scene.getEngine();
  59073. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59074. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59075. var dataOffset = 0;
  59076. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59077. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59078. dataOffset += 3;
  59079. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59080. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59081. dataOffset += 4;
  59082. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59083. this._vertexBuffers["angle"] = options;
  59084. dataOffset += 1;
  59085. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59086. this._vertexBuffers["size"] = size;
  59087. dataOffset += 2;
  59088. if (this._isAnimationSheetEnabled) {
  59089. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59090. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59091. dataOffset += 1;
  59092. }
  59093. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59094. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59095. this._vertexBuffers["direction"] = directionBuffer;
  59096. dataOffset += 3;
  59097. }
  59098. if (this._useRampGradients) {
  59099. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59100. this._vertexBuffers["remapData"] = rampDataBuffer;
  59101. dataOffset += 4;
  59102. }
  59103. var offsets;
  59104. if (this._useInstancing) {
  59105. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59106. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59107. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59108. }
  59109. else {
  59110. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59111. dataOffset += 2;
  59112. }
  59113. this._vertexBuffers["offset"] = offsets;
  59114. };
  59115. ParticleSystem.prototype._createIndexBuffer = function () {
  59116. if (this._useInstancing) {
  59117. return;
  59118. }
  59119. var indices = [];
  59120. var index = 0;
  59121. for (var count = 0; count < this._capacity; count++) {
  59122. indices.push(index);
  59123. indices.push(index + 1);
  59124. indices.push(index + 2);
  59125. indices.push(index);
  59126. indices.push(index + 2);
  59127. indices.push(index + 3);
  59128. index += 4;
  59129. }
  59130. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59131. };
  59132. /**
  59133. * Gets the maximum number of particles active at the same time.
  59134. * @returns The max number of active particles.
  59135. */
  59136. ParticleSystem.prototype.getCapacity = function () {
  59137. return this._capacity;
  59138. };
  59139. /**
  59140. * Gets whether there are still active particles in the system.
  59141. * @returns True if it is alive, otherwise false.
  59142. */
  59143. ParticleSystem.prototype.isAlive = function () {
  59144. return this._alive;
  59145. };
  59146. /**
  59147. * Gets if the system has been started. (Note: this will still be true after stop is called)
  59148. * @returns True if it has been started, otherwise false.
  59149. */
  59150. ParticleSystem.prototype.isStarted = function () {
  59151. return this._started;
  59152. };
  59153. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  59154. var _this = this;
  59155. this._subEmitters = new Array();
  59156. if (this.subEmitters) {
  59157. this.subEmitters.forEach(function (subEmitter) {
  59158. if (subEmitter instanceof ParticleSystem) {
  59159. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  59160. }
  59161. else if (subEmitter instanceof BABYLON.SubEmitter) {
  59162. _this._subEmitters.push([subEmitter]);
  59163. }
  59164. else if (subEmitter instanceof Array) {
  59165. _this._subEmitters.push(subEmitter);
  59166. }
  59167. });
  59168. }
  59169. };
  59170. /**
  59171. * Starts the particle system and begins to emit
  59172. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  59173. */
  59174. ParticleSystem.prototype.start = function (delay) {
  59175. var _this = this;
  59176. if (delay === void 0) { delay = this.startDelay; }
  59177. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  59178. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  59179. }
  59180. if (delay) {
  59181. setTimeout(function () {
  59182. _this.start(0);
  59183. }, delay);
  59184. return;
  59185. }
  59186. // Convert the subEmitters field to the constant type field _subEmitters
  59187. this._prepareSubEmitterInternalArray();
  59188. this._started = true;
  59189. this._stopped = false;
  59190. this._actualFrame = 0;
  59191. if (this._subEmitters && this._subEmitters.length != 0) {
  59192. this.activeSubSystems = new Array();
  59193. }
  59194. if (this.preWarmCycles) {
  59195. if (this.emitter instanceof BABYLON.AbstractMesh) {
  59196. this.emitter.computeWorldMatrix(true);
  59197. }
  59198. var noiseTextureAsProcedural_1 = this.noiseTexture;
  59199. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  59200. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  59201. setTimeout(function () {
  59202. for (var index = 0; index < _this.preWarmCycles; index++) {
  59203. _this.animate(true);
  59204. noiseTextureAsProcedural_1.render();
  59205. }
  59206. });
  59207. });
  59208. }
  59209. else {
  59210. for (var index = 0; index < this.preWarmCycles; index++) {
  59211. this.animate(true);
  59212. }
  59213. }
  59214. }
  59215. // Animations
  59216. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  59217. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  59218. }
  59219. };
  59220. /**
  59221. * Stops the particle system.
  59222. * @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.
  59223. */
  59224. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  59225. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  59226. this._stopped = true;
  59227. if (stopSubEmitters) {
  59228. this._stopSubEmitters();
  59229. }
  59230. };
  59231. // animation sheet
  59232. /**
  59233. * Remove all active particles
  59234. */
  59235. ParticleSystem.prototype.reset = function () {
  59236. this._stockParticles = [];
  59237. this._particles = [];
  59238. };
  59239. /**
  59240. * @hidden (for internal use only)
  59241. */
  59242. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59243. var offset = index * this._vertexBufferSize;
  59244. this._vertexData[offset++] = particle.position.x;
  59245. this._vertexData[offset++] = particle.position.y;
  59246. this._vertexData[offset++] = particle.position.z;
  59247. this._vertexData[offset++] = particle.color.r;
  59248. this._vertexData[offset++] = particle.color.g;
  59249. this._vertexData[offset++] = particle.color.b;
  59250. this._vertexData[offset++] = particle.color.a;
  59251. this._vertexData[offset++] = particle.angle;
  59252. this._vertexData[offset++] = particle.scale.x * particle.size;
  59253. this._vertexData[offset++] = particle.scale.y * particle.size;
  59254. if (this._isAnimationSheetEnabled) {
  59255. this._vertexData[offset++] = particle.cellIndex;
  59256. }
  59257. if (!this._isBillboardBased) {
  59258. if (particle._initialDirection) {
  59259. this._vertexData[offset++] = particle._initialDirection.x;
  59260. this._vertexData[offset++] = particle._initialDirection.y;
  59261. this._vertexData[offset++] = particle._initialDirection.z;
  59262. }
  59263. else {
  59264. this._vertexData[offset++] = particle.direction.x;
  59265. this._vertexData[offset++] = particle.direction.y;
  59266. this._vertexData[offset++] = particle.direction.z;
  59267. }
  59268. }
  59269. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59270. this._vertexData[offset++] = particle.direction.x;
  59271. this._vertexData[offset++] = particle.direction.y;
  59272. this._vertexData[offset++] = particle.direction.z;
  59273. }
  59274. if (this._useRampGradients) {
  59275. this._vertexData[offset++] = particle.remapData.x;
  59276. this._vertexData[offset++] = particle.remapData.y;
  59277. this._vertexData[offset++] = particle.remapData.z;
  59278. this._vertexData[offset++] = particle.remapData.w;
  59279. }
  59280. if (!this._useInstancing) {
  59281. if (this._isAnimationSheetEnabled) {
  59282. if (offsetX === 0)
  59283. offsetX = this._epsilon;
  59284. else if (offsetX === 1)
  59285. offsetX = 1 - this._epsilon;
  59286. if (offsetY === 0)
  59287. offsetY = this._epsilon;
  59288. else if (offsetY === 1)
  59289. offsetY = 1 - this._epsilon;
  59290. }
  59291. this._vertexData[offset++] = offsetX;
  59292. this._vertexData[offset++] = offsetY;
  59293. }
  59294. };
  59295. ParticleSystem.prototype._stopSubEmitters = function () {
  59296. if (!this.activeSubSystems) {
  59297. return;
  59298. }
  59299. this.activeSubSystems.forEach(function (subSystem) {
  59300. subSystem.stop(true);
  59301. });
  59302. this.activeSubSystems = new Array();
  59303. };
  59304. ParticleSystem.prototype._removeFromRoot = function () {
  59305. if (!this._rootParticleSystem) {
  59306. return;
  59307. }
  59308. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59309. if (index !== -1) {
  59310. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59311. }
  59312. this._rootParticleSystem = null;
  59313. };
  59314. // End of sub system methods
  59315. ParticleSystem.prototype._update = function (newParticles) {
  59316. var _this = this;
  59317. // Update current
  59318. this._alive = this._particles.length > 0;
  59319. if (this.emitter.position) {
  59320. var emitterMesh = this.emitter;
  59321. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59322. }
  59323. else {
  59324. var emitterPosition = this.emitter;
  59325. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59326. }
  59327. this.updateFunction(this._particles);
  59328. // Add new ones
  59329. var particle;
  59330. var _loop_2 = function () {
  59331. if (this_1._particles.length === this_1._capacity) {
  59332. return "break";
  59333. }
  59334. particle = this_1._createParticle();
  59335. this_1._particles.push(particle);
  59336. // Emitter
  59337. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59338. if (this_1.startPositionFunction) {
  59339. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59340. }
  59341. else {
  59342. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59343. }
  59344. if (this_1.startDirectionFunction) {
  59345. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59346. }
  59347. else {
  59348. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59349. }
  59350. if (emitPower === 0) {
  59351. if (!particle._initialDirection) {
  59352. particle._initialDirection = particle.direction.clone();
  59353. }
  59354. else {
  59355. particle._initialDirection.copyFrom(particle.direction);
  59356. }
  59357. }
  59358. else {
  59359. particle._initialDirection = null;
  59360. }
  59361. particle.direction.scaleInPlace(emitPower);
  59362. // Life time
  59363. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  59364. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  59365. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  59366. var factorGradient1 = currentGradient;
  59367. var factorGradient2 = nextGradient;
  59368. var lifeTime1 = factorGradient1.getFactor();
  59369. var lifeTime2 = factorGradient2.getFactor();
  59370. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  59371. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  59372. });
  59373. }
  59374. else {
  59375. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  59376. }
  59377. // Size
  59378. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  59379. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  59380. }
  59381. else {
  59382. particle._currentSizeGradient = this_1._sizeGradients[0];
  59383. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  59384. particle.size = particle._currentSize1;
  59385. if (this_1._sizeGradients.length > 1) {
  59386. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  59387. }
  59388. else {
  59389. particle._currentSize2 = particle._currentSize1;
  59390. }
  59391. }
  59392. // Size and scale
  59393. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  59394. // Adjust scale by start size
  59395. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  59396. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  59397. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  59398. if (currentGradient !== _this._currentStartSizeGradient) {
  59399. _this._currentStartSize1 = _this._currentStartSize2;
  59400. _this._currentStartSize2 = nextGradient.getFactor();
  59401. _this._currentStartSizeGradient = currentGradient;
  59402. }
  59403. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  59404. particle.scale.scaleInPlace(value);
  59405. });
  59406. }
  59407. // Angle
  59408. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  59409. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  59410. }
  59411. else {
  59412. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  59413. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  59414. particle._currentAngularSpeed1 = particle.angularSpeed;
  59415. if (this_1._angularSpeedGradients.length > 1) {
  59416. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  59417. }
  59418. else {
  59419. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  59420. }
  59421. }
  59422. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  59423. // Velocity
  59424. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  59425. particle._currentVelocityGradient = this_1._velocityGradients[0];
  59426. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  59427. if (this_1._velocityGradients.length > 1) {
  59428. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  59429. }
  59430. else {
  59431. particle._currentVelocity2 = particle._currentVelocity1;
  59432. }
  59433. }
  59434. // Limit velocity
  59435. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  59436. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  59437. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  59438. if (this_1._limitVelocityGradients.length > 1) {
  59439. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  59440. }
  59441. else {
  59442. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  59443. }
  59444. }
  59445. // Drag
  59446. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  59447. particle._currentDragGradient = this_1._dragGradients[0];
  59448. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  59449. if (this_1._dragGradients.length > 1) {
  59450. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  59451. }
  59452. else {
  59453. particle._currentDrag2 = particle._currentDrag1;
  59454. }
  59455. }
  59456. // Color
  59457. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  59458. step = BABYLON.Scalar.RandomRange(0, 1.0);
  59459. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  59460. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  59461. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  59462. }
  59463. else {
  59464. particle._currentColorGradient = this_1._colorGradients[0];
  59465. particle._currentColorGradient.getColorToRef(particle.color);
  59466. particle._currentColor1.copyFrom(particle.color);
  59467. if (this_1._colorGradients.length > 1) {
  59468. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  59469. }
  59470. else {
  59471. particle._currentColor2.copyFrom(particle.color);
  59472. }
  59473. }
  59474. // Sheet
  59475. if (this_1._isAnimationSheetEnabled) {
  59476. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  59477. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  59478. }
  59479. // Inherited Velocity
  59480. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  59481. // Ramp
  59482. if (this_1._useRampGradients) {
  59483. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  59484. }
  59485. // Noise texture coordinates
  59486. if (this_1.noiseTexture) {
  59487. if (particle._randomNoiseCoordinates1) {
  59488. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  59489. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  59490. }
  59491. else {
  59492. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59493. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59494. }
  59495. }
  59496. // Update the position of the attached sub-emitters to match their attached particle
  59497. particle._inheritParticleInfoToSubEmitters();
  59498. };
  59499. var this_1 = this, step;
  59500. for (var index = 0; index < newParticles; index++) {
  59501. var state_1 = _loop_2();
  59502. if (state_1 === "break")
  59503. break;
  59504. }
  59505. };
  59506. /** @hidden */
  59507. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  59508. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59509. if (isBillboardBased === void 0) { isBillboardBased = false; }
  59510. if (useRampGradients === void 0) { useRampGradients = false; }
  59511. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  59512. if (isAnimationSheetEnabled) {
  59513. attributeNamesOrOptions.push("cellIndex");
  59514. }
  59515. if (!isBillboardBased) {
  59516. attributeNamesOrOptions.push("direction");
  59517. }
  59518. if (useRampGradients) {
  59519. attributeNamesOrOptions.push("remapData");
  59520. }
  59521. return attributeNamesOrOptions;
  59522. };
  59523. /** @hidden */
  59524. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  59525. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59526. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  59527. if (isAnimationSheetEnabled) {
  59528. effectCreationOption.push("particlesInfos");
  59529. }
  59530. return effectCreationOption;
  59531. };
  59532. /** @hidden */
  59533. ParticleSystem.prototype._getEffect = function (blendMode) {
  59534. if (this._customEffect) {
  59535. return this._customEffect;
  59536. }
  59537. ;
  59538. var defines = [];
  59539. if (this._scene.clipPlane) {
  59540. defines.push("#define CLIPPLANE");
  59541. }
  59542. if (this._scene.clipPlane2) {
  59543. defines.push("#define CLIPPLANE2");
  59544. }
  59545. if (this._scene.clipPlane3) {
  59546. defines.push("#define CLIPPLANE3");
  59547. }
  59548. if (this._scene.clipPlane4) {
  59549. defines.push("#define CLIPPLANE4");
  59550. }
  59551. if (this._isAnimationSheetEnabled) {
  59552. defines.push("#define ANIMATESHEET");
  59553. }
  59554. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  59555. defines.push("#define BLENDMULTIPLYMODE");
  59556. }
  59557. if (this._useRampGradients) {
  59558. defines.push("#define RAMPGRADIENT");
  59559. }
  59560. if (this._isBillboardBased) {
  59561. defines.push("#define BILLBOARD");
  59562. switch (this.billboardMode) {
  59563. case ParticleSystem.BILLBOARDMODE_Y:
  59564. defines.push("#define BILLBOARDY");
  59565. break;
  59566. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  59567. defines.push("#define BILLBOARDSTRETCHED");
  59568. break;
  59569. case ParticleSystem.BILLBOARDMODE_ALL:
  59570. default:
  59571. break;
  59572. }
  59573. }
  59574. if (this._imageProcessingConfiguration) {
  59575. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  59576. defines.push(this._imageProcessingConfigurationDefines.toString());
  59577. }
  59578. // Effect
  59579. var join = defines.join("\n");
  59580. if (this._cachedDefines !== join) {
  59581. this._cachedDefines = join;
  59582. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  59583. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  59584. var samplers = ["diffuseSampler", "rampSampler"];
  59585. if (BABYLON.ImageProcessingConfiguration) {
  59586. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  59587. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  59588. }
  59589. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  59590. }
  59591. return this._effect;
  59592. };
  59593. /**
  59594. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  59595. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  59596. */
  59597. ParticleSystem.prototype.animate = function (preWarmOnly) {
  59598. var _this = this;
  59599. if (preWarmOnly === void 0) { preWarmOnly = false; }
  59600. if (!this._started)
  59601. return;
  59602. if (!preWarmOnly) {
  59603. // Check
  59604. if (!this.isReady())
  59605. return;
  59606. if (this._currentRenderId === this._scene.getRenderId()) {
  59607. return;
  59608. }
  59609. this._currentRenderId = this._scene.getRenderId();
  59610. }
  59611. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  59612. // Determine the number of particles we need to create
  59613. var newParticles;
  59614. if (this.manualEmitCount > -1) {
  59615. newParticles = this.manualEmitCount;
  59616. this._newPartsExcess = 0;
  59617. this.manualEmitCount = 0;
  59618. }
  59619. else {
  59620. var rate_1 = this.emitRate;
  59621. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  59622. var ratio = this._actualFrame / this.targetStopDuration;
  59623. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  59624. if (currentGradient !== _this._currentEmitRateGradient) {
  59625. _this._currentEmitRate1 = _this._currentEmitRate2;
  59626. _this._currentEmitRate2 = nextGradient.getFactor();
  59627. _this._currentEmitRateGradient = currentGradient;
  59628. }
  59629. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  59630. });
  59631. }
  59632. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  59633. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  59634. }
  59635. if (this._newPartsExcess > 1.0) {
  59636. newParticles += this._newPartsExcess >> 0;
  59637. this._newPartsExcess -= this._newPartsExcess >> 0;
  59638. }
  59639. this._alive = false;
  59640. if (!this._stopped) {
  59641. this._actualFrame += this._scaledUpdateSpeed;
  59642. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  59643. this.stop();
  59644. }
  59645. else {
  59646. newParticles = 0;
  59647. }
  59648. this._update(newParticles);
  59649. // Stopped?
  59650. if (this._stopped) {
  59651. if (!this._alive) {
  59652. this._started = false;
  59653. if (this.onAnimationEnd) {
  59654. this.onAnimationEnd();
  59655. }
  59656. if (this.disposeOnStop) {
  59657. this._scene._toBeDisposed.push(this);
  59658. }
  59659. }
  59660. }
  59661. if (!preWarmOnly) {
  59662. // Update VBO
  59663. var offset = 0;
  59664. for (var index = 0; index < this._particles.length; index++) {
  59665. var particle = this._particles[index];
  59666. this._appendParticleVertices(offset, particle);
  59667. offset += this._useInstancing ? 1 : 4;
  59668. }
  59669. if (this._vertexBuffer) {
  59670. this._vertexBuffer.update(this._vertexData);
  59671. }
  59672. }
  59673. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  59674. this.stop();
  59675. }
  59676. };
  59677. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  59678. this._appendParticleVertex(offset++, particle, 0, 0);
  59679. if (!this._useInstancing) {
  59680. this._appendParticleVertex(offset++, particle, 1, 0);
  59681. this._appendParticleVertex(offset++, particle, 1, 1);
  59682. this._appendParticleVertex(offset++, particle, 0, 1);
  59683. }
  59684. };
  59685. /**
  59686. * Rebuilds the particle system.
  59687. */
  59688. ParticleSystem.prototype.rebuild = function () {
  59689. this._createIndexBuffer();
  59690. if (this._vertexBuffer) {
  59691. this._vertexBuffer._rebuild();
  59692. }
  59693. };
  59694. /**
  59695. * Is this system ready to be used/rendered
  59696. * @return true if the system is ready
  59697. */
  59698. ParticleSystem.prototype.isReady = function () {
  59699. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59700. return false;
  59701. }
  59702. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59703. if (!this._getEffect(this.blendMode).isReady()) {
  59704. return false;
  59705. }
  59706. }
  59707. else {
  59708. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  59709. return false;
  59710. }
  59711. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  59712. return false;
  59713. }
  59714. }
  59715. return true;
  59716. };
  59717. ParticleSystem.prototype._render = function (blendMode) {
  59718. var effect = this._getEffect(blendMode);
  59719. var engine = this._scene.getEngine();
  59720. // Render
  59721. engine.enableEffect(effect);
  59722. var viewMatrix = this._scene.getViewMatrix();
  59723. effect.setTexture("diffuseSampler", this.particleTexture);
  59724. effect.setMatrix("view", viewMatrix);
  59725. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  59726. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59727. var baseSize = this.particleTexture.getBaseSize();
  59728. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59729. }
  59730. effect.setVector2("translationPivot", this.translationPivot);
  59731. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  59732. if (this._isBillboardBased) {
  59733. var camera = this._scene.activeCamera;
  59734. effect.setVector3("eyePosition", camera.globalPosition);
  59735. }
  59736. if (this._rampGradientsTexture) {
  59737. effect.setTexture("rampSampler", this._rampGradientsTexture);
  59738. }
  59739. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  59740. var invView = viewMatrix.clone();
  59741. invView.invert();
  59742. effect.setMatrix("invView", invView);
  59743. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  59744. }
  59745. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  59746. // image processing
  59747. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  59748. this._imageProcessingConfiguration.bind(effect);
  59749. }
  59750. // Draw order
  59751. switch (blendMode) {
  59752. case ParticleSystem.BLENDMODE_ADD:
  59753. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  59754. break;
  59755. case ParticleSystem.BLENDMODE_ONEONE:
  59756. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  59757. break;
  59758. case ParticleSystem.BLENDMODE_STANDARD:
  59759. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59760. break;
  59761. case ParticleSystem.BLENDMODE_MULTIPLY:
  59762. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  59763. break;
  59764. }
  59765. if (this._useInstancing) {
  59766. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  59767. }
  59768. else {
  59769. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  59770. }
  59771. return this._particles.length;
  59772. };
  59773. /**
  59774. * Renders the particle system in its current state.
  59775. * @returns the current number of particles
  59776. */
  59777. ParticleSystem.prototype.render = function () {
  59778. // Check
  59779. if (!this.isReady() || !this._particles.length) {
  59780. return 0;
  59781. }
  59782. var engine = this._scene.getEngine();
  59783. engine.setState(false);
  59784. if (this.forceDepthWrite) {
  59785. engine.setDepthWrite(true);
  59786. }
  59787. var outparticles = 0;
  59788. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59789. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  59790. }
  59791. outparticles = this._render(this.blendMode);
  59792. engine.unbindInstanceAttributes();
  59793. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59794. return outparticles;
  59795. };
  59796. /**
  59797. * Disposes the particle system and free the associated resources
  59798. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  59799. */
  59800. ParticleSystem.prototype.dispose = function (disposeTexture) {
  59801. if (disposeTexture === void 0) { disposeTexture = true; }
  59802. if (this._vertexBuffer) {
  59803. this._vertexBuffer.dispose();
  59804. this._vertexBuffer = null;
  59805. }
  59806. if (this._spriteBuffer) {
  59807. this._spriteBuffer.dispose();
  59808. this._spriteBuffer = null;
  59809. }
  59810. if (this._indexBuffer) {
  59811. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59812. this._indexBuffer = null;
  59813. }
  59814. if (disposeTexture && this.particleTexture) {
  59815. this.particleTexture.dispose();
  59816. this.particleTexture = null;
  59817. }
  59818. if (disposeTexture && this.noiseTexture) {
  59819. this.noiseTexture.dispose();
  59820. this.noiseTexture = null;
  59821. }
  59822. if (this._rampGradientsTexture) {
  59823. this._rampGradientsTexture.dispose();
  59824. this._rampGradientsTexture = null;
  59825. }
  59826. this._removeFromRoot();
  59827. if (this._subEmitters && this._subEmitters.length) {
  59828. for (var index = 0; index < this._subEmitters.length; index++) {
  59829. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  59830. var subEmitter = _a[_i];
  59831. subEmitter.dispose();
  59832. }
  59833. }
  59834. this._subEmitters = [];
  59835. this.subEmitters = [];
  59836. }
  59837. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  59838. this.emitter.dispose(true);
  59839. }
  59840. // Remove from scene
  59841. var index = this._scene.particleSystems.indexOf(this);
  59842. if (index > -1) {
  59843. this._scene.particleSystems.splice(index, 1);
  59844. }
  59845. this._scene._activeParticleSystems.dispose();
  59846. // Callback
  59847. this.onDisposeObservable.notifyObservers(this);
  59848. this.onDisposeObservable.clear();
  59849. this.reset();
  59850. };
  59851. // Clone
  59852. /**
  59853. * Clones the particle system.
  59854. * @param name The name of the cloned object
  59855. * @param newEmitter The new emitter to use
  59856. * @returns the cloned particle system
  59857. */
  59858. ParticleSystem.prototype.clone = function (name, newEmitter) {
  59859. var custom = null;
  59860. var program = null;
  59861. if (this.customShader != null) {
  59862. program = this.customShader;
  59863. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59864. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59865. }
  59866. else if (this._customEffect) {
  59867. custom = this._customEffect;
  59868. }
  59869. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  59870. result.customShader = program;
  59871. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  59872. if (newEmitter === undefined) {
  59873. newEmitter = this.emitter;
  59874. }
  59875. result.noiseTexture = this.noiseTexture;
  59876. result.emitter = newEmitter;
  59877. if (this.particleTexture) {
  59878. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  59879. }
  59880. // Clone gradients
  59881. if (this._colorGradients) {
  59882. this._colorGradients.forEach(function (v) {
  59883. result.addColorGradient(v.gradient, v.color1, v.color2);
  59884. });
  59885. }
  59886. if (this._dragGradients) {
  59887. this._dragGradients.forEach(function (v) {
  59888. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  59889. });
  59890. }
  59891. if (this._angularSpeedGradients) {
  59892. this._angularSpeedGradients.forEach(function (v) {
  59893. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  59894. });
  59895. }
  59896. if (this._emitRateGradients) {
  59897. this._emitRateGradients.forEach(function (v) {
  59898. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  59899. });
  59900. }
  59901. if (this._lifeTimeGradients) {
  59902. this._lifeTimeGradients.forEach(function (v) {
  59903. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  59904. });
  59905. }
  59906. if (this._limitVelocityGradients) {
  59907. this._limitVelocityGradients.forEach(function (v) {
  59908. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  59909. });
  59910. }
  59911. if (this._sizeGradients) {
  59912. this._sizeGradients.forEach(function (v) {
  59913. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  59914. });
  59915. }
  59916. if (this._startSizeGradients) {
  59917. this._startSizeGradients.forEach(function (v) {
  59918. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  59919. });
  59920. }
  59921. if (this._velocityGradients) {
  59922. this._velocityGradients.forEach(function (v) {
  59923. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  59924. });
  59925. }
  59926. if (this._rampGradients) {
  59927. this._rampGradients.forEach(function (v) {
  59928. result.addRampGradient(v.gradient, v.color);
  59929. });
  59930. }
  59931. if (this._colorRemapGradients) {
  59932. this._colorRemapGradients.forEach(function (v) {
  59933. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  59934. });
  59935. }
  59936. if (this._alphaRemapGradients) {
  59937. this._alphaRemapGradients.forEach(function (v) {
  59938. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  59939. });
  59940. }
  59941. if (!this.preventAutoStart) {
  59942. result.start();
  59943. }
  59944. return result;
  59945. };
  59946. /**
  59947. * Serializes the particle system to a JSON object.
  59948. * @returns the JSON object
  59949. */
  59950. ParticleSystem.prototype.serialize = function () {
  59951. var serializationObject = {};
  59952. ParticleSystem._Serialize(serializationObject, this);
  59953. serializationObject.textureMask = this.textureMask.asArray();
  59954. serializationObject.customShader = this.customShader;
  59955. serializationObject.preventAutoStart = this.preventAutoStart;
  59956. // SubEmitters
  59957. if (this.subEmitters) {
  59958. serializationObject.subEmitters = [];
  59959. if (!this._subEmitters) {
  59960. this._prepareSubEmitterInternalArray();
  59961. }
  59962. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59963. var subs = _a[_i];
  59964. var cell = [];
  59965. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59966. var sub = subs_1[_b];
  59967. cell.push(sub.serialize());
  59968. }
  59969. serializationObject.subEmitters.push(cell);
  59970. }
  59971. }
  59972. return serializationObject;
  59973. };
  59974. /** @hidden */
  59975. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  59976. serializationObject.name = particleSystem.name;
  59977. serializationObject.id = particleSystem.id;
  59978. serializationObject.capacity = particleSystem.getCapacity();
  59979. // Emitter
  59980. if (particleSystem.emitter.position) {
  59981. var emitterMesh = particleSystem.emitter;
  59982. serializationObject.emitterId = emitterMesh.id;
  59983. }
  59984. else {
  59985. var emitterPosition = particleSystem.emitter;
  59986. serializationObject.emitter = emitterPosition.asArray();
  59987. }
  59988. // Emitter
  59989. if (particleSystem.particleEmitterType) {
  59990. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59991. }
  59992. if (particleSystem.particleTexture) {
  59993. serializationObject.textureName = particleSystem.particleTexture.name;
  59994. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59995. }
  59996. // Animations
  59997. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59998. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59999. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60000. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60001. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60002. // Particle system
  60003. serializationObject.startDelay = particleSystem.startDelay;
  60004. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60005. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60006. serializationObject.billboardMode = particleSystem.billboardMode;
  60007. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60008. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60009. serializationObject.minSize = particleSystem.minSize;
  60010. serializationObject.maxSize = particleSystem.maxSize;
  60011. serializationObject.minScaleX = particleSystem.minScaleX;
  60012. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60013. serializationObject.minScaleY = particleSystem.minScaleY;
  60014. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60015. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60016. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60017. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60018. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60019. serializationObject.emitRate = particleSystem.emitRate;
  60020. serializationObject.gravity = particleSystem.gravity.asArray();
  60021. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60022. serializationObject.color1 = particleSystem.color1.asArray();
  60023. serializationObject.color2 = particleSystem.color2.asArray();
  60024. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60025. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60026. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60027. serializationObject.blendMode = particleSystem.blendMode;
  60028. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60029. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60030. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60031. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60032. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60033. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60034. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60035. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60036. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60037. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60038. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60039. var colorGradients = particleSystem.getColorGradients();
  60040. if (colorGradients) {
  60041. serializationObject.colorGradients = [];
  60042. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60043. var colorGradient = colorGradients_1[_i];
  60044. var serializedGradient = {
  60045. gradient: colorGradient.gradient,
  60046. color1: colorGradient.color1.asArray()
  60047. };
  60048. if (colorGradient.color2) {
  60049. serializedGradient.color2 = colorGradient.color2.asArray();
  60050. }
  60051. serializationObject.colorGradients.push(serializedGradient);
  60052. }
  60053. }
  60054. var rampGradients = particleSystem.getRampGradients();
  60055. if (rampGradients) {
  60056. serializationObject.rampGradients = [];
  60057. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60058. var rampGradient = rampGradients_1[_a];
  60059. var serializedGradient = {
  60060. gradient: rampGradient.gradient,
  60061. color: rampGradient.color.asArray()
  60062. };
  60063. serializationObject.rampGradients.push(serializedGradient);
  60064. }
  60065. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60066. }
  60067. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60068. if (colorRemapGradients) {
  60069. serializationObject.colorRemapGradients = [];
  60070. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60071. var colorRemapGradient = colorRemapGradients_1[_b];
  60072. var serializedGradient = {
  60073. gradient: colorRemapGradient.gradient,
  60074. factor1: colorRemapGradient.factor1
  60075. };
  60076. if (colorRemapGradient.factor2 !== undefined) {
  60077. serializedGradient.factor2 = colorRemapGradient.factor2;
  60078. }
  60079. serializationObject.colorRemapGradients.push(serializedGradient);
  60080. }
  60081. }
  60082. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60083. if (alphaRemapGradients) {
  60084. serializationObject.alphaRemapGradients = [];
  60085. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60086. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60087. var serializedGradient = {
  60088. gradient: alphaRemapGradient.gradient,
  60089. factor1: alphaRemapGradient.factor1
  60090. };
  60091. if (alphaRemapGradient.factor2 !== undefined) {
  60092. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60093. }
  60094. serializationObject.alphaRemapGradients.push(serializedGradient);
  60095. }
  60096. }
  60097. var sizeGradients = particleSystem.getSizeGradients();
  60098. if (sizeGradients) {
  60099. serializationObject.sizeGradients = [];
  60100. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60101. var sizeGradient = sizeGradients_1[_d];
  60102. var serializedGradient = {
  60103. gradient: sizeGradient.gradient,
  60104. factor1: sizeGradient.factor1
  60105. };
  60106. if (sizeGradient.factor2 !== undefined) {
  60107. serializedGradient.factor2 = sizeGradient.factor2;
  60108. }
  60109. serializationObject.sizeGradients.push(serializedGradient);
  60110. }
  60111. }
  60112. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60113. if (angularSpeedGradients) {
  60114. serializationObject.angularSpeedGradients = [];
  60115. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60116. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60117. var serializedGradient = {
  60118. gradient: angularSpeedGradient.gradient,
  60119. factor1: angularSpeedGradient.factor1
  60120. };
  60121. if (angularSpeedGradient.factor2 !== undefined) {
  60122. serializedGradient.factor2 = angularSpeedGradient.factor2;
  60123. }
  60124. serializationObject.angularSpeedGradients.push(serializedGradient);
  60125. }
  60126. }
  60127. var velocityGradients = particleSystem.getVelocityGradients();
  60128. if (velocityGradients) {
  60129. serializationObject.velocityGradients = [];
  60130. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  60131. var velocityGradient = velocityGradients_1[_f];
  60132. var serializedGradient = {
  60133. gradient: velocityGradient.gradient,
  60134. factor1: velocityGradient.factor1
  60135. };
  60136. if (velocityGradient.factor2 !== undefined) {
  60137. serializedGradient.factor2 = velocityGradient.factor2;
  60138. }
  60139. serializationObject.velocityGradients.push(serializedGradient);
  60140. }
  60141. }
  60142. var dragGradients = particleSystem.getDragGradients();
  60143. if (dragGradients) {
  60144. serializationObject.dragyGradients = [];
  60145. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  60146. var dragGradient = dragGradients_1[_g];
  60147. var serializedGradient = {
  60148. gradient: dragGradient.gradient,
  60149. factor1: dragGradient.factor1
  60150. };
  60151. if (dragGradient.factor2 !== undefined) {
  60152. serializedGradient.factor2 = dragGradient.factor2;
  60153. }
  60154. serializationObject.dragGradients.push(serializedGradient);
  60155. }
  60156. }
  60157. var emitRateGradients = particleSystem.getEmitRateGradients();
  60158. if (emitRateGradients) {
  60159. serializationObject.emitRateGradients = [];
  60160. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  60161. var emitRateGradient = emitRateGradients_1[_h];
  60162. var serializedGradient = {
  60163. gradient: emitRateGradient.gradient,
  60164. factor1: emitRateGradient.factor1
  60165. };
  60166. if (emitRateGradient.factor2 !== undefined) {
  60167. serializedGradient.factor2 = emitRateGradient.factor2;
  60168. }
  60169. serializationObject.emitRateGradients.push(serializedGradient);
  60170. }
  60171. }
  60172. var startSizeGradients = particleSystem.getStartSizeGradients();
  60173. if (startSizeGradients) {
  60174. serializationObject.startSizeGradients = [];
  60175. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  60176. var startSizeGradient = startSizeGradients_1[_j];
  60177. var serializedGradient = {
  60178. gradient: startSizeGradient.gradient,
  60179. factor1: startSizeGradient.factor1
  60180. };
  60181. if (startSizeGradient.factor2 !== undefined) {
  60182. serializedGradient.factor2 = startSizeGradient.factor2;
  60183. }
  60184. serializationObject.startSizeGradients.push(serializedGradient);
  60185. }
  60186. }
  60187. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  60188. if (lifeTimeGradients) {
  60189. serializationObject.lifeTimeGradients = [];
  60190. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  60191. var lifeTimeGradient = lifeTimeGradients_1[_k];
  60192. var serializedGradient = {
  60193. gradient: lifeTimeGradient.gradient,
  60194. factor1: lifeTimeGradient.factor1
  60195. };
  60196. if (lifeTimeGradient.factor2 !== undefined) {
  60197. serializedGradient.factor2 = lifeTimeGradient.factor2;
  60198. }
  60199. serializationObject.lifeTimeGradients.push(serializedGradient);
  60200. }
  60201. }
  60202. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  60203. if (limitVelocityGradients) {
  60204. serializationObject.limitVelocityGradients = [];
  60205. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  60206. var limitVelocityGradient = limitVelocityGradients_1[_l];
  60207. var serializedGradient = {
  60208. gradient: limitVelocityGradient.gradient,
  60209. factor1: limitVelocityGradient.factor1
  60210. };
  60211. if (limitVelocityGradient.factor2 !== undefined) {
  60212. serializedGradient.factor2 = limitVelocityGradient.factor2;
  60213. }
  60214. serializationObject.limitVelocityGradients.push(serializedGradient);
  60215. }
  60216. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  60217. }
  60218. if (particleSystem.noiseTexture) {
  60219. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  60220. }
  60221. };
  60222. /** @hidden */
  60223. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  60224. // Texture
  60225. if (parsedParticleSystem.textureName) {
  60226. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  60227. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  60228. }
  60229. // Emitter
  60230. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  60231. particleSystem.emitter = BABYLON.Vector3.Zero();
  60232. }
  60233. else if (parsedParticleSystem.emitterId) {
  60234. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60235. }
  60236. else {
  60237. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60238. }
  60239. // Misc.
  60240. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60241. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60242. }
  60243. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60244. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60245. }
  60246. if (parsedParticleSystem.billboardMode !== undefined) {
  60247. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60248. }
  60249. // Animations
  60250. if (parsedParticleSystem.animations) {
  60251. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60252. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60253. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60254. }
  60255. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60256. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60257. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60258. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60259. }
  60260. if (parsedParticleSystem.autoAnimate) {
  60261. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60262. }
  60263. // Particle system
  60264. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60265. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60266. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60267. particleSystem.minSize = parsedParticleSystem.minSize;
  60268. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60269. if (parsedParticleSystem.minScaleX) {
  60270. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60271. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60272. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60273. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60274. }
  60275. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60276. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60277. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60278. }
  60279. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60280. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60281. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60282. }
  60283. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60284. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60285. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60286. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60287. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60288. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60289. if (parsedParticleSystem.noiseStrength) {
  60290. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60291. }
  60292. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60293. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60294. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60295. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60296. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60297. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60298. if (parsedParticleSystem.colorGradients) {
  60299. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60300. var colorGradient = _a[_i];
  60301. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60302. }
  60303. }
  60304. if (parsedParticleSystem.rampGradients) {
  60305. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60306. var rampGradient = _c[_b];
  60307. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60308. }
  60309. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60310. }
  60311. if (parsedParticleSystem.colorRemapGradients) {
  60312. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60313. var colorRemapGradient = _e[_d];
  60314. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60315. }
  60316. }
  60317. if (parsedParticleSystem.alphaRemapGradients) {
  60318. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60319. var alphaRemapGradient = _g[_f];
  60320. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60321. }
  60322. }
  60323. if (parsedParticleSystem.sizeGradients) {
  60324. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60325. var sizeGradient = _j[_h];
  60326. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60327. }
  60328. }
  60329. if (parsedParticleSystem.sizeGradients) {
  60330. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60331. var sizeGradient = _l[_k];
  60332. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60333. }
  60334. }
  60335. if (parsedParticleSystem.angularSpeedGradients) {
  60336. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60337. var angularSpeedGradient = _o[_m];
  60338. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60339. }
  60340. }
  60341. if (parsedParticleSystem.velocityGradients) {
  60342. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60343. var velocityGradient = _q[_p];
  60344. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60345. }
  60346. }
  60347. if (parsedParticleSystem.dragGradients) {
  60348. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  60349. var dragGradient = _s[_r];
  60350. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  60351. }
  60352. }
  60353. if (parsedParticleSystem.emitRateGradients) {
  60354. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  60355. var emitRateGradient = _u[_t];
  60356. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  60357. }
  60358. }
  60359. if (parsedParticleSystem.startSizeGradients) {
  60360. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  60361. var startSizeGradient = _w[_v];
  60362. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  60363. }
  60364. }
  60365. if (parsedParticleSystem.lifeTimeGradients) {
  60366. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  60367. var lifeTimeGradient = _y[_x];
  60368. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  60369. }
  60370. }
  60371. if (parsedParticleSystem.limitVelocityGradients) {
  60372. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  60373. var limitVelocityGradient = _0[_z];
  60374. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  60375. }
  60376. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  60377. }
  60378. if (parsedParticleSystem.noiseTexture) {
  60379. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  60380. }
  60381. // Emitter
  60382. var emitterType;
  60383. if (parsedParticleSystem.particleEmitterType) {
  60384. switch (parsedParticleSystem.particleEmitterType.type) {
  60385. case "SphereParticleEmitter":
  60386. emitterType = new BABYLON.SphereParticleEmitter();
  60387. break;
  60388. case "SphereDirectedParticleEmitter":
  60389. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  60390. break;
  60391. case "ConeEmitter":
  60392. case "ConeParticleEmitter":
  60393. emitterType = new BABYLON.ConeParticleEmitter();
  60394. break;
  60395. case "CylinderParticleEmitter":
  60396. emitterType = new BABYLON.CylinderParticleEmitter();
  60397. break;
  60398. case "HemisphericParticleEmitter":
  60399. emitterType = new BABYLON.HemisphericParticleEmitter();
  60400. break;
  60401. case "BoxEmitter":
  60402. case "BoxParticleEmitter":
  60403. default:
  60404. emitterType = new BABYLON.BoxParticleEmitter();
  60405. break;
  60406. }
  60407. emitterType.parse(parsedParticleSystem.particleEmitterType);
  60408. }
  60409. else {
  60410. emitterType = new BABYLON.BoxParticleEmitter();
  60411. emitterType.parse(parsedParticleSystem);
  60412. }
  60413. particleSystem.particleEmitterType = emitterType;
  60414. // Animation sheet
  60415. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  60416. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  60417. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  60418. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  60419. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  60420. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  60421. };
  60422. /**
  60423. * Parses a JSON object to create a particle system.
  60424. * @param parsedParticleSystem The JSON object to parse
  60425. * @param scene The scene to create the particle system in
  60426. * @param rootUrl The root url to use to load external dependencies like texture
  60427. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  60428. * @returns the Parsed particle system
  60429. */
  60430. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  60431. if (doNotStart === void 0) { doNotStart = false; }
  60432. var name = parsedParticleSystem.name;
  60433. var custom = null;
  60434. var program = null;
  60435. if (parsedParticleSystem.customShader) {
  60436. program = parsedParticleSystem.customShader;
  60437. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60438. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60439. }
  60440. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  60441. particleSystem.customShader = program;
  60442. if (parsedParticleSystem.id) {
  60443. particleSystem.id = parsedParticleSystem.id;
  60444. }
  60445. // SubEmitters
  60446. if (parsedParticleSystem.subEmitters) {
  60447. particleSystem.subEmitters = [];
  60448. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  60449. var cell = _a[_i];
  60450. var cellArray = [];
  60451. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  60452. var sub = cell_1[_b];
  60453. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  60454. }
  60455. particleSystem.subEmitters.push(cellArray);
  60456. }
  60457. }
  60458. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60459. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  60460. // Auto start
  60461. if (parsedParticleSystem.preventAutoStart) {
  60462. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  60463. }
  60464. if (!doNotStart && !particleSystem.preventAutoStart) {
  60465. particleSystem.start();
  60466. }
  60467. return particleSystem;
  60468. };
  60469. /**
  60470. * Billboard mode will only apply to Y axis
  60471. */
  60472. ParticleSystem.BILLBOARDMODE_Y = 2;
  60473. /**
  60474. * Billboard mode will apply to all axes
  60475. */
  60476. ParticleSystem.BILLBOARDMODE_ALL = 7;
  60477. /**
  60478. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  60479. */
  60480. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  60481. return ParticleSystem;
  60482. }(BABYLON.BaseParticleSystem));
  60483. BABYLON.ParticleSystem = ParticleSystem;
  60484. })(BABYLON || (BABYLON = {}));
  60485. //# sourceMappingURL=babylon.particleSystem.js.map
  60486. var BABYLON;
  60487. (function (BABYLON) {
  60488. /**
  60489. * Particle emitter emitting particles from the inside of a box.
  60490. * It emits the particles randomly between 2 given directions.
  60491. */
  60492. var BoxParticleEmitter = /** @class */ (function () {
  60493. /**
  60494. * Creates a new instance BoxParticleEmitter
  60495. */
  60496. function BoxParticleEmitter() {
  60497. /**
  60498. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60499. */
  60500. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60501. /**
  60502. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60503. */
  60504. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60505. /**
  60506. * 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.
  60507. */
  60508. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  60509. /**
  60510. * 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.
  60511. */
  60512. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  60513. }
  60514. /**
  60515. * Called by the particle System when the direction is computed for the created particle.
  60516. * @param worldMatrix is the world matrix of the particle system
  60517. * @param directionToUpdate is the direction vector to update with the result
  60518. * @param particle is the particle we are computed the direction for
  60519. */
  60520. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60521. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60522. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60523. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60524. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60525. };
  60526. /**
  60527. * Called by the particle System when the position is computed for the created particle.
  60528. * @param worldMatrix is the world matrix of the particle system
  60529. * @param positionToUpdate is the position vector to update with the result
  60530. * @param particle is the particle we are computed the position for
  60531. */
  60532. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60533. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  60534. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  60535. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  60536. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60537. };
  60538. /**
  60539. * Clones the current emitter and returns a copy of it
  60540. * @returns the new emitter
  60541. */
  60542. BoxParticleEmitter.prototype.clone = function () {
  60543. var newOne = new BoxParticleEmitter();
  60544. BABYLON.Tools.DeepCopy(this, newOne);
  60545. return newOne;
  60546. };
  60547. /**
  60548. * Called by the GPUParticleSystem to setup the update shader
  60549. * @param effect defines the update shader
  60550. */
  60551. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  60552. effect.setVector3("direction1", this.direction1);
  60553. effect.setVector3("direction2", this.direction2);
  60554. effect.setVector3("minEmitBox", this.minEmitBox);
  60555. effect.setVector3("maxEmitBox", this.maxEmitBox);
  60556. };
  60557. /**
  60558. * Returns a string to use to update the GPU particles update shader
  60559. * @returns a string containng the defines string
  60560. */
  60561. BoxParticleEmitter.prototype.getEffectDefines = function () {
  60562. return "#define BOXEMITTER";
  60563. };
  60564. /**
  60565. * Returns the string "BoxParticleEmitter"
  60566. * @returns a string containing the class name
  60567. */
  60568. BoxParticleEmitter.prototype.getClassName = function () {
  60569. return "BoxParticleEmitter";
  60570. };
  60571. /**
  60572. * Serializes the particle system to a JSON object.
  60573. * @returns the JSON object
  60574. */
  60575. BoxParticleEmitter.prototype.serialize = function () {
  60576. var serializationObject = {};
  60577. serializationObject.type = this.getClassName();
  60578. serializationObject.direction1 = this.direction1.asArray();
  60579. serializationObject.direction2 = this.direction2.asArray();
  60580. serializationObject.minEmitBox = this.minEmitBox.asArray();
  60581. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  60582. return serializationObject;
  60583. };
  60584. /**
  60585. * Parse properties from a JSON object
  60586. * @param serializationObject defines the JSON object
  60587. */
  60588. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  60589. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60590. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60591. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  60592. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  60593. };
  60594. return BoxParticleEmitter;
  60595. }());
  60596. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  60597. })(BABYLON || (BABYLON = {}));
  60598. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  60599. var BABYLON;
  60600. (function (BABYLON) {
  60601. /**
  60602. * Particle emitter emitting particles from the inside of a cylinder.
  60603. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  60604. */
  60605. var CylinderParticleEmitter = /** @class */ (function () {
  60606. /**
  60607. * Creates a new instance CylinderParticleEmitter
  60608. * @param radius the radius of the emission cylinder (1 by default)
  60609. * @param height the height of the emission cylinder (1 by default)
  60610. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60611. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60612. */
  60613. function CylinderParticleEmitter(
  60614. /**
  60615. * The radius of the emission cylinder.
  60616. */
  60617. radius,
  60618. /**
  60619. * The height of the emission cylinder.
  60620. */
  60621. height,
  60622. /**
  60623. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60624. */
  60625. radiusRange,
  60626. /**
  60627. * How much to randomize the particle direction [0-1].
  60628. */
  60629. directionRandomizer) {
  60630. if (radius === void 0) { radius = 1; }
  60631. if (height === void 0) { height = 1; }
  60632. if (radiusRange === void 0) { radiusRange = 1; }
  60633. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60634. this.radius = radius;
  60635. this.height = height;
  60636. this.radiusRange = radiusRange;
  60637. this.directionRandomizer = directionRandomizer;
  60638. }
  60639. /**
  60640. * Called by the particle System when the direction is computed for the created particle.
  60641. * @param worldMatrix is the world matrix of the particle system
  60642. * @param directionToUpdate is the direction vector to update with the result
  60643. * @param particle is the particle we are computed the direction for
  60644. */
  60645. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60646. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60647. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  60648. var angle = Math.atan2(direction.x, direction.z);
  60649. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  60650. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  60651. direction.x = Math.sin(angle);
  60652. direction.z = Math.cos(angle);
  60653. direction.normalize();
  60654. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60655. };
  60656. /**
  60657. * Called by the particle System when the position is computed for the created particle.
  60658. * @param worldMatrix is the world matrix of the particle system
  60659. * @param positionToUpdate is the position vector to update with the result
  60660. * @param particle is the particle we are computed the position for
  60661. */
  60662. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60663. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  60664. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60665. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  60666. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  60667. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  60668. var xPos = positionRadius * Math.cos(angle);
  60669. var zPos = positionRadius * Math.sin(angle);
  60670. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  60671. };
  60672. /**
  60673. * Clones the current emitter and returns a copy of it
  60674. * @returns the new emitter
  60675. */
  60676. CylinderParticleEmitter.prototype.clone = function () {
  60677. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  60678. BABYLON.Tools.DeepCopy(this, newOne);
  60679. return newOne;
  60680. };
  60681. /**
  60682. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60683. * @param effect defines the update shader
  60684. */
  60685. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  60686. effect.setFloat("radius", this.radius);
  60687. effect.setFloat("height", this.height);
  60688. effect.setFloat("radiusRange", this.radiusRange);
  60689. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60690. };
  60691. /**
  60692. * Returns a string to use to update the GPU particles update shader
  60693. * @returns a string containng the defines string
  60694. */
  60695. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  60696. return "#define CYLINDEREMITTER";
  60697. };
  60698. /**
  60699. * Returns the string "CylinderParticleEmitter"
  60700. * @returns a string containing the class name
  60701. */
  60702. CylinderParticleEmitter.prototype.getClassName = function () {
  60703. return "CylinderParticleEmitter";
  60704. };
  60705. /**
  60706. * Serializes the particle system to a JSON object.
  60707. * @returns the JSON object
  60708. */
  60709. CylinderParticleEmitter.prototype.serialize = function () {
  60710. var serializationObject = {};
  60711. serializationObject.type = this.getClassName();
  60712. serializationObject.radius = this.radius;
  60713. serializationObject.height = this.height;
  60714. serializationObject.radiusRange = this.radiusRange;
  60715. serializationObject.directionRandomizer = this.directionRandomizer;
  60716. return serializationObject;
  60717. };
  60718. /**
  60719. * Parse properties from a JSON object
  60720. * @param serializationObject defines the JSON object
  60721. */
  60722. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  60723. this.radius = serializationObject.radius;
  60724. this.height = serializationObject.height;
  60725. this.radiusRange = serializationObject.radiusRange;
  60726. this.directionRandomizer = serializationObject.directionRandomizer;
  60727. };
  60728. return CylinderParticleEmitter;
  60729. }());
  60730. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  60731. /**
  60732. * Particle emitter emitting particles from the inside of a cylinder.
  60733. * It emits the particles randomly between two vectors.
  60734. */
  60735. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  60736. __extends(CylinderDirectedParticleEmitter, _super);
  60737. /**
  60738. * Creates a new instance CylinderDirectedParticleEmitter
  60739. * @param radius the radius of the emission cylinder (1 by default)
  60740. * @param height the height of the emission cylinder (1 by default)
  60741. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60742. * @param direction1 the min limit of the emission direction (up vector by default)
  60743. * @param direction2 the max limit of the emission direction (up vector by default)
  60744. */
  60745. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  60746. /**
  60747. * The min limit of the emission direction.
  60748. */
  60749. direction1,
  60750. /**
  60751. * The max limit of the emission direction.
  60752. */
  60753. direction2) {
  60754. if (radius === void 0) { radius = 1; }
  60755. if (height === void 0) { height = 1; }
  60756. if (radiusRange === void 0) { radiusRange = 1; }
  60757. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60758. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60759. var _this = _super.call(this, radius, height, radiusRange) || this;
  60760. _this.direction1 = direction1;
  60761. _this.direction2 = direction2;
  60762. return _this;
  60763. }
  60764. /**
  60765. * Called by the particle System when the direction is computed for the created particle.
  60766. * @param worldMatrix is the world matrix of the particle system
  60767. * @param directionToUpdate is the direction vector to update with the result
  60768. * @param particle is the particle we are computed the direction for
  60769. */
  60770. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60771. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60772. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60773. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60774. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60775. };
  60776. /**
  60777. * Clones the current emitter and returns a copy of it
  60778. * @returns the new emitter
  60779. */
  60780. CylinderDirectedParticleEmitter.prototype.clone = function () {
  60781. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  60782. BABYLON.Tools.DeepCopy(this, newOne);
  60783. return newOne;
  60784. };
  60785. /**
  60786. * Called by the GPUParticleSystem to setup the update shader
  60787. * @param effect defines the update shader
  60788. */
  60789. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60790. effect.setFloat("radius", this.radius);
  60791. effect.setFloat("height", this.height);
  60792. effect.setFloat("radiusRange", this.radiusRange);
  60793. effect.setVector3("direction1", this.direction1);
  60794. effect.setVector3("direction2", this.direction2);
  60795. };
  60796. /**
  60797. * Returns a string to use to update the GPU particles update shader
  60798. * @returns a string containng the defines string
  60799. */
  60800. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60801. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  60802. };
  60803. /**
  60804. * Returns the string "CylinderDirectedParticleEmitter"
  60805. * @returns a string containing the class name
  60806. */
  60807. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  60808. return "CylinderDirectedParticleEmitter";
  60809. };
  60810. /**
  60811. * Serializes the particle system to a JSON object.
  60812. * @returns the JSON object
  60813. */
  60814. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  60815. var serializationObject = _super.prototype.serialize.call(this);
  60816. serializationObject.direction1 = this.direction1.asArray();
  60817. serializationObject.direction2 = this.direction2.asArray();
  60818. return serializationObject;
  60819. };
  60820. /**
  60821. * Parse properties from a JSON object
  60822. * @param serializationObject defines the JSON object
  60823. */
  60824. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60825. _super.prototype.parse.call(this, serializationObject);
  60826. this.direction1.copyFrom(serializationObject.direction1);
  60827. this.direction2.copyFrom(serializationObject.direction2);
  60828. };
  60829. return CylinderDirectedParticleEmitter;
  60830. }(CylinderParticleEmitter));
  60831. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  60832. })(BABYLON || (BABYLON = {}));
  60833. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  60834. var BABYLON;
  60835. (function (BABYLON) {
  60836. /**
  60837. * Particle emitter emitting particles from the inside of a cone.
  60838. * It emits the particles alongside the cone volume from the base to the particle.
  60839. * The emission direction might be randomized.
  60840. */
  60841. var ConeParticleEmitter = /** @class */ (function () {
  60842. /**
  60843. * Creates a new instance ConeParticleEmitter
  60844. * @param radius the radius of the emission cone (1 by default)
  60845. * @param angles the cone base angle (PI by default)
  60846. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  60847. */
  60848. function ConeParticleEmitter(radius, angle,
  60849. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  60850. directionRandomizer) {
  60851. if (radius === void 0) { radius = 1; }
  60852. if (angle === void 0) { angle = Math.PI; }
  60853. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60854. this.directionRandomizer = directionRandomizer;
  60855. /**
  60856. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  60857. */
  60858. this.radiusRange = 1;
  60859. /**
  60860. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  60861. */
  60862. this.heightRange = 1;
  60863. /**
  60864. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  60865. */
  60866. this.emitFromSpawnPointOnly = false;
  60867. this.angle = angle;
  60868. this.radius = radius;
  60869. }
  60870. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  60871. /**
  60872. * Gets or sets the radius of the emission cone
  60873. */
  60874. get: function () {
  60875. return this._radius;
  60876. },
  60877. set: function (value) {
  60878. this._radius = value;
  60879. this._buildHeight();
  60880. },
  60881. enumerable: true,
  60882. configurable: true
  60883. });
  60884. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  60885. /**
  60886. * Gets or sets the angle of the emission cone
  60887. */
  60888. get: function () {
  60889. return this._angle;
  60890. },
  60891. set: function (value) {
  60892. this._angle = value;
  60893. this._buildHeight();
  60894. },
  60895. enumerable: true,
  60896. configurable: true
  60897. });
  60898. ConeParticleEmitter.prototype._buildHeight = function () {
  60899. if (this._angle !== 0) {
  60900. this._height = this._radius / Math.tan(this._angle / 2);
  60901. }
  60902. else {
  60903. this._height = 1;
  60904. }
  60905. };
  60906. /**
  60907. * Called by the particle System when the direction is computed for the created particle.
  60908. * @param worldMatrix is the world matrix of the particle system
  60909. * @param directionToUpdate is the direction vector to update with the result
  60910. * @param particle is the particle we are computed the direction for
  60911. */
  60912. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60913. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  60914. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  60915. }
  60916. else {
  60917. // measure the direction Vector from the emitter to the particle.
  60918. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60919. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60920. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60921. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60922. direction.x += randX;
  60923. direction.y += randY;
  60924. direction.z += randZ;
  60925. direction.normalize();
  60926. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60927. }
  60928. };
  60929. /**
  60930. * Called by the particle System when the position is computed for the created particle.
  60931. * @param worldMatrix is the world matrix of the particle system
  60932. * @param positionToUpdate is the position vector to update with the result
  60933. * @param particle is the particle we are computed the position for
  60934. */
  60935. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60936. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  60937. var h;
  60938. if (!this.emitFromSpawnPointOnly) {
  60939. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  60940. // Better distribution in a cone at normal angles.
  60941. h = 1 - h * h;
  60942. }
  60943. else {
  60944. h = 0.0001;
  60945. }
  60946. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  60947. radius = radius * h;
  60948. var randX = radius * Math.sin(s);
  60949. var randZ = radius * Math.cos(s);
  60950. var randY = h * this._height;
  60951. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60952. };
  60953. /**
  60954. * Clones the current emitter and returns a copy of it
  60955. * @returns the new emitter
  60956. */
  60957. ConeParticleEmitter.prototype.clone = function () {
  60958. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  60959. BABYLON.Tools.DeepCopy(this, newOne);
  60960. return newOne;
  60961. };
  60962. /**
  60963. * Called by the GPUParticleSystem to setup the update shader
  60964. * @param effect defines the update shader
  60965. */
  60966. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60967. effect.setFloat2("radius", this._radius, this.radiusRange);
  60968. effect.setFloat("coneAngle", this._angle);
  60969. effect.setFloat2("height", this._height, this.heightRange);
  60970. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60971. };
  60972. /**
  60973. * Returns a string to use to update the GPU particles update shader
  60974. * @returns a string containng the defines string
  60975. */
  60976. ConeParticleEmitter.prototype.getEffectDefines = function () {
  60977. var defines = "#define CONEEMITTER";
  60978. if (this.emitFromSpawnPointOnly) {
  60979. defines += "\n#define CONEEMITTERSPAWNPOINT";
  60980. }
  60981. return defines;
  60982. };
  60983. /**
  60984. * Returns the string "ConeParticleEmitter"
  60985. * @returns a string containing the class name
  60986. */
  60987. ConeParticleEmitter.prototype.getClassName = function () {
  60988. return "ConeParticleEmitter";
  60989. };
  60990. /**
  60991. * Serializes the particle system to a JSON object.
  60992. * @returns the JSON object
  60993. */
  60994. ConeParticleEmitter.prototype.serialize = function () {
  60995. var serializationObject = {};
  60996. serializationObject.type = this.getClassName();
  60997. serializationObject.radius = this._radius;
  60998. serializationObject.angle = this._angle;
  60999. serializationObject.directionRandomizer = this.directionRandomizer;
  61000. return serializationObject;
  61001. };
  61002. /**
  61003. * Parse properties from a JSON object
  61004. * @param serializationObject defines the JSON object
  61005. */
  61006. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61007. this.radius = serializationObject.radius;
  61008. this.angle = serializationObject.angle;
  61009. this.directionRandomizer = serializationObject.directionRandomizer;
  61010. };
  61011. return ConeParticleEmitter;
  61012. }());
  61013. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61014. })(BABYLON || (BABYLON = {}));
  61015. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61016. var BABYLON;
  61017. (function (BABYLON) {
  61018. /**
  61019. * Particle emitter emitting particles from the inside of a sphere.
  61020. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61021. */
  61022. var SphereParticleEmitter = /** @class */ (function () {
  61023. /**
  61024. * Creates a new instance SphereParticleEmitter
  61025. * @param radius the radius of the emission sphere (1 by default)
  61026. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61027. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61028. */
  61029. function SphereParticleEmitter(
  61030. /**
  61031. * The radius of the emission sphere.
  61032. */
  61033. radius,
  61034. /**
  61035. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61036. */
  61037. radiusRange,
  61038. /**
  61039. * How much to randomize the particle direction [0-1].
  61040. */
  61041. directionRandomizer) {
  61042. if (radius === void 0) { radius = 1; }
  61043. if (radiusRange === void 0) { radiusRange = 1; }
  61044. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61045. this.radius = radius;
  61046. this.radiusRange = radiusRange;
  61047. this.directionRandomizer = directionRandomizer;
  61048. }
  61049. /**
  61050. * Called by the particle System when the direction is computed for the created particle.
  61051. * @param worldMatrix is the world matrix of the particle system
  61052. * @param directionToUpdate is the direction vector to update with the result
  61053. * @param particle is the particle we are computed the direction for
  61054. */
  61055. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61056. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61057. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61058. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61059. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61060. direction.x += randX;
  61061. direction.y += randY;
  61062. direction.z += randZ;
  61063. direction.normalize();
  61064. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61065. };
  61066. /**
  61067. * Called by the particle System when the position is computed for the created particle.
  61068. * @param worldMatrix is the world matrix of the particle system
  61069. * @param positionToUpdate is the position vector to update with the result
  61070. * @param particle is the particle we are computed the position for
  61071. */
  61072. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61073. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61074. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61075. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61076. var theta = Math.acos(2 * v - 1);
  61077. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61078. var randY = randRadius * Math.cos(theta);
  61079. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61080. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61081. };
  61082. /**
  61083. * Clones the current emitter and returns a copy of it
  61084. * @returns the new emitter
  61085. */
  61086. SphereParticleEmitter.prototype.clone = function () {
  61087. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61088. BABYLON.Tools.DeepCopy(this, newOne);
  61089. return newOne;
  61090. };
  61091. /**
  61092. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61093. * @param effect defines the update shader
  61094. */
  61095. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61096. effect.setFloat("radius", this.radius);
  61097. effect.setFloat("radiusRange", this.radiusRange);
  61098. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61099. };
  61100. /**
  61101. * Returns a string to use to update the GPU particles update shader
  61102. * @returns a string containng the defines string
  61103. */
  61104. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61105. return "#define SPHEREEMITTER";
  61106. };
  61107. /**
  61108. * Returns the string "SphereParticleEmitter"
  61109. * @returns a string containing the class name
  61110. */
  61111. SphereParticleEmitter.prototype.getClassName = function () {
  61112. return "SphereParticleEmitter";
  61113. };
  61114. /**
  61115. * Serializes the particle system to a JSON object.
  61116. * @returns the JSON object
  61117. */
  61118. SphereParticleEmitter.prototype.serialize = function () {
  61119. var serializationObject = {};
  61120. serializationObject.type = this.getClassName();
  61121. serializationObject.radius = this.radius;
  61122. serializationObject.radiusRange = this.radiusRange;
  61123. serializationObject.directionRandomizer = this.directionRandomizer;
  61124. return serializationObject;
  61125. };
  61126. /**
  61127. * Parse properties from a JSON object
  61128. * @param serializationObject defines the JSON object
  61129. */
  61130. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  61131. this.radius = serializationObject.radius;
  61132. this.radiusRange = serializationObject.radiusRange;
  61133. this.directionRandomizer = serializationObject.directionRandomizer;
  61134. };
  61135. return SphereParticleEmitter;
  61136. }());
  61137. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  61138. /**
  61139. * Particle emitter emitting particles from the inside of a sphere.
  61140. * It emits the particles randomly between two vectors.
  61141. */
  61142. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  61143. __extends(SphereDirectedParticleEmitter, _super);
  61144. /**
  61145. * Creates a new instance SphereDirectedParticleEmitter
  61146. * @param radius the radius of the emission sphere (1 by default)
  61147. * @param direction1 the min limit of the emission direction (up vector by default)
  61148. * @param direction2 the max limit of the emission direction (up vector by default)
  61149. */
  61150. function SphereDirectedParticleEmitter(radius,
  61151. /**
  61152. * The min limit of the emission direction.
  61153. */
  61154. direction1,
  61155. /**
  61156. * The max limit of the emission direction.
  61157. */
  61158. direction2) {
  61159. if (radius === void 0) { radius = 1; }
  61160. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61161. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61162. var _this = _super.call(this, radius) || this;
  61163. _this.direction1 = direction1;
  61164. _this.direction2 = direction2;
  61165. return _this;
  61166. }
  61167. /**
  61168. * Called by the particle System when the direction is computed for the created particle.
  61169. * @param worldMatrix is the world matrix of the particle system
  61170. * @param directionToUpdate is the direction vector to update with the result
  61171. * @param particle is the particle we are computed the direction for
  61172. */
  61173. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61174. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61175. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61176. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61177. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61178. };
  61179. /**
  61180. * Clones the current emitter and returns a copy of it
  61181. * @returns the new emitter
  61182. */
  61183. SphereDirectedParticleEmitter.prototype.clone = function () {
  61184. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  61185. BABYLON.Tools.DeepCopy(this, newOne);
  61186. return newOne;
  61187. };
  61188. /**
  61189. * Called by the GPUParticleSystem to setup the update shader
  61190. * @param effect defines the update shader
  61191. */
  61192. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61193. effect.setFloat("radius", this.radius);
  61194. effect.setFloat("radiusRange", this.radiusRange);
  61195. effect.setVector3("direction1", this.direction1);
  61196. effect.setVector3("direction2", this.direction2);
  61197. };
  61198. /**
  61199. * Returns a string to use to update the GPU particles update shader
  61200. * @returns a string containng the defines string
  61201. */
  61202. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61203. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  61204. };
  61205. /**
  61206. * Returns the string "SphereDirectedParticleEmitter"
  61207. * @returns a string containing the class name
  61208. */
  61209. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  61210. return "SphereDirectedParticleEmitter";
  61211. };
  61212. /**
  61213. * Serializes the particle system to a JSON object.
  61214. * @returns the JSON object
  61215. */
  61216. SphereDirectedParticleEmitter.prototype.serialize = function () {
  61217. var serializationObject = _super.prototype.serialize.call(this);
  61218. serializationObject.direction1 = this.direction1.asArray();
  61219. serializationObject.direction2 = this.direction2.asArray();
  61220. return serializationObject;
  61221. };
  61222. /**
  61223. * Parse properties from a JSON object
  61224. * @param serializationObject defines the JSON object
  61225. */
  61226. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61227. _super.prototype.parse.call(this, serializationObject);
  61228. this.direction1.copyFrom(serializationObject.direction1);
  61229. this.direction2.copyFrom(serializationObject.direction2);
  61230. };
  61231. return SphereDirectedParticleEmitter;
  61232. }(SphereParticleEmitter));
  61233. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  61234. })(BABYLON || (BABYLON = {}));
  61235. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61236. var BABYLON;
  61237. (function (BABYLON) {
  61238. /**
  61239. * Particle emitter emitting particles from the inside of a hemisphere.
  61240. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61241. */
  61242. var HemisphericParticleEmitter = /** @class */ (function () {
  61243. /**
  61244. * Creates a new instance HemisphericParticleEmitter
  61245. * @param radius the radius of the emission hemisphere (1 by default)
  61246. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61247. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61248. */
  61249. function HemisphericParticleEmitter(
  61250. /**
  61251. * The radius of the emission hemisphere.
  61252. */
  61253. radius,
  61254. /**
  61255. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61256. */
  61257. radiusRange,
  61258. /**
  61259. * How much to randomize the particle direction [0-1].
  61260. */
  61261. directionRandomizer) {
  61262. if (radius === void 0) { radius = 1; }
  61263. if (radiusRange === void 0) { radiusRange = 1; }
  61264. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61265. this.radius = radius;
  61266. this.radiusRange = radiusRange;
  61267. this.directionRandomizer = directionRandomizer;
  61268. }
  61269. /**
  61270. * Called by the particle System when the direction is computed for the created particle.
  61271. * @param worldMatrix is the world matrix of the particle system
  61272. * @param directionToUpdate is the direction vector to update with the result
  61273. * @param particle is the particle we are computed the direction for
  61274. */
  61275. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61276. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61277. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61278. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61279. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61280. direction.x += randX;
  61281. direction.y += randY;
  61282. direction.z += randZ;
  61283. direction.normalize();
  61284. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61285. };
  61286. /**
  61287. * Called by the particle System when the position is computed for the created particle.
  61288. * @param worldMatrix is the world matrix of the particle system
  61289. * @param positionToUpdate is the position vector to update with the result
  61290. * @param particle is the particle we are computed the position for
  61291. */
  61292. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61293. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61294. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61295. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61296. var theta = Math.acos(2 * v - 1);
  61297. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61298. var randY = randRadius * Math.cos(theta);
  61299. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61300. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61301. };
  61302. /**
  61303. * Clones the current emitter and returns a copy of it
  61304. * @returns the new emitter
  61305. */
  61306. HemisphericParticleEmitter.prototype.clone = function () {
  61307. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61308. BABYLON.Tools.DeepCopy(this, newOne);
  61309. return newOne;
  61310. };
  61311. /**
  61312. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61313. * @param effect defines the update shader
  61314. */
  61315. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61316. effect.setFloat("radius", this.radius);
  61317. effect.setFloat("radiusRange", this.radiusRange);
  61318. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61319. };
  61320. /**
  61321. * Returns a string to use to update the GPU particles update shader
  61322. * @returns a string containng the defines string
  61323. */
  61324. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61325. return "#define HEMISPHERICEMITTER";
  61326. };
  61327. /**
  61328. * Returns the string "HemisphericParticleEmitter"
  61329. * @returns a string containing the class name
  61330. */
  61331. HemisphericParticleEmitter.prototype.getClassName = function () {
  61332. return "HemisphericParticleEmitter";
  61333. };
  61334. /**
  61335. * Serializes the particle system to a JSON object.
  61336. * @returns the JSON object
  61337. */
  61338. HemisphericParticleEmitter.prototype.serialize = function () {
  61339. var serializationObject = {};
  61340. serializationObject.type = this.getClassName();
  61341. serializationObject.radius = this.radius;
  61342. serializationObject.radiusRange = this.radiusRange;
  61343. serializationObject.directionRandomizer = this.directionRandomizer;
  61344. return serializationObject;
  61345. };
  61346. /**
  61347. * Parse properties from a JSON object
  61348. * @param serializationObject defines the JSON object
  61349. */
  61350. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  61351. this.radius = serializationObject.radius;
  61352. this.radiusRange = serializationObject.radiusRange;
  61353. this.directionRandomizer = serializationObject.directionRandomizer;
  61354. };
  61355. return HemisphericParticleEmitter;
  61356. }());
  61357. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  61358. })(BABYLON || (BABYLON = {}));
  61359. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  61360. var BABYLON;
  61361. (function (BABYLON) {
  61362. /**
  61363. * Particle emitter emitting particles from a point.
  61364. * It emits the particles randomly between 2 given directions.
  61365. */
  61366. var PointParticleEmitter = /** @class */ (function () {
  61367. /**
  61368. * Creates a new instance PointParticleEmitter
  61369. */
  61370. function PointParticleEmitter() {
  61371. /**
  61372. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61373. */
  61374. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61375. /**
  61376. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61377. */
  61378. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61379. }
  61380. /**
  61381. * Called by the particle System when the direction is computed for the created particle.
  61382. * @param worldMatrix is the world matrix of the particle system
  61383. * @param directionToUpdate is the direction vector to update with the result
  61384. * @param particle is the particle we are computed the direction for
  61385. */
  61386. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61387. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61388. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61389. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61390. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61391. };
  61392. /**
  61393. * Called by the particle System when the position is computed for the created particle.
  61394. * @param worldMatrix is the world matrix of the particle system
  61395. * @param positionToUpdate is the position vector to update with the result
  61396. * @param particle is the particle we are computed the position for
  61397. */
  61398. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61399. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  61400. };
  61401. /**
  61402. * Clones the current emitter and returns a copy of it
  61403. * @returns the new emitter
  61404. */
  61405. PointParticleEmitter.prototype.clone = function () {
  61406. var newOne = new PointParticleEmitter();
  61407. BABYLON.Tools.DeepCopy(this, newOne);
  61408. return newOne;
  61409. };
  61410. /**
  61411. * Called by the GPUParticleSystem to setup the update shader
  61412. * @param effect defines the update shader
  61413. */
  61414. PointParticleEmitter.prototype.applyToShader = function (effect) {
  61415. effect.setVector3("direction1", this.direction1);
  61416. effect.setVector3("direction2", this.direction2);
  61417. };
  61418. /**
  61419. * Returns a string to use to update the GPU particles update shader
  61420. * @returns a string containng the defines string
  61421. */
  61422. PointParticleEmitter.prototype.getEffectDefines = function () {
  61423. return "#define POINTEMITTER";
  61424. };
  61425. /**
  61426. * Returns the string "PointParticleEmitter"
  61427. * @returns a string containing the class name
  61428. */
  61429. PointParticleEmitter.prototype.getClassName = function () {
  61430. return "PointParticleEmitter";
  61431. };
  61432. /**
  61433. * Serializes the particle system to a JSON object.
  61434. * @returns the JSON object
  61435. */
  61436. PointParticleEmitter.prototype.serialize = function () {
  61437. var serializationObject = {};
  61438. serializationObject.type = this.getClassName();
  61439. serializationObject.direction1 = this.direction1.asArray();
  61440. serializationObject.direction2 = this.direction2.asArray();
  61441. return serializationObject;
  61442. };
  61443. /**
  61444. * Parse properties from a JSON object
  61445. * @param serializationObject defines the JSON object
  61446. */
  61447. PointParticleEmitter.prototype.parse = function (serializationObject) {
  61448. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61449. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61450. };
  61451. return PointParticleEmitter;
  61452. }());
  61453. BABYLON.PointParticleEmitter = PointParticleEmitter;
  61454. })(BABYLON || (BABYLON = {}));
  61455. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  61456. var BABYLON;
  61457. (function (BABYLON) {
  61458. // Adds the parsers to the scene parsers.
  61459. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  61460. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  61461. if (!individualParser) {
  61462. return;
  61463. }
  61464. // Particles Systems
  61465. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61466. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61467. var parsedParticleSystem = parsedData.particleSystems[index];
  61468. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  61469. }
  61470. }
  61471. });
  61472. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  61473. if (parsedParticleSystem.activeParticleCount) {
  61474. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61475. return ps;
  61476. }
  61477. else {
  61478. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61479. return ps;
  61480. }
  61481. });
  61482. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  61483. if (uniformsNames === void 0) { uniformsNames = []; }
  61484. if (samplers === void 0) { samplers = []; }
  61485. if (defines === void 0) { defines = ""; }
  61486. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  61487. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  61488. if (defines.indexOf(" BILLBOARD") === -1) {
  61489. defines += "\n#define BILLBOARD\n";
  61490. }
  61491. if (samplers.indexOf("diffuseSampler") === -1) {
  61492. samplers.push("diffuseSampler");
  61493. }
  61494. return this.createEffect({
  61495. vertex: "particles",
  61496. fragmentElement: fragmentName
  61497. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  61498. };
  61499. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  61500. var results = new Array();
  61501. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61502. var particleSystem = this.getScene().particleSystems[index];
  61503. if (particleSystem.emitter === this) {
  61504. results.push(particleSystem);
  61505. }
  61506. }
  61507. return results;
  61508. };
  61509. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  61510. var results = new Array();
  61511. var descendants = this.getDescendants();
  61512. descendants.push(this);
  61513. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61514. var particleSystem = this.getScene().particleSystems[index];
  61515. var emitter = particleSystem.emitter;
  61516. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  61517. results.push(particleSystem);
  61518. }
  61519. }
  61520. return results;
  61521. };
  61522. })(BABYLON || (BABYLON = {}));
  61523. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  61524. var BABYLON;
  61525. (function (BABYLON) {
  61526. /**
  61527. * Type of sub emitter
  61528. */
  61529. var SubEmitterType;
  61530. (function (SubEmitterType) {
  61531. /**
  61532. * Attached to the particle over it's lifetime
  61533. */
  61534. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  61535. /**
  61536. * Created when the particle dies
  61537. */
  61538. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  61539. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  61540. /**
  61541. * Sub emitter class used to emit particles from an existing particle
  61542. */
  61543. var SubEmitter = /** @class */ (function () {
  61544. /**
  61545. * Creates a sub emitter
  61546. * @param particleSystem the particle system to be used by the sub emitter
  61547. */
  61548. function SubEmitter(
  61549. /**
  61550. * the particle system to be used by the sub emitter
  61551. */
  61552. particleSystem) {
  61553. this.particleSystem = particleSystem;
  61554. /**
  61555. * Type of the submitter (Default: END)
  61556. */
  61557. this.type = SubEmitterType.END;
  61558. /**
  61559. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  61560. * Note: This only is supported when using an emitter of type Mesh
  61561. */
  61562. this.inheritDirection = false;
  61563. /**
  61564. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  61565. */
  61566. this.inheritedVelocityAmount = 0;
  61567. }
  61568. /**
  61569. * Clones the sub emitter
  61570. * @returns the cloned sub emitter
  61571. */
  61572. SubEmitter.prototype.clone = function () {
  61573. // Clone particle system
  61574. var emitter = this.particleSystem.emitter;
  61575. if (!emitter) {
  61576. emitter = new BABYLON.Vector3();
  61577. }
  61578. else if (emitter instanceof BABYLON.Vector3) {
  61579. emitter = emitter.clone();
  61580. }
  61581. else if (emitter instanceof BABYLON.AbstractMesh) {
  61582. emitter = new BABYLON.Mesh("", emitter.getScene());
  61583. emitter.isVisible = false;
  61584. }
  61585. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  61586. // Clone properties
  61587. clone.type = this.type;
  61588. clone.inheritDirection = this.inheritDirection;
  61589. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61590. clone.particleSystem._disposeEmitterOnDispose = true;
  61591. clone.particleSystem.disposeOnStop = true;
  61592. return clone;
  61593. };
  61594. /**
  61595. * Serialize current object to a JSON object
  61596. * @returns the serialized object
  61597. */
  61598. SubEmitter.prototype.serialize = function () {
  61599. var serializationObject = {};
  61600. serializationObject.type = this.type;
  61601. serializationObject.inheritDirection = this.inheritDirection;
  61602. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61603. serializationObject.particleSystem = this.particleSystem.serialize();
  61604. return serializationObject;
  61605. };
  61606. /**
  61607. * Creates a new SubEmitter from a serialized JSON version
  61608. * @param serializationObject defines the JSON object to read from
  61609. * @param scene defines the hosting scene
  61610. * @param rootUrl defines the rootUrl for data loading
  61611. * @returns a new SubEmitter
  61612. */
  61613. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  61614. var system = serializationObject.particleSystem;
  61615. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  61616. subEmitter.type = serializationObject.type;
  61617. subEmitter.inheritDirection = serializationObject.inheritDirection;
  61618. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  61619. subEmitter.particleSystem._isSubEmitter = true;
  61620. return subEmitter;
  61621. };
  61622. /** Release associated resources */
  61623. SubEmitter.prototype.dispose = function () {
  61624. this.particleSystem.dispose();
  61625. };
  61626. return SubEmitter;
  61627. }());
  61628. BABYLON.SubEmitter = SubEmitter;
  61629. })(BABYLON || (BABYLON = {}));
  61630. //# sourceMappingURL=babylon.subEmitter.js.map
  61631. var BABYLON;
  61632. (function (BABYLON) {
  61633. /**
  61634. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61635. *
  61636. * This returned material effects how the mesh will look based on the code in the shaders.
  61637. *
  61638. * @see http://doc.babylonjs.com/how_to/shader_material
  61639. */
  61640. var ShaderMaterial = /** @class */ (function (_super) {
  61641. __extends(ShaderMaterial, _super);
  61642. /**
  61643. * Instantiate a new shader material.
  61644. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61645. * This returned material effects how the mesh will look based on the code in the shaders.
  61646. * @see http://doc.babylonjs.com/how_to/shader_material
  61647. * @param name Define the name of the material in the scene
  61648. * @param scene Define the scene the material belongs to
  61649. * @param shaderPath Defines the route to the shader code in one of three ways:
  61650. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  61651. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  61652. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  61653. * @param options Define the options used to create the shader
  61654. */
  61655. function ShaderMaterial(name, scene, shaderPath, options) {
  61656. if (options === void 0) { options = {}; }
  61657. var _this = _super.call(this, name, scene) || this;
  61658. _this._textures = {};
  61659. _this._textureArrays = {};
  61660. _this._floats = {};
  61661. _this._ints = {};
  61662. _this._floatsArrays = {};
  61663. _this._colors3 = {};
  61664. _this._colors3Arrays = {};
  61665. _this._colors4 = {};
  61666. _this._vectors2 = {};
  61667. _this._vectors3 = {};
  61668. _this._vectors4 = {};
  61669. _this._matrices = {};
  61670. _this._matrices3x3 = {};
  61671. _this._matrices2x2 = {};
  61672. _this._vectors2Arrays = {};
  61673. _this._vectors3Arrays = {};
  61674. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  61675. _this._shaderPath = shaderPath;
  61676. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  61677. return _this;
  61678. }
  61679. /**
  61680. * Gets the current class name of the material e.g. "ShaderMaterial"
  61681. * Mainly use in serialization.
  61682. * @returns the class name
  61683. */
  61684. ShaderMaterial.prototype.getClassName = function () {
  61685. return "ShaderMaterial";
  61686. };
  61687. /**
  61688. * Specifies if the material will require alpha blending
  61689. * @returns a boolean specifying if alpha blending is needed
  61690. */
  61691. ShaderMaterial.prototype.needAlphaBlending = function () {
  61692. return (this.alpha < 1.0);
  61693. };
  61694. /**
  61695. * Specifies if this material should be rendered in alpha test mode
  61696. * @returns a boolean specifying if an alpha test is needed.
  61697. */
  61698. ShaderMaterial.prototype.needAlphaTesting = function () {
  61699. return this._options.needAlphaTesting;
  61700. };
  61701. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  61702. if (this._options.uniforms.indexOf(uniformName) === -1) {
  61703. this._options.uniforms.push(uniformName);
  61704. }
  61705. };
  61706. /**
  61707. * Set a texture in the shader.
  61708. * @param name Define the name of the uniform samplers as defined in the shader
  61709. * @param texture Define the texture to bind to this sampler
  61710. * @return the material itself allowing "fluent" like uniform updates
  61711. */
  61712. ShaderMaterial.prototype.setTexture = function (name, texture) {
  61713. if (this._options.samplers.indexOf(name) === -1) {
  61714. this._options.samplers.push(name);
  61715. }
  61716. this._textures[name] = texture;
  61717. return this;
  61718. };
  61719. /**
  61720. * Set a texture array in the shader.
  61721. * @param name Define the name of the uniform sampler array as defined in the shader
  61722. * @param textures Define the list of textures to bind to this sampler
  61723. * @return the material itself allowing "fluent" like uniform updates
  61724. */
  61725. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  61726. if (this._options.samplers.indexOf(name) === -1) {
  61727. this._options.samplers.push(name);
  61728. }
  61729. this._checkUniform(name);
  61730. this._textureArrays[name] = textures;
  61731. return this;
  61732. };
  61733. /**
  61734. * Set a float in the shader.
  61735. * @param name Define the name of the uniform as defined in the shader
  61736. * @param value Define the value to give to the uniform
  61737. * @return the material itself allowing "fluent" like uniform updates
  61738. */
  61739. ShaderMaterial.prototype.setFloat = function (name, value) {
  61740. this._checkUniform(name);
  61741. this._floats[name] = value;
  61742. return this;
  61743. };
  61744. /**
  61745. * Set a int in the shader.
  61746. * @param name Define the name of the uniform as defined in the shader
  61747. * @param value Define the value to give to the uniform
  61748. * @return the material itself allowing "fluent" like uniform updates
  61749. */
  61750. ShaderMaterial.prototype.setInt = function (name, value) {
  61751. this._checkUniform(name);
  61752. this._ints[name] = value;
  61753. return this;
  61754. };
  61755. /**
  61756. * Set an array of floats in the shader.
  61757. * @param name Define the name of the uniform as defined in the shader
  61758. * @param value Define the value to give to the uniform
  61759. * @return the material itself allowing "fluent" like uniform updates
  61760. */
  61761. ShaderMaterial.prototype.setFloats = function (name, value) {
  61762. this._checkUniform(name);
  61763. this._floatsArrays[name] = value;
  61764. return this;
  61765. };
  61766. /**
  61767. * Set a vec3 in the shader from a Color3.
  61768. * @param name Define the name of the uniform as defined in the shader
  61769. * @param value Define the value to give to the uniform
  61770. * @return the material itself allowing "fluent" like uniform updates
  61771. */
  61772. ShaderMaterial.prototype.setColor3 = function (name, value) {
  61773. this._checkUniform(name);
  61774. this._colors3[name] = value;
  61775. return this;
  61776. };
  61777. /**
  61778. * Set a vec3 array in the shader from a Color3 array.
  61779. * @param name Define the name of the uniform as defined in the shader
  61780. * @param value Define the value to give to the uniform
  61781. * @return the material itself allowing "fluent" like uniform updates
  61782. */
  61783. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  61784. this._checkUniform(name);
  61785. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  61786. color.toArray(arr, arr.length);
  61787. return arr;
  61788. }, []);
  61789. return this;
  61790. };
  61791. /**
  61792. * Set a vec4 in the shader from a Color4.
  61793. * @param name Define the name of the uniform as defined in the shader
  61794. * @param value Define the value to give to the uniform
  61795. * @return the material itself allowing "fluent" like uniform updates
  61796. */
  61797. ShaderMaterial.prototype.setColor4 = function (name, value) {
  61798. this._checkUniform(name);
  61799. this._colors4[name] = value;
  61800. return this;
  61801. };
  61802. /**
  61803. * Set a vec2 in the shader from a Vector2.
  61804. * @param name Define the name of the uniform as defined in the shader
  61805. * @param value Define the value to give to the uniform
  61806. * @return the material itself allowing "fluent" like uniform updates
  61807. */
  61808. ShaderMaterial.prototype.setVector2 = function (name, value) {
  61809. this._checkUniform(name);
  61810. this._vectors2[name] = value;
  61811. return this;
  61812. };
  61813. /**
  61814. * Set a vec3 in the shader from a Vector3.
  61815. * @param name Define the name of the uniform as defined in the shader
  61816. * @param value Define the value to give to the uniform
  61817. * @return the material itself allowing "fluent" like uniform updates
  61818. */
  61819. ShaderMaterial.prototype.setVector3 = function (name, value) {
  61820. this._checkUniform(name);
  61821. this._vectors3[name] = value;
  61822. return this;
  61823. };
  61824. /**
  61825. * Set a vec4 in the shader from a Vector4.
  61826. * @param name Define the name of the uniform as defined in the shader
  61827. * @param value Define the value to give to the uniform
  61828. * @return the material itself allowing "fluent" like uniform updates
  61829. */
  61830. ShaderMaterial.prototype.setVector4 = function (name, value) {
  61831. this._checkUniform(name);
  61832. this._vectors4[name] = value;
  61833. return this;
  61834. };
  61835. /**
  61836. * Set a mat4 in the shader from a Matrix.
  61837. * @param name Define the name of the uniform as defined in the shader
  61838. * @param value Define the value to give to the uniform
  61839. * @return the material itself allowing "fluent" like uniform updates
  61840. */
  61841. ShaderMaterial.prototype.setMatrix = function (name, value) {
  61842. this._checkUniform(name);
  61843. this._matrices[name] = value;
  61844. return this;
  61845. };
  61846. /**
  61847. * Set a mat3 in the shader from a Float32Array.
  61848. * @param name Define the name of the uniform as defined in the shader
  61849. * @param value Define the value to give to the uniform
  61850. * @return the material itself allowing "fluent" like uniform updates
  61851. */
  61852. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  61853. this._checkUniform(name);
  61854. this._matrices3x3[name] = value;
  61855. return this;
  61856. };
  61857. /**
  61858. * Set a mat2 in the shader from a Float32Array.
  61859. * @param name Define the name of the uniform as defined in the shader
  61860. * @param value Define the value to give to the uniform
  61861. * @return the material itself allowing "fluent" like uniform updates
  61862. */
  61863. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  61864. this._checkUniform(name);
  61865. this._matrices2x2[name] = value;
  61866. return this;
  61867. };
  61868. /**
  61869. * Set a vec2 array in the shader from a number array.
  61870. * @param name Define the name of the uniform as defined in the shader
  61871. * @param value Define the value to give to the uniform
  61872. * @return the material itself allowing "fluent" like uniform updates
  61873. */
  61874. ShaderMaterial.prototype.setArray2 = function (name, value) {
  61875. this._checkUniform(name);
  61876. this._vectors2Arrays[name] = value;
  61877. return this;
  61878. };
  61879. /**
  61880. * Set a vec3 array in the shader from a number array.
  61881. * @param name Define the name of the uniform as defined in the shader
  61882. * @param value Define the value to give to the uniform
  61883. * @return the material itself allowing "fluent" like uniform updates
  61884. */
  61885. ShaderMaterial.prototype.setArray3 = function (name, value) {
  61886. this._checkUniform(name);
  61887. this._vectors3Arrays[name] = value;
  61888. return this;
  61889. };
  61890. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61891. if (!mesh) {
  61892. return true;
  61893. }
  61894. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  61895. return false;
  61896. }
  61897. return false;
  61898. };
  61899. /**
  61900. * Checks if the material is ready to render the requested mesh
  61901. * @param mesh Define the mesh to render
  61902. * @param useInstances Define whether or not the material is used with instances
  61903. * @returns true if ready, otherwise false
  61904. */
  61905. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  61906. var scene = this.getScene();
  61907. var engine = scene.getEngine();
  61908. if (!this.checkReadyOnEveryCall) {
  61909. if (this._renderId === scene.getRenderId()) {
  61910. if (this._checkCache(scene, mesh, useInstances)) {
  61911. return true;
  61912. }
  61913. }
  61914. }
  61915. // Instances
  61916. var defines = [];
  61917. var attribs = [];
  61918. var fallbacks = new BABYLON.EffectFallbacks();
  61919. for (var index = 0; index < this._options.defines.length; index++) {
  61920. defines.push(this._options.defines[index]);
  61921. }
  61922. for (var index = 0; index < this._options.attributes.length; index++) {
  61923. attribs.push(this._options.attributes[index]);
  61924. }
  61925. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61926. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61927. defines.push("#define VERTEXCOLOR");
  61928. }
  61929. if (useInstances) {
  61930. defines.push("#define INSTANCES");
  61931. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  61932. }
  61933. // Bones
  61934. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61935. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61936. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61937. if (mesh.numBoneInfluencers > 4) {
  61938. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61939. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61940. }
  61941. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61942. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61943. fallbacks.addCPUSkinningFallback(0, mesh);
  61944. if (this._options.uniforms.indexOf("mBones") === -1) {
  61945. this._options.uniforms.push("mBones");
  61946. }
  61947. }
  61948. else {
  61949. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61950. }
  61951. // Textures
  61952. for (var name in this._textures) {
  61953. if (!this._textures[name].isReady()) {
  61954. return false;
  61955. }
  61956. }
  61957. // Alpha test
  61958. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  61959. defines.push("#define ALPHATEST");
  61960. }
  61961. var previousEffect = this._effect;
  61962. var join = defines.join("\n");
  61963. this._effect = engine.createEffect(this._shaderPath, {
  61964. attributes: attribs,
  61965. uniformsNames: this._options.uniforms,
  61966. uniformBuffersNames: this._options.uniformBuffers,
  61967. samplers: this._options.samplers,
  61968. defines: join,
  61969. fallbacks: fallbacks,
  61970. onCompiled: this.onCompiled,
  61971. onError: this.onError
  61972. }, engine);
  61973. if (!this._effect.isReady()) {
  61974. return false;
  61975. }
  61976. if (previousEffect !== this._effect) {
  61977. scene.resetCachedMaterial();
  61978. }
  61979. this._renderId = scene.getRenderId();
  61980. return true;
  61981. };
  61982. /**
  61983. * Binds the world matrix to the material
  61984. * @param world defines the world transformation matrix
  61985. */
  61986. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61987. var scene = this.getScene();
  61988. if (!this._effect) {
  61989. return;
  61990. }
  61991. if (this._options.uniforms.indexOf("world") !== -1) {
  61992. this._effect.setMatrix("world", world);
  61993. }
  61994. if (this._options.uniforms.indexOf("worldView") !== -1) {
  61995. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  61996. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  61997. }
  61998. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  61999. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62000. }
  62001. };
  62002. /**
  62003. * Binds the material to the mesh
  62004. * @param world defines the world transformation matrix
  62005. * @param mesh defines the mesh to bind the material to
  62006. */
  62007. ShaderMaterial.prototype.bind = function (world, mesh) {
  62008. // Std values
  62009. this.bindOnlyWorldMatrix(world);
  62010. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62011. if (this._options.uniforms.indexOf("view") !== -1) {
  62012. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62013. }
  62014. if (this._options.uniforms.indexOf("projection") !== -1) {
  62015. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62016. }
  62017. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62018. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62019. }
  62020. // Bones
  62021. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62022. var name;
  62023. // Texture
  62024. for (name in this._textures) {
  62025. this._effect.setTexture(name, this._textures[name]);
  62026. }
  62027. // Texture arrays
  62028. for (name in this._textureArrays) {
  62029. this._effect.setTextureArray(name, this._textureArrays[name]);
  62030. }
  62031. // Int
  62032. for (name in this._ints) {
  62033. this._effect.setInt(name, this._ints[name]);
  62034. }
  62035. // Float
  62036. for (name in this._floats) {
  62037. this._effect.setFloat(name, this._floats[name]);
  62038. }
  62039. // Floats
  62040. for (name in this._floatsArrays) {
  62041. this._effect.setArray(name, this._floatsArrays[name]);
  62042. }
  62043. // Color3
  62044. for (name in this._colors3) {
  62045. this._effect.setColor3(name, this._colors3[name]);
  62046. }
  62047. for (name in this._colors3Arrays) {
  62048. this._effect.setArray3(name, this._colors3Arrays[name]);
  62049. }
  62050. // Color4
  62051. for (name in this._colors4) {
  62052. var color = this._colors4[name];
  62053. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62054. }
  62055. // Vector2
  62056. for (name in this._vectors2) {
  62057. this._effect.setVector2(name, this._vectors2[name]);
  62058. }
  62059. // Vector3
  62060. for (name in this._vectors3) {
  62061. this._effect.setVector3(name, this._vectors3[name]);
  62062. }
  62063. // Vector4
  62064. for (name in this._vectors4) {
  62065. this._effect.setVector4(name, this._vectors4[name]);
  62066. }
  62067. // Matrix
  62068. for (name in this._matrices) {
  62069. this._effect.setMatrix(name, this._matrices[name]);
  62070. }
  62071. // Matrix 3x3
  62072. for (name in this._matrices3x3) {
  62073. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62074. }
  62075. // Matrix 2x2
  62076. for (name in this._matrices2x2) {
  62077. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62078. }
  62079. // Vector2Array
  62080. for (name in this._vectors2Arrays) {
  62081. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62082. }
  62083. // Vector3Array
  62084. for (name in this._vectors3Arrays) {
  62085. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62086. }
  62087. }
  62088. this._afterBind(mesh);
  62089. };
  62090. /**
  62091. * Gets the active textures from the material
  62092. * @returns an array of textures
  62093. */
  62094. ShaderMaterial.prototype.getActiveTextures = function () {
  62095. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62096. for (var name in this._textures) {
  62097. activeTextures.push(this._textures[name]);
  62098. }
  62099. for (var name in this._textureArrays) {
  62100. var array = this._textureArrays[name];
  62101. for (var index = 0; index < array.length; index++) {
  62102. activeTextures.push(array[index]);
  62103. }
  62104. }
  62105. return activeTextures;
  62106. };
  62107. /**
  62108. * Specifies if the material uses a texture
  62109. * @param texture defines the texture to check against the material
  62110. * @returns a boolean specifying if the material uses the texture
  62111. */
  62112. ShaderMaterial.prototype.hasTexture = function (texture) {
  62113. if (_super.prototype.hasTexture.call(this, texture)) {
  62114. return true;
  62115. }
  62116. for (var name in this._textures) {
  62117. if (this._textures[name] === texture) {
  62118. return true;
  62119. }
  62120. }
  62121. for (var name in this._textureArrays) {
  62122. var array = this._textureArrays[name];
  62123. for (var index = 0; index < array.length; index++) {
  62124. if (array[index] === texture) {
  62125. return true;
  62126. }
  62127. }
  62128. }
  62129. return false;
  62130. };
  62131. /**
  62132. * Makes a duplicate of the material, and gives it a new name
  62133. * @param name defines the new name for the duplicated material
  62134. * @returns the cloned material
  62135. */
  62136. ShaderMaterial.prototype.clone = function (name) {
  62137. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  62138. return newShaderMaterial;
  62139. };
  62140. /**
  62141. * Disposes the material
  62142. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  62143. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  62144. */
  62145. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62146. if (forceDisposeTextures) {
  62147. var name;
  62148. for (name in this._textures) {
  62149. this._textures[name].dispose();
  62150. }
  62151. for (name in this._textureArrays) {
  62152. var array = this._textureArrays[name];
  62153. for (var index = 0; index < array.length; index++) {
  62154. array[index].dispose();
  62155. }
  62156. }
  62157. }
  62158. this._textures = {};
  62159. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62160. };
  62161. /**
  62162. * Serializes this material in a JSON representation
  62163. * @returns the serialized material object
  62164. */
  62165. ShaderMaterial.prototype.serialize = function () {
  62166. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62167. serializationObject.customType = "BABYLON.ShaderMaterial";
  62168. serializationObject.options = this._options;
  62169. serializationObject.shaderPath = this._shaderPath;
  62170. var name;
  62171. // Texture
  62172. serializationObject.textures = {};
  62173. for (name in this._textures) {
  62174. serializationObject.textures[name] = this._textures[name].serialize();
  62175. }
  62176. // Texture arrays
  62177. serializationObject.textureArrays = {};
  62178. for (name in this._textureArrays) {
  62179. serializationObject.textureArrays[name] = [];
  62180. var array = this._textureArrays[name];
  62181. for (var index = 0; index < array.length; index++) {
  62182. serializationObject.textureArrays[name].push(array[index].serialize());
  62183. }
  62184. }
  62185. // Float
  62186. serializationObject.floats = {};
  62187. for (name in this._floats) {
  62188. serializationObject.floats[name] = this._floats[name];
  62189. }
  62190. // Float s
  62191. serializationObject.FloatArrays = {};
  62192. for (name in this._floatsArrays) {
  62193. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  62194. }
  62195. // Color3
  62196. serializationObject.colors3 = {};
  62197. for (name in this._colors3) {
  62198. serializationObject.colors3[name] = this._colors3[name].asArray();
  62199. }
  62200. // Color3 array
  62201. serializationObject.colors3Arrays = {};
  62202. for (name in this._colors3Arrays) {
  62203. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  62204. }
  62205. // Color4
  62206. serializationObject.colors4 = {};
  62207. for (name in this._colors4) {
  62208. serializationObject.colors4[name] = this._colors4[name].asArray();
  62209. }
  62210. // Vector2
  62211. serializationObject.vectors2 = {};
  62212. for (name in this._vectors2) {
  62213. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  62214. }
  62215. // Vector3
  62216. serializationObject.vectors3 = {};
  62217. for (name in this._vectors3) {
  62218. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  62219. }
  62220. // Vector4
  62221. serializationObject.vectors4 = {};
  62222. for (name in this._vectors4) {
  62223. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  62224. }
  62225. // Matrix
  62226. serializationObject.matrices = {};
  62227. for (name in this._matrices) {
  62228. serializationObject.matrices[name] = this._matrices[name].asArray();
  62229. }
  62230. // Matrix 3x3
  62231. serializationObject.matrices3x3 = {};
  62232. for (name in this._matrices3x3) {
  62233. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  62234. }
  62235. // Matrix 2x2
  62236. serializationObject.matrices2x2 = {};
  62237. for (name in this._matrices2x2) {
  62238. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62239. }
  62240. // Vector2Array
  62241. serializationObject.vectors2Arrays = {};
  62242. for (name in this._vectors2Arrays) {
  62243. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62244. }
  62245. // Vector3Array
  62246. serializationObject.vectors3Arrays = {};
  62247. for (name in this._vectors3Arrays) {
  62248. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62249. }
  62250. return serializationObject;
  62251. };
  62252. /**
  62253. * Creates a shader material from parsed shader material data
  62254. * @param source defines the JSON represnetation of the material
  62255. * @param scene defines the hosting scene
  62256. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62257. * @returns a new material
  62258. */
  62259. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62260. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62261. var name;
  62262. // Texture
  62263. for (name in source.textures) {
  62264. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62265. }
  62266. // Texture arrays
  62267. for (name in source.textureArrays) {
  62268. var array = source.textureArrays[name];
  62269. var textureArray = new Array();
  62270. for (var index = 0; index < array.length; index++) {
  62271. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62272. }
  62273. material.setTextureArray(name, textureArray);
  62274. }
  62275. // Float
  62276. for (name in source.floats) {
  62277. material.setFloat(name, source.floats[name]);
  62278. }
  62279. // Float s
  62280. for (name in source.floatsArrays) {
  62281. material.setFloats(name, source.floatsArrays[name]);
  62282. }
  62283. // Color3
  62284. for (name in source.colors3) {
  62285. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62286. }
  62287. // Color3 arrays
  62288. for (name in source.colors3Arrays) {
  62289. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62290. if (i % 3 === 0) {
  62291. arr.push([num]);
  62292. }
  62293. else {
  62294. arr[arr.length - 1].push(num);
  62295. }
  62296. return arr;
  62297. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62298. material.setColor3Array(name, colors);
  62299. }
  62300. // Color4
  62301. for (name in source.colors4) {
  62302. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62303. }
  62304. // Vector2
  62305. for (name in source.vectors2) {
  62306. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62307. }
  62308. // Vector3
  62309. for (name in source.vectors3) {
  62310. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62311. }
  62312. // Vector4
  62313. for (name in source.vectors4) {
  62314. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62315. }
  62316. // Matrix
  62317. for (name in source.matrices) {
  62318. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62319. }
  62320. // Matrix 3x3
  62321. for (name in source.matrices3x3) {
  62322. material.setMatrix3x3(name, source.matrices3x3[name]);
  62323. }
  62324. // Matrix 2x2
  62325. for (name in source.matrices2x2) {
  62326. material.setMatrix2x2(name, source.matrices2x2[name]);
  62327. }
  62328. // Vector2Array
  62329. for (name in source.vectors2Arrays) {
  62330. material.setArray2(name, source.vectors2Arrays[name]);
  62331. }
  62332. // Vector3Array
  62333. for (name in source.vectors3Arrays) {
  62334. material.setArray3(name, source.vectors3Arrays[name]);
  62335. }
  62336. return material;
  62337. };
  62338. return ShaderMaterial;
  62339. }(BABYLON.Material));
  62340. BABYLON.ShaderMaterial = ShaderMaterial;
  62341. })(BABYLON || (BABYLON = {}));
  62342. //# sourceMappingURL=babylon.shaderMaterial.js.map
  62343. var BABYLON;
  62344. (function (BABYLON) {
  62345. var GroundMesh = /** @class */ (function (_super) {
  62346. __extends(GroundMesh, _super);
  62347. function GroundMesh(name, scene) {
  62348. var _this = _super.call(this, name, scene) || this;
  62349. _this.generateOctree = false;
  62350. return _this;
  62351. }
  62352. GroundMesh.prototype.getClassName = function () {
  62353. return "GroundMesh";
  62354. };
  62355. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  62356. get: function () {
  62357. return Math.min(this._subdivisionsX, this._subdivisionsY);
  62358. },
  62359. enumerable: true,
  62360. configurable: true
  62361. });
  62362. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  62363. get: function () {
  62364. return this._subdivisionsX;
  62365. },
  62366. enumerable: true,
  62367. configurable: true
  62368. });
  62369. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  62370. get: function () {
  62371. return this._subdivisionsY;
  62372. },
  62373. enumerable: true,
  62374. configurable: true
  62375. });
  62376. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  62377. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  62378. this._subdivisionsX = chunksCount;
  62379. this._subdivisionsY = chunksCount;
  62380. this.subdivide(chunksCount);
  62381. // Call the octree system optimization if it is defined.
  62382. var thisAsAny = this;
  62383. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  62384. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  62385. }
  62386. };
  62387. /**
  62388. * Returns a height (y) value in the Worl system :
  62389. * the ground altitude at the coordinates (x, z) expressed in the World system.
  62390. * Returns the ground y position if (x, z) are outside the ground surface.
  62391. */
  62392. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  62393. var world = this.getWorldMatrix();
  62394. var invMat = BABYLON.Tmp.Matrix[5];
  62395. world.invertToRef(invMat);
  62396. var tmpVect = BABYLON.Tmp.Vector3[8];
  62397. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  62398. x = tmpVect.x;
  62399. z = tmpVect.z;
  62400. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62401. return this.position.y;
  62402. }
  62403. if (!this._heightQuads || this._heightQuads.length == 0) {
  62404. this._initHeightQuads();
  62405. this._computeHeightQuads();
  62406. }
  62407. var facet = this._getFacetAt(x, z);
  62408. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  62409. // return y in the World system
  62410. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  62411. return tmpVect.y;
  62412. };
  62413. /**
  62414. * Returns a normalized vector (Vector3) orthogonal to the ground
  62415. * at the ground coordinates (x, z) expressed in the World system.
  62416. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  62417. */
  62418. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  62419. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  62420. this.getNormalAtCoordinatesToRef(x, z, normal);
  62421. return normal;
  62422. };
  62423. /**
  62424. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  62425. * at the ground coordinates (x, z) expressed in the World system.
  62426. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  62427. * Returns the GroundMesh.
  62428. */
  62429. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  62430. var world = this.getWorldMatrix();
  62431. var tmpMat = BABYLON.Tmp.Matrix[5];
  62432. world.invertToRef(tmpMat);
  62433. var tmpVect = BABYLON.Tmp.Vector3[8];
  62434. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  62435. x = tmpVect.x;
  62436. z = tmpVect.z;
  62437. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62438. return this;
  62439. }
  62440. if (!this._heightQuads || this._heightQuads.length == 0) {
  62441. this._initHeightQuads();
  62442. this._computeHeightQuads();
  62443. }
  62444. var facet = this._getFacetAt(x, z);
  62445. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  62446. return this;
  62447. };
  62448. /**
  62449. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  62450. * if the ground has been updated.
  62451. * This can be used in the render loop.
  62452. * Returns the GroundMesh.
  62453. */
  62454. GroundMesh.prototype.updateCoordinateHeights = function () {
  62455. if (!this._heightQuads || this._heightQuads.length == 0) {
  62456. this._initHeightQuads();
  62457. }
  62458. this._computeHeightQuads();
  62459. return this;
  62460. };
  62461. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  62462. GroundMesh.prototype._getFacetAt = function (x, z) {
  62463. // retrieve col and row from x, z coordinates in the ground local system
  62464. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  62465. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  62466. var quad = this._heightQuads[row * this._subdivisionsX + col];
  62467. var facet;
  62468. if (z < quad.slope.x * x + quad.slope.y) {
  62469. facet = quad.facet1;
  62470. }
  62471. else {
  62472. facet = quad.facet2;
  62473. }
  62474. return facet;
  62475. };
  62476. // Creates and populates the heightMap array with "facet" elements :
  62477. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  62478. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62479. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62480. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62481. // Returns the GroundMesh.
  62482. GroundMesh.prototype._initHeightQuads = function () {
  62483. var subdivisionsX = this._subdivisionsX;
  62484. var subdivisionsY = this._subdivisionsY;
  62485. this._heightQuads = new Array();
  62486. for (var row = 0; row < subdivisionsY; row++) {
  62487. for (var col = 0; col < subdivisionsX; col++) {
  62488. 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) };
  62489. this._heightQuads[row * subdivisionsX + col] = quad;
  62490. }
  62491. }
  62492. return this;
  62493. };
  62494. // Compute each quad element values and update the the heightMap array :
  62495. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62496. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62497. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62498. // Returns the GroundMesh.
  62499. GroundMesh.prototype._computeHeightQuads = function () {
  62500. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62501. if (!positions) {
  62502. return this;
  62503. }
  62504. var v1 = BABYLON.Tmp.Vector3[3];
  62505. var v2 = BABYLON.Tmp.Vector3[2];
  62506. var v3 = BABYLON.Tmp.Vector3[1];
  62507. var v4 = BABYLON.Tmp.Vector3[0];
  62508. var v1v2 = BABYLON.Tmp.Vector3[4];
  62509. var v1v3 = BABYLON.Tmp.Vector3[5];
  62510. var v1v4 = BABYLON.Tmp.Vector3[6];
  62511. var norm1 = BABYLON.Tmp.Vector3[7];
  62512. var norm2 = BABYLON.Tmp.Vector3[8];
  62513. var i = 0;
  62514. var j = 0;
  62515. var k = 0;
  62516. var cd = 0; // 2D slope coefficient : z = cd * x + h
  62517. var h = 0;
  62518. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  62519. var d2 = 0;
  62520. var subdivisionsX = this._subdivisionsX;
  62521. var subdivisionsY = this._subdivisionsY;
  62522. for (var row = 0; row < subdivisionsY; row++) {
  62523. for (var col = 0; col < subdivisionsX; col++) {
  62524. i = col * 3;
  62525. j = row * (subdivisionsX + 1) * 3;
  62526. k = (row + 1) * (subdivisionsX + 1) * 3;
  62527. v1.x = positions[j + i];
  62528. v1.y = positions[j + i + 1];
  62529. v1.z = positions[j + i + 2];
  62530. v2.x = positions[j + i + 3];
  62531. v2.y = positions[j + i + 4];
  62532. v2.z = positions[j + i + 5];
  62533. v3.x = positions[k + i];
  62534. v3.y = positions[k + i + 1];
  62535. v3.z = positions[k + i + 2];
  62536. v4.x = positions[k + i + 3];
  62537. v4.y = positions[k + i + 4];
  62538. v4.z = positions[k + i + 5];
  62539. // 2D slope V1V4
  62540. cd = (v4.z - v1.z) / (v4.x - v1.x);
  62541. h = v1.z - cd * v1.x; // v1 belongs to the slope
  62542. // facet equations :
  62543. // we compute each facet normal vector
  62544. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  62545. // we compute the value d by applying the equation to v1 which belongs to the plane
  62546. // then we store the facet equation in a Vector4
  62547. v2.subtractToRef(v1, v1v2);
  62548. v3.subtractToRef(v1, v1v3);
  62549. v4.subtractToRef(v1, v1v4);
  62550. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  62551. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  62552. norm1.normalize();
  62553. norm2.normalize();
  62554. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  62555. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  62556. var quad = this._heightQuads[row * subdivisionsX + col];
  62557. quad.slope.copyFromFloats(cd, h);
  62558. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  62559. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  62560. }
  62561. }
  62562. return this;
  62563. };
  62564. GroundMesh.prototype.serialize = function (serializationObject) {
  62565. _super.prototype.serialize.call(this, serializationObject);
  62566. serializationObject.subdivisionsX = this._subdivisionsX;
  62567. serializationObject.subdivisionsY = this._subdivisionsY;
  62568. serializationObject.minX = this._minX;
  62569. serializationObject.maxX = this._maxX;
  62570. serializationObject.minZ = this._minZ;
  62571. serializationObject.maxZ = this._maxZ;
  62572. serializationObject.width = this._width;
  62573. serializationObject.height = this._height;
  62574. };
  62575. GroundMesh.Parse = function (parsedMesh, scene) {
  62576. var result = new GroundMesh(parsedMesh.name, scene);
  62577. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  62578. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  62579. result._minX = parsedMesh.minX;
  62580. result._maxX = parsedMesh.maxX;
  62581. result._minZ = parsedMesh.minZ;
  62582. result._maxZ = parsedMesh.maxZ;
  62583. result._width = parsedMesh.width;
  62584. result._height = parsedMesh.height;
  62585. return result;
  62586. };
  62587. return GroundMesh;
  62588. }(BABYLON.Mesh));
  62589. BABYLON.GroundMesh = GroundMesh;
  62590. })(BABYLON || (BABYLON = {}));
  62591. //# sourceMappingURL=babylon.groundMesh.js.map
  62592. var BABYLON;
  62593. (function (BABYLON) {
  62594. /**
  62595. * Creates an instance based on a source mesh.
  62596. */
  62597. var InstancedMesh = /** @class */ (function (_super) {
  62598. __extends(InstancedMesh, _super);
  62599. function InstancedMesh(name, source) {
  62600. var _this = _super.call(this, name, source.getScene()) || this;
  62601. source.instances.push(_this);
  62602. _this._sourceMesh = source;
  62603. _this.position.copyFrom(source.position);
  62604. _this.rotation.copyFrom(source.rotation);
  62605. _this.scaling.copyFrom(source.scaling);
  62606. if (source.rotationQuaternion) {
  62607. _this.rotationQuaternion = source.rotationQuaternion.clone();
  62608. }
  62609. _this.infiniteDistance = source.infiniteDistance;
  62610. _this.setPivotMatrix(source.getPivotMatrix());
  62611. _this.refreshBoundingInfo();
  62612. _this._syncSubMeshes();
  62613. return _this;
  62614. }
  62615. /**
  62616. * Returns the string "InstancedMesh".
  62617. */
  62618. InstancedMesh.prototype.getClassName = function () {
  62619. return "InstancedMesh";
  62620. };
  62621. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  62622. // Methods
  62623. get: function () {
  62624. return this._sourceMesh.receiveShadows;
  62625. },
  62626. enumerable: true,
  62627. configurable: true
  62628. });
  62629. Object.defineProperty(InstancedMesh.prototype, "material", {
  62630. get: function () {
  62631. return this._sourceMesh.material;
  62632. },
  62633. enumerable: true,
  62634. configurable: true
  62635. });
  62636. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  62637. get: function () {
  62638. return this._sourceMesh.visibility;
  62639. },
  62640. enumerable: true,
  62641. configurable: true
  62642. });
  62643. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  62644. get: function () {
  62645. return this._sourceMesh.skeleton;
  62646. },
  62647. enumerable: true,
  62648. configurable: true
  62649. });
  62650. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  62651. get: function () {
  62652. return this._sourceMesh.renderingGroupId;
  62653. },
  62654. set: function (value) {
  62655. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  62656. return;
  62657. }
  62658. //no-op with warning
  62659. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  62660. },
  62661. enumerable: true,
  62662. configurable: true
  62663. });
  62664. /**
  62665. * Returns the total number of vertices (integer).
  62666. */
  62667. InstancedMesh.prototype.getTotalVertices = function () {
  62668. return this._sourceMesh.getTotalVertices();
  62669. };
  62670. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  62671. get: function () {
  62672. return this._sourceMesh;
  62673. },
  62674. enumerable: true,
  62675. configurable: true
  62676. });
  62677. /**
  62678. * Is this node ready to be used/rendered
  62679. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  62680. * @return {boolean} is it ready
  62681. */
  62682. InstancedMesh.prototype.isReady = function (completeCheck) {
  62683. if (completeCheck === void 0) { completeCheck = false; }
  62684. return this._sourceMesh.isReady(completeCheck, true);
  62685. };
  62686. /**
  62687. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  62688. */
  62689. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  62690. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  62691. };
  62692. /**
  62693. * Sets the vertex data of the mesh geometry for the requested `kind`.
  62694. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  62695. * The `data` are either a numeric array either a Float32Array.
  62696. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  62697. * 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).
  62698. * Note that a new underlying VertexBuffer object is created each call.
  62699. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  62700. *
  62701. * Possible `kind` values :
  62702. * - BABYLON.VertexBuffer.PositionKind
  62703. * - BABYLON.VertexBuffer.UVKind
  62704. * - BABYLON.VertexBuffer.UV2Kind
  62705. * - BABYLON.VertexBuffer.UV3Kind
  62706. * - BABYLON.VertexBuffer.UV4Kind
  62707. * - BABYLON.VertexBuffer.UV5Kind
  62708. * - BABYLON.VertexBuffer.UV6Kind
  62709. * - BABYLON.VertexBuffer.ColorKind
  62710. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62711. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62712. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62713. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62714. *
  62715. * Returns the Mesh.
  62716. */
  62717. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  62718. if (this.sourceMesh) {
  62719. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  62720. }
  62721. return this.sourceMesh;
  62722. };
  62723. /**
  62724. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  62725. * If the mesh has no geometry, it is simply returned as it is.
  62726. * The `data` are either a numeric array either a Float32Array.
  62727. * No new underlying VertexBuffer object is created.
  62728. * 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.
  62729. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  62730. *
  62731. * Possible `kind` values :
  62732. * - BABYLON.VertexBuffer.PositionKind
  62733. * - BABYLON.VertexBuffer.UVKind
  62734. * - BABYLON.VertexBuffer.UV2Kind
  62735. * - BABYLON.VertexBuffer.UV3Kind
  62736. * - BABYLON.VertexBuffer.UV4Kind
  62737. * - BABYLON.VertexBuffer.UV5Kind
  62738. * - BABYLON.VertexBuffer.UV6Kind
  62739. * - BABYLON.VertexBuffer.ColorKind
  62740. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62741. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62742. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62743. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62744. *
  62745. * Returns the Mesh.
  62746. */
  62747. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  62748. if (this.sourceMesh) {
  62749. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  62750. }
  62751. return this.sourceMesh;
  62752. };
  62753. /**
  62754. * Sets the mesh indices.
  62755. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  62756. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  62757. * This method creates a new index buffer each call.
  62758. * Returns the Mesh.
  62759. */
  62760. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  62761. if (totalVertices === void 0) { totalVertices = null; }
  62762. if (this.sourceMesh) {
  62763. this.sourceMesh.setIndices(indices, totalVertices);
  62764. }
  62765. return this.sourceMesh;
  62766. };
  62767. /**
  62768. * Boolean : True if the mesh owns the requested kind of data.
  62769. */
  62770. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  62771. return this._sourceMesh.isVerticesDataPresent(kind);
  62772. };
  62773. /**
  62774. * Returns an array of indices (IndicesArray).
  62775. */
  62776. InstancedMesh.prototype.getIndices = function () {
  62777. return this._sourceMesh.getIndices();
  62778. };
  62779. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  62780. get: function () {
  62781. return this._sourceMesh._positions;
  62782. },
  62783. enumerable: true,
  62784. configurable: true
  62785. });
  62786. /**
  62787. * Sets a new updated BoundingInfo to the mesh.
  62788. * Returns the mesh.
  62789. */
  62790. InstancedMesh.prototype.refreshBoundingInfo = function () {
  62791. var meshBB = this._sourceMesh.getBoundingInfo();
  62792. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  62793. this._updateBoundingInfo();
  62794. return this;
  62795. };
  62796. /** @hidden */
  62797. InstancedMesh.prototype._preActivate = function () {
  62798. if (this._currentLOD) {
  62799. this._currentLOD._preActivate();
  62800. }
  62801. return this;
  62802. };
  62803. /** @hidden */
  62804. InstancedMesh.prototype._activate = function (renderId) {
  62805. if (this._currentLOD) {
  62806. this._currentLOD._registerInstanceForRenderId(this, renderId);
  62807. }
  62808. return this;
  62809. };
  62810. /**
  62811. * Returns the current associated LOD AbstractMesh.
  62812. */
  62813. InstancedMesh.prototype.getLOD = function (camera) {
  62814. if (!camera) {
  62815. return this;
  62816. }
  62817. var boundingInfo = this.getBoundingInfo();
  62818. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  62819. if (this._currentLOD === this.sourceMesh) {
  62820. return this;
  62821. }
  62822. return this._currentLOD;
  62823. };
  62824. /** @hidden */
  62825. InstancedMesh.prototype._syncSubMeshes = function () {
  62826. this.releaseSubMeshes();
  62827. if (this._sourceMesh.subMeshes) {
  62828. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  62829. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  62830. }
  62831. }
  62832. return this;
  62833. };
  62834. /** @hidden */
  62835. InstancedMesh.prototype._generatePointsArray = function () {
  62836. return this._sourceMesh._generatePointsArray();
  62837. };
  62838. /**
  62839. * Creates a new InstancedMesh from the current mesh.
  62840. * - name (string) : the cloned mesh name
  62841. * - newParent (optional Node) : the optional Node to parent the clone to.
  62842. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  62843. *
  62844. * Returns the clone.
  62845. */
  62846. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62847. var result = this._sourceMesh.createInstance(name);
  62848. // Deep copy
  62849. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  62850. // Bounding info
  62851. this.refreshBoundingInfo();
  62852. // Parent
  62853. if (newParent) {
  62854. result.parent = newParent;
  62855. }
  62856. if (!doNotCloneChildren) {
  62857. // Children
  62858. for (var index = 0; index < this.getScene().meshes.length; index++) {
  62859. var mesh = this.getScene().meshes[index];
  62860. if (mesh.parent === this) {
  62861. mesh.clone(mesh.name, result);
  62862. }
  62863. }
  62864. }
  62865. result.computeWorldMatrix(true);
  62866. return result;
  62867. };
  62868. /**
  62869. * Disposes the InstancedMesh.
  62870. * Returns nothing.
  62871. */
  62872. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  62873. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  62874. // Remove from mesh
  62875. var index = this._sourceMesh.instances.indexOf(this);
  62876. this._sourceMesh.instances.splice(index, 1);
  62877. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  62878. };
  62879. return InstancedMesh;
  62880. }(BABYLON.AbstractMesh));
  62881. BABYLON.InstancedMesh = InstancedMesh;
  62882. })(BABYLON || (BABYLON = {}));
  62883. //# sourceMappingURL=babylon.instancedMesh.js.map
  62884. var BABYLON;
  62885. (function (BABYLON) {
  62886. var LinesMesh = /** @class */ (function (_super) {
  62887. __extends(LinesMesh, _super);
  62888. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  62889. if (scene === void 0) { scene = null; }
  62890. if (parent === void 0) { parent = null; }
  62891. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  62892. _this.useVertexColor = useVertexColor;
  62893. _this.useVertexAlpha = useVertexAlpha;
  62894. _this.color = new BABYLON.Color3(1, 1, 1);
  62895. _this.alpha = 1;
  62896. if (source) {
  62897. _this.color = source.color.clone();
  62898. _this.alpha = source.alpha;
  62899. _this.useVertexColor = source.useVertexColor;
  62900. _this.useVertexAlpha = source.useVertexAlpha;
  62901. }
  62902. _this._intersectionThreshold = 0.1;
  62903. var defines = [];
  62904. var options = {
  62905. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  62906. uniforms: ["world", "viewProjection"],
  62907. needAlphaBlending: true,
  62908. defines: defines
  62909. };
  62910. if (useVertexAlpha === false) {
  62911. options.needAlphaBlending = false;
  62912. }
  62913. if (!useVertexColor) {
  62914. options.uniforms.push("color");
  62915. }
  62916. else {
  62917. options.defines.push("#define VERTEXCOLOR");
  62918. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  62919. }
  62920. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  62921. return _this;
  62922. }
  62923. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  62924. /**
  62925. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62926. * This margin is expressed in world space coordinates, so its value may vary.
  62927. * Default value is 0.1
  62928. * @returns the intersection Threshold value.
  62929. */
  62930. get: function () {
  62931. return this._intersectionThreshold;
  62932. },
  62933. /**
  62934. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62935. * This margin is expressed in world space coordinates, so its value may vary.
  62936. * @param value the new threshold to apply
  62937. */
  62938. set: function (value) {
  62939. if (this._intersectionThreshold === value) {
  62940. return;
  62941. }
  62942. this._intersectionThreshold = value;
  62943. if (this.geometry) {
  62944. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  62945. }
  62946. },
  62947. enumerable: true,
  62948. configurable: true
  62949. });
  62950. /**
  62951. * Returns the string "LineMesh"
  62952. */
  62953. LinesMesh.prototype.getClassName = function () {
  62954. return "LinesMesh";
  62955. };
  62956. Object.defineProperty(LinesMesh.prototype, "material", {
  62957. /**
  62958. * @hidden
  62959. */
  62960. get: function () {
  62961. return this._colorShader;
  62962. },
  62963. /**
  62964. * @hidden
  62965. */
  62966. set: function (value) {
  62967. // Do nothing
  62968. },
  62969. enumerable: true,
  62970. configurable: true
  62971. });
  62972. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  62973. /**
  62974. * @hidden
  62975. */
  62976. get: function () {
  62977. return false;
  62978. },
  62979. enumerable: true,
  62980. configurable: true
  62981. });
  62982. /** @hidden */
  62983. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  62984. if (!this._geometry) {
  62985. return this;
  62986. }
  62987. // VBOs
  62988. this._geometry._bind(this._colorShader.getEffect());
  62989. // Color
  62990. if (!this.useVertexColor) {
  62991. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  62992. }
  62993. return this;
  62994. };
  62995. /** @hidden */
  62996. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  62997. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  62998. return this;
  62999. }
  63000. var engine = this.getScene().getEngine();
  63001. // Draw order
  63002. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63003. return this;
  63004. };
  63005. LinesMesh.prototype.dispose = function (doNotRecurse) {
  63006. this._colorShader.dispose();
  63007. _super.prototype.dispose.call(this, doNotRecurse);
  63008. };
  63009. /**
  63010. * Returns a new LineMesh object cloned from the current one.
  63011. */
  63012. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63013. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  63014. };
  63015. return LinesMesh;
  63016. }(BABYLON.Mesh));
  63017. BABYLON.LinesMesh = LinesMesh;
  63018. })(BABYLON || (BABYLON = {}));
  63019. //# sourceMappingURL=babylon.linesMesh.js.map
  63020. var BABYLON;
  63021. (function (BABYLON) {
  63022. /**
  63023. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63024. * The underlying implementation relies on an associative array to ensure the best performances.
  63025. * The value can be anything including 'null' but except 'undefined'
  63026. */
  63027. var StringDictionary = /** @class */ (function () {
  63028. function StringDictionary() {
  63029. this._count = 0;
  63030. this._data = {};
  63031. }
  63032. /**
  63033. * This will clear this dictionary and copy the content from the 'source' one.
  63034. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63035. * @param source the dictionary to take the content from and copy to this dictionary
  63036. */
  63037. StringDictionary.prototype.copyFrom = function (source) {
  63038. var _this = this;
  63039. this.clear();
  63040. source.forEach(function (t, v) { return _this.add(t, v); });
  63041. };
  63042. /**
  63043. * Get a value based from its key
  63044. * @param key the given key to get the matching value from
  63045. * @return the value if found, otherwise undefined is returned
  63046. */
  63047. StringDictionary.prototype.get = function (key) {
  63048. var val = this._data[key];
  63049. if (val !== undefined) {
  63050. return val;
  63051. }
  63052. return undefined;
  63053. };
  63054. /**
  63055. * Get a value from its key or add it if it doesn't exist.
  63056. * This method will ensure you that a given key/data will be present in the dictionary.
  63057. * @param key the given key to get the matching value from
  63058. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63059. * The factory will only be invoked if there's no data for the given key.
  63060. * @return the value corresponding to the key.
  63061. */
  63062. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63063. var val = this.get(key);
  63064. if (val !== undefined) {
  63065. return val;
  63066. }
  63067. val = factory(key);
  63068. if (val) {
  63069. this.add(key, val);
  63070. }
  63071. return val;
  63072. };
  63073. /**
  63074. * Get a value from its key if present in the dictionary otherwise add it
  63075. * @param key the key to get the value from
  63076. * @param val if there's no such key/value pair in the dictionary add it with this value
  63077. * @return the value corresponding to the key
  63078. */
  63079. StringDictionary.prototype.getOrAdd = function (key, val) {
  63080. var curVal = this.get(key);
  63081. if (curVal !== undefined) {
  63082. return curVal;
  63083. }
  63084. this.add(key, val);
  63085. return val;
  63086. };
  63087. /**
  63088. * Check if there's a given key in the dictionary
  63089. * @param key the key to check for
  63090. * @return true if the key is present, false otherwise
  63091. */
  63092. StringDictionary.prototype.contains = function (key) {
  63093. return this._data[key] !== undefined;
  63094. };
  63095. /**
  63096. * Add a new key and its corresponding value
  63097. * @param key the key to add
  63098. * @param value the value corresponding to the key
  63099. * @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
  63100. */
  63101. StringDictionary.prototype.add = function (key, value) {
  63102. if (this._data[key] !== undefined) {
  63103. return false;
  63104. }
  63105. this._data[key] = value;
  63106. ++this._count;
  63107. return true;
  63108. };
  63109. StringDictionary.prototype.set = function (key, value) {
  63110. if (this._data[key] === undefined) {
  63111. return false;
  63112. }
  63113. this._data[key] = value;
  63114. return true;
  63115. };
  63116. /**
  63117. * Get the element of the given key and remove it from the dictionary
  63118. * @param key
  63119. */
  63120. StringDictionary.prototype.getAndRemove = function (key) {
  63121. var val = this.get(key);
  63122. if (val !== undefined) {
  63123. delete this._data[key];
  63124. --this._count;
  63125. return val;
  63126. }
  63127. return null;
  63128. };
  63129. /**
  63130. * Remove a key/value from the dictionary.
  63131. * @param key the key to remove
  63132. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63133. */
  63134. StringDictionary.prototype.remove = function (key) {
  63135. if (this.contains(key)) {
  63136. delete this._data[key];
  63137. --this._count;
  63138. return true;
  63139. }
  63140. return false;
  63141. };
  63142. /**
  63143. * Clear the whole content of the dictionary
  63144. */
  63145. StringDictionary.prototype.clear = function () {
  63146. this._data = {};
  63147. this._count = 0;
  63148. };
  63149. Object.defineProperty(StringDictionary.prototype, "count", {
  63150. get: function () {
  63151. return this._count;
  63152. },
  63153. enumerable: true,
  63154. configurable: true
  63155. });
  63156. /**
  63157. * Execute a callback on each key/val of the dictionary.
  63158. * Note that you can remove any element in this dictionary in the callback implementation
  63159. * @param callback the callback to execute on a given key/value pair
  63160. */
  63161. StringDictionary.prototype.forEach = function (callback) {
  63162. for (var cur in this._data) {
  63163. var val = this._data[cur];
  63164. callback(cur, val);
  63165. }
  63166. };
  63167. /**
  63168. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63169. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63170. * Note that you can remove any element in this dictionary in the callback implementation
  63171. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63172. */
  63173. StringDictionary.prototype.first = function (callback) {
  63174. for (var cur in this._data) {
  63175. var val = this._data[cur];
  63176. var res = callback(cur, val);
  63177. if (res) {
  63178. return res;
  63179. }
  63180. }
  63181. return null;
  63182. };
  63183. return StringDictionary;
  63184. }());
  63185. BABYLON.StringDictionary = StringDictionary;
  63186. })(BABYLON || (BABYLON = {}));
  63187. //# sourceMappingURL=babylon.stringDictionary.js.map
  63188. var BABYLON;
  63189. (function (BABYLON) {
  63190. var Debug;
  63191. (function (Debug) {
  63192. /**
  63193. * Class used to render a debug view of a given skeleton
  63194. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  63195. */
  63196. var SkeletonViewer = /** @class */ (function () {
  63197. /**
  63198. * Creates a new SkeletonViewer
  63199. * @param skeleton defines the skeleton to render
  63200. * @param mesh defines the mesh attached to the skeleton
  63201. * @param scene defines the hosting scene
  63202. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  63203. * @param renderingGroupId defines the rendering group id to use with the viewer
  63204. */
  63205. function SkeletonViewer(
  63206. /** defines the skeleton to render */
  63207. skeleton,
  63208. /** defines the mesh attached to the skeleton */
  63209. mesh, scene,
  63210. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  63211. autoUpdateBonesMatrices,
  63212. /** defines the rendering group id to use with the viewer */
  63213. renderingGroupId) {
  63214. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63215. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63216. this.skeleton = skeleton;
  63217. this.mesh = mesh;
  63218. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63219. this.renderingGroupId = renderingGroupId;
  63220. /** Gets or sets the color used to render the skeleton */
  63221. this.color = BABYLON.Color3.White();
  63222. this._debugLines = new Array();
  63223. this._isEnabled = false;
  63224. this._scene = scene;
  63225. this.update();
  63226. this._renderFunction = this.update.bind(this);
  63227. }
  63228. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63229. get: function () {
  63230. return this._isEnabled;
  63231. },
  63232. /** Gets or sets a boolean indicating if the viewer is enabled */
  63233. set: function (value) {
  63234. if (this._isEnabled === value) {
  63235. return;
  63236. }
  63237. this._isEnabled = value;
  63238. if (value) {
  63239. this._scene.registerBeforeRender(this._renderFunction);
  63240. }
  63241. else {
  63242. this._scene.unregisterBeforeRender(this._renderFunction);
  63243. }
  63244. },
  63245. enumerable: true,
  63246. configurable: true
  63247. });
  63248. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63249. if (x === void 0) { x = 0; }
  63250. if (y === void 0) { y = 0; }
  63251. if (z === void 0) { z = 0; }
  63252. var tmat = BABYLON.Tmp.Matrix[0];
  63253. var parentBone = bone.getParent();
  63254. tmat.copyFrom(bone.getLocalMatrix());
  63255. if (x !== 0 || y !== 0 || z !== 0) {
  63256. var tmat2 = BABYLON.Tmp.Matrix[1];
  63257. BABYLON.Matrix.IdentityToRef(tmat2);
  63258. tmat2.m[12] = x;
  63259. tmat2.m[13] = y;
  63260. tmat2.m[14] = z;
  63261. tmat2.multiplyToRef(tmat, tmat);
  63262. }
  63263. if (parentBone) {
  63264. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63265. }
  63266. tmat.multiplyToRef(meshMat, tmat);
  63267. position.x = tmat.m[12];
  63268. position.y = tmat.m[13];
  63269. position.z = tmat.m[14];
  63270. };
  63271. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63272. var len = bones.length;
  63273. var meshPos = this.mesh.position;
  63274. for (var i = 0; i < len; i++) {
  63275. var bone = bones[i];
  63276. var points = this._debugLines[i];
  63277. if (!points) {
  63278. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63279. this._debugLines[i] = points;
  63280. }
  63281. this._getBonePosition(points[0], bone, meshMat);
  63282. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63283. points[0].subtractInPlace(meshPos);
  63284. points[1].subtractInPlace(meshPos);
  63285. }
  63286. };
  63287. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63288. var len = bones.length;
  63289. var boneNum = 0;
  63290. var meshPos = this.mesh.position;
  63291. for (var i = len - 1; i >= 0; i--) {
  63292. var childBone = bones[i];
  63293. var parentBone = childBone.getParent();
  63294. if (!parentBone) {
  63295. continue;
  63296. }
  63297. var points = this._debugLines[boneNum];
  63298. if (!points) {
  63299. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63300. this._debugLines[boneNum] = points;
  63301. }
  63302. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63303. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63304. points[0].subtractInPlace(meshPos);
  63305. points[1].subtractInPlace(meshPos);
  63306. boneNum++;
  63307. }
  63308. };
  63309. /** Update the viewer to sync with current skeleton state */
  63310. SkeletonViewer.prototype.update = function () {
  63311. if (this.autoUpdateBonesMatrices) {
  63312. this.skeleton.computeAbsoluteTransforms();
  63313. }
  63314. if (this.skeleton.bones[0].length === undefined) {
  63315. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63316. }
  63317. else {
  63318. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63319. }
  63320. if (!this._debugMesh) {
  63321. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  63322. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63323. }
  63324. else {
  63325. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63326. }
  63327. this._debugMesh.position.copyFrom(this.mesh.position);
  63328. this._debugMesh.color = this.color;
  63329. };
  63330. /** Release associated resources */
  63331. SkeletonViewer.prototype.dispose = function () {
  63332. if (this._debugMesh) {
  63333. this.isEnabled = false;
  63334. this._debugMesh.dispose();
  63335. this._debugMesh = null;
  63336. }
  63337. };
  63338. return SkeletonViewer;
  63339. }());
  63340. Debug.SkeletonViewer = SkeletonViewer;
  63341. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63342. })(BABYLON || (BABYLON = {}));
  63343. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63344. /**
  63345. * Module Debug contains the (visual) components to debug a scene correctly
  63346. */
  63347. var BABYLON;
  63348. (function (BABYLON) {
  63349. var Debug;
  63350. (function (Debug) {
  63351. /**
  63352. * The Axes viewer will show 3 axes in a specific point in space
  63353. */
  63354. var AxesViewer = /** @class */ (function () {
  63355. /**
  63356. * Creates a new AxesViewer
  63357. * @param scene defines the hosting scene
  63358. * @param scaleLines defines a number used to scale line length (1 by default)
  63359. */
  63360. function AxesViewer(scene, scaleLines) {
  63361. if (scaleLines === void 0) { scaleLines = 1; }
  63362. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63363. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63364. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63365. /**
  63366. * Gets or sets a number used to scale line length
  63367. */
  63368. this.scaleLines = 1;
  63369. this.scaleLines = scaleLines;
  63370. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63371. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63372. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63373. this._xmesh.renderingGroupId = 2;
  63374. this._ymesh.renderingGroupId = 2;
  63375. this._zmesh.renderingGroupId = 2;
  63376. this._xmesh.material.checkReadyOnlyOnce = true;
  63377. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63378. this._ymesh.material.checkReadyOnlyOnce = true;
  63379. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63380. this._zmesh.material.checkReadyOnlyOnce = true;
  63381. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63382. this.scene = scene;
  63383. }
  63384. /**
  63385. * Force the viewer to update
  63386. * @param position defines the position of the viewer
  63387. * @param xaxis defines the x axis of the viewer
  63388. * @param yaxis defines the y axis of the viewer
  63389. * @param zaxis defines the z axis of the viewer
  63390. */
  63391. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63392. var scaleLines = this.scaleLines;
  63393. if (this._xmesh) {
  63394. this._xmesh.position.copyFrom(position);
  63395. }
  63396. if (this._ymesh) {
  63397. this._ymesh.position.copyFrom(position);
  63398. }
  63399. if (this._zmesh) {
  63400. this._zmesh.position.copyFrom(position);
  63401. }
  63402. var point2 = this._xline[1];
  63403. point2.x = xaxis.x * scaleLines;
  63404. point2.y = xaxis.y * scaleLines;
  63405. point2.z = xaxis.z * scaleLines;
  63406. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  63407. point2 = this._yline[1];
  63408. point2.x = yaxis.x * scaleLines;
  63409. point2.y = yaxis.y * scaleLines;
  63410. point2.z = yaxis.z * scaleLines;
  63411. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  63412. point2 = this._zline[1];
  63413. point2.x = zaxis.x * scaleLines;
  63414. point2.y = zaxis.y * scaleLines;
  63415. point2.z = zaxis.z * scaleLines;
  63416. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  63417. };
  63418. /** Releases resources */
  63419. AxesViewer.prototype.dispose = function () {
  63420. if (this._xmesh) {
  63421. this._xmesh.dispose();
  63422. }
  63423. if (this._ymesh) {
  63424. this._ymesh.dispose();
  63425. }
  63426. if (this._zmesh) {
  63427. this._zmesh.dispose();
  63428. }
  63429. this._xmesh = null;
  63430. this._ymesh = null;
  63431. this._zmesh = null;
  63432. this.scene = null;
  63433. };
  63434. return AxesViewer;
  63435. }());
  63436. Debug.AxesViewer = AxesViewer;
  63437. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63438. })(BABYLON || (BABYLON = {}));
  63439. //# sourceMappingURL=babylon.axesViewer.js.map
  63440. var BABYLON;
  63441. (function (BABYLON) {
  63442. var Debug;
  63443. (function (Debug) {
  63444. /**
  63445. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  63446. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  63447. */
  63448. var BoneAxesViewer = /** @class */ (function (_super) {
  63449. __extends(BoneAxesViewer, _super);
  63450. /**
  63451. * Creates a new BoneAxesViewer
  63452. * @param scene defines the hosting scene
  63453. * @param bone defines the target bone
  63454. * @param mesh defines the target mesh
  63455. * @param scaleLines defines a scaling factor for line length (1 by default)
  63456. */
  63457. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63458. if (scaleLines === void 0) { scaleLines = 1; }
  63459. var _this = _super.call(this, scene, scaleLines) || this;
  63460. /** Gets current position */
  63461. _this.pos = BABYLON.Vector3.Zero();
  63462. /** Gets direction of X axis */
  63463. _this.xaxis = BABYLON.Vector3.Zero();
  63464. /** Gets direction of Y axis */
  63465. _this.yaxis = BABYLON.Vector3.Zero();
  63466. /** Gets direction of Z axis */
  63467. _this.zaxis = BABYLON.Vector3.Zero();
  63468. _this.mesh = mesh;
  63469. _this.bone = bone;
  63470. return _this;
  63471. }
  63472. /**
  63473. * Force the viewer to update
  63474. */
  63475. BoneAxesViewer.prototype.update = function () {
  63476. if (!this.mesh || !this.bone) {
  63477. return;
  63478. }
  63479. var bone = this.bone;
  63480. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63481. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63482. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63483. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63484. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63485. };
  63486. /** Releases resources */
  63487. BoneAxesViewer.prototype.dispose = function () {
  63488. if (this.mesh) {
  63489. this.mesh = null;
  63490. this.bone = null;
  63491. _super.prototype.dispose.call(this);
  63492. }
  63493. };
  63494. return BoneAxesViewer;
  63495. }(Debug.AxesViewer));
  63496. Debug.BoneAxesViewer = BoneAxesViewer;
  63497. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63498. })(BABYLON || (BABYLON = {}));
  63499. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63500. var BABYLON;
  63501. (function (BABYLON) {
  63502. /**
  63503. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63504. * in order to better appreciate the issue one might have.
  63505. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63506. */
  63507. var RayHelper = /** @class */ (function () {
  63508. /**
  63509. * Instantiate a new ray helper.
  63510. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63511. * in order to better appreciate the issue one might have.
  63512. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63513. * @param ray Defines the ray we are currently tryin to visualize
  63514. */
  63515. function RayHelper(ray) {
  63516. this.ray = ray;
  63517. }
  63518. /**
  63519. * Helper function to create a colored helper in a scene in one line.
  63520. * @param ray Defines the ray we are currently tryin to visualize
  63521. * @param scene Defines the scene the ray is used in
  63522. * @param color Defines the color we want to see the ray in
  63523. * @returns The newly created ray helper.
  63524. */
  63525. RayHelper.CreateAndShow = function (ray, scene, color) {
  63526. var helper = new RayHelper(ray);
  63527. helper.show(scene, color);
  63528. return helper;
  63529. };
  63530. /**
  63531. * Shows the ray we are willing to debug.
  63532. * @param scene Defines the scene the ray needs to be rendered in
  63533. * @param color Defines the color the ray needs to be rendered in
  63534. */
  63535. RayHelper.prototype.show = function (scene, color) {
  63536. if (!this._renderFunction && this.ray) {
  63537. var ray = this.ray;
  63538. this._renderFunction = this._render.bind(this);
  63539. this._scene = scene;
  63540. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63541. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63542. if (this._renderFunction) {
  63543. this._scene.registerBeforeRender(this._renderFunction);
  63544. }
  63545. }
  63546. if (color && this._renderLine) {
  63547. this._renderLine.color.copyFrom(color);
  63548. }
  63549. };
  63550. /**
  63551. * Hides the ray we are debugging.
  63552. */
  63553. RayHelper.prototype.hide = function () {
  63554. if (this._renderFunction && this._scene) {
  63555. this._scene.unregisterBeforeRender(this._renderFunction);
  63556. this._scene = null;
  63557. this._renderFunction = null;
  63558. if (this._renderLine) {
  63559. this._renderLine.dispose();
  63560. this._renderLine = null;
  63561. }
  63562. this._renderPoints = [];
  63563. }
  63564. };
  63565. RayHelper.prototype._render = function () {
  63566. var ray = this.ray;
  63567. if (!ray) {
  63568. return;
  63569. }
  63570. var point = this._renderPoints[1];
  63571. var len = Math.min(ray.length, 1000000);
  63572. point.copyFrom(ray.direction);
  63573. point.scaleInPlace(len);
  63574. point.addInPlace(ray.origin);
  63575. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63576. };
  63577. /**
  63578. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  63579. * @param mesh Defines the mesh we want the helper attached to
  63580. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  63581. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  63582. * @param length Defines the length of the ray
  63583. */
  63584. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63585. this._attachedToMesh = mesh;
  63586. var ray = this.ray;
  63587. if (!ray) {
  63588. return;
  63589. }
  63590. if (!ray.direction) {
  63591. ray.direction = BABYLON.Vector3.Zero();
  63592. }
  63593. if (!ray.origin) {
  63594. ray.origin = BABYLON.Vector3.Zero();
  63595. }
  63596. if (length) {
  63597. ray.length = length;
  63598. }
  63599. if (!meshSpaceOrigin) {
  63600. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63601. }
  63602. if (!meshSpaceDirection) {
  63603. // -1 so that this will work with Mesh.lookAt
  63604. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63605. }
  63606. if (!this._meshSpaceDirection) {
  63607. this._meshSpaceDirection = meshSpaceDirection.clone();
  63608. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63609. }
  63610. else {
  63611. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63612. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63613. }
  63614. if (!this._updateToMeshFunction) {
  63615. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63616. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63617. }
  63618. this._updateToMesh();
  63619. };
  63620. /**
  63621. * Detach the ray helper from the mesh it has previously been attached to.
  63622. */
  63623. RayHelper.prototype.detachFromMesh = function () {
  63624. if (this._attachedToMesh) {
  63625. if (this._updateToMeshFunction) {
  63626. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63627. }
  63628. this._attachedToMesh = null;
  63629. this._updateToMeshFunction = null;
  63630. }
  63631. };
  63632. RayHelper.prototype._updateToMesh = function () {
  63633. var ray = this.ray;
  63634. if (!this._attachedToMesh || !ray) {
  63635. return;
  63636. }
  63637. if (this._attachedToMesh._isDisposed) {
  63638. this.detachFromMesh();
  63639. return;
  63640. }
  63641. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63642. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63643. };
  63644. /**
  63645. * Dispose the helper and release its associated resources.
  63646. */
  63647. RayHelper.prototype.dispose = function () {
  63648. this.hide();
  63649. this.detachFromMesh();
  63650. this.ray = null;
  63651. };
  63652. return RayHelper;
  63653. }());
  63654. BABYLON.RayHelper = RayHelper;
  63655. })(BABYLON || (BABYLON = {}));
  63656. //# sourceMappingURL=babylon.rayHelper.js.map
  63657. var BABYLON;
  63658. (function (BABYLON) {
  63659. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  63660. get: function () {
  63661. if (!this._debugLayer) {
  63662. this._debugLayer = new DebugLayer(this);
  63663. }
  63664. return this._debugLayer;
  63665. },
  63666. enumerable: true,
  63667. configurable: true
  63668. });
  63669. /**
  63670. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63671. * what is happening in your scene
  63672. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63673. */
  63674. var DebugLayer = /** @class */ (function () {
  63675. /**
  63676. * Instantiates a new debug layer.
  63677. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63678. * what is happening in your scene
  63679. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63680. * @param scene Defines the scene to inspect
  63681. */
  63682. function DebugLayer(scene) {
  63683. var _this = this;
  63684. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63685. /**
  63686. * Observable triggered when a property is changed through the inspector.
  63687. */
  63688. this.onPropertyChangedObservable = new BABYLON.Observable();
  63689. this._scene = scene;
  63690. this._scene.onDisposeObservable.add(function () {
  63691. // Debug layer
  63692. if (_this._scene._debugLayer) {
  63693. _this._scene._debugLayer.hide();
  63694. }
  63695. });
  63696. }
  63697. /** Creates the inspector window. */
  63698. DebugLayer.prototype._createInspector = function (config) {
  63699. if (config === void 0) { config = {}; }
  63700. var popup = config.popup || false;
  63701. var initialTab = config.initialTab || 0;
  63702. var parentElement = config.parentElement || null;
  63703. if (!this._inspector) {
  63704. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63705. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63706. } // else nothing to do as instance is already created
  63707. };
  63708. /**
  63709. * Get if the inspector is visible or not.
  63710. * @returns true if visible otherwise, false
  63711. */
  63712. DebugLayer.prototype.isVisible = function () {
  63713. if (!this._inspector) {
  63714. return false;
  63715. }
  63716. return true;
  63717. };
  63718. /**
  63719. * Hide the inspector and close its window.
  63720. */
  63721. DebugLayer.prototype.hide = function () {
  63722. if (this._inspector) {
  63723. try {
  63724. this._inspector.dispose();
  63725. }
  63726. catch (e) {
  63727. // If the inspector has been removed directly from the inspector tool
  63728. }
  63729. this.onPropertyChangedObservable.clear();
  63730. this._inspector = null;
  63731. }
  63732. };
  63733. /**
  63734. *
  63735. * Launch the debugLayer.
  63736. *
  63737. * initialTab:
  63738. * | Value | Tab Name |
  63739. * | --- | --- |
  63740. * | 0 | Scene |
  63741. * | 1 | Console |
  63742. * | 2 | Stats |
  63743. * | 3 | Textures |
  63744. * | 4 | Mesh |
  63745. * | 5 | Light |
  63746. * | 6 | Material |
  63747. * | 7 | GLTF |
  63748. * | 8 | GUI |
  63749. * | 9 | Physics |
  63750. * | 10 | Camera |
  63751. * | 11 | Audio |
  63752. *
  63753. * @param config Define the configuration of the inspector
  63754. */
  63755. DebugLayer.prototype.show = function (config) {
  63756. if (config === void 0) { config = {}; }
  63757. if (typeof this.BJSINSPECTOR == 'undefined') {
  63758. // Load inspector and add it to the DOM
  63759. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63760. }
  63761. else {
  63762. // Otherwise creates the inspector
  63763. this._createInspector(config);
  63764. }
  63765. };
  63766. /**
  63767. * Gets the active tab
  63768. * @return the index of the active tab or -1 if the inspector is hidden
  63769. */
  63770. DebugLayer.prototype.getActiveTab = function () {
  63771. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  63772. };
  63773. /**
  63774. * Define the url to get the inspector script from.
  63775. * By default it uses the babylonjs CDN.
  63776. * @ignoreNaming
  63777. */
  63778. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63779. return DebugLayer;
  63780. }());
  63781. BABYLON.DebugLayer = DebugLayer;
  63782. })(BABYLON || (BABYLON = {}));
  63783. //# sourceMappingURL=babylon.debugLayer.js.map
  63784. var BABYLON;
  63785. (function (BABYLON) {
  63786. var Debug;
  63787. (function (Debug) {
  63788. /**
  63789. * Used to show the physics impostor around the specific mesh
  63790. */
  63791. var PhysicsViewer = /** @class */ (function () {
  63792. /**
  63793. * Creates a new PhysicsViewer
  63794. * @param scene defines the hosting scene
  63795. */
  63796. function PhysicsViewer(scene) {
  63797. /** @hidden */
  63798. this._impostors = [];
  63799. /** @hidden */
  63800. this._meshes = [];
  63801. /** @hidden */
  63802. this._numMeshes = 0;
  63803. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63804. var physicEngine = this._scene.getPhysicsEngine();
  63805. if (physicEngine) {
  63806. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  63807. }
  63808. }
  63809. /** @hidden */
  63810. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63811. var plugin = this._physicsEnginePlugin;
  63812. for (var i = 0; i < this._numMeshes; i++) {
  63813. var impostor = this._impostors[i];
  63814. if (!impostor) {
  63815. continue;
  63816. }
  63817. if (impostor.isDisposed) {
  63818. this.hideImpostor(this._impostors[i--]);
  63819. }
  63820. else {
  63821. var mesh = this._meshes[i];
  63822. if (mesh && plugin) {
  63823. plugin.syncMeshWithImpostor(mesh, impostor);
  63824. }
  63825. }
  63826. }
  63827. };
  63828. /**
  63829. * Renders a specified physic impostor
  63830. * @param impostor defines the impostor to render
  63831. */
  63832. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63833. if (!this._scene) {
  63834. return;
  63835. }
  63836. for (var i = 0; i < this._numMeshes; i++) {
  63837. if (this._impostors[i] == impostor) {
  63838. return;
  63839. }
  63840. }
  63841. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63842. if (debugMesh) {
  63843. this._impostors[this._numMeshes] = impostor;
  63844. this._meshes[this._numMeshes] = debugMesh;
  63845. if (this._numMeshes === 0) {
  63846. this._renderFunction = this._updateDebugMeshes.bind(this);
  63847. this._scene.registerBeforeRender(this._renderFunction);
  63848. }
  63849. this._numMeshes++;
  63850. }
  63851. };
  63852. /**
  63853. * Hides a specified physic impostor
  63854. * @param impostor defines the impostor to hide
  63855. */
  63856. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63857. if (!impostor || !this._scene) {
  63858. return;
  63859. }
  63860. var removed = false;
  63861. for (var i = 0; i < this._numMeshes; i++) {
  63862. if (this._impostors[i] == impostor) {
  63863. var mesh = this._meshes[i];
  63864. if (!mesh) {
  63865. continue;
  63866. }
  63867. this._scene.removeMesh(mesh);
  63868. mesh.dispose();
  63869. this._numMeshes--;
  63870. if (this._numMeshes > 0) {
  63871. this._meshes[i] = this._meshes[this._numMeshes];
  63872. this._impostors[i] = this._impostors[this._numMeshes];
  63873. this._meshes[this._numMeshes] = null;
  63874. this._impostors[this._numMeshes] = null;
  63875. }
  63876. else {
  63877. this._meshes[0] = null;
  63878. this._impostors[0] = null;
  63879. }
  63880. removed = true;
  63881. break;
  63882. }
  63883. }
  63884. if (removed && this._numMeshes === 0) {
  63885. this._scene.unregisterBeforeRender(this._renderFunction);
  63886. }
  63887. };
  63888. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63889. if (!this._debugMaterial) {
  63890. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63891. this._debugMaterial.wireframe = true;
  63892. }
  63893. return this._debugMaterial;
  63894. };
  63895. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63896. if (!this._debugBoxMesh) {
  63897. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63898. this._debugBoxMesh.renderingGroupId = 1;
  63899. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63900. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63901. scene.removeMesh(this._debugBoxMesh);
  63902. }
  63903. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63904. };
  63905. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63906. if (!this._debugSphereMesh) {
  63907. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63908. this._debugSphereMesh.renderingGroupId = 1;
  63909. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63910. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63911. scene.removeMesh(this._debugSphereMesh);
  63912. }
  63913. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63914. };
  63915. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63916. var mesh = null;
  63917. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63918. mesh = this._getDebugBoxMesh(scene);
  63919. impostor.getBoxSizeToRef(mesh.scaling);
  63920. }
  63921. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63922. mesh = this._getDebugSphereMesh(scene);
  63923. var radius = impostor.getRadius();
  63924. mesh.scaling.x = radius * 2;
  63925. mesh.scaling.y = radius * 2;
  63926. mesh.scaling.z = radius * 2;
  63927. }
  63928. return mesh;
  63929. };
  63930. /** Releases all resources */
  63931. PhysicsViewer.prototype.dispose = function () {
  63932. for (var i = 0; i < this._numMeshes; i++) {
  63933. this.hideImpostor(this._impostors[i]);
  63934. }
  63935. if (this._debugBoxMesh) {
  63936. this._debugBoxMesh.dispose();
  63937. }
  63938. if (this._debugSphereMesh) {
  63939. this._debugSphereMesh.dispose();
  63940. }
  63941. if (this._debugMaterial) {
  63942. this._debugMaterial.dispose();
  63943. }
  63944. this._impostors.length = 0;
  63945. this._scene = null;
  63946. this._physicsEnginePlugin = null;
  63947. };
  63948. return PhysicsViewer;
  63949. }());
  63950. Debug.PhysicsViewer = PhysicsViewer;
  63951. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63952. })(BABYLON || (BABYLON = {}));
  63953. //# sourceMappingURL=babylon.physicsViewer.js.map
  63954. var BABYLON;
  63955. (function (BABYLON) {
  63956. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  63957. get: function () {
  63958. return this._forceShowBoundingBoxes || false;
  63959. },
  63960. set: function (value) {
  63961. this._forceShowBoundingBoxes = value;
  63962. // Lazyly creates a BB renderer if needed.
  63963. if (value) {
  63964. this.getBoundingBoxRenderer();
  63965. }
  63966. },
  63967. enumerable: true,
  63968. configurable: true
  63969. });
  63970. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  63971. if (!this._boundingBoxRenderer) {
  63972. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  63973. }
  63974. return this._boundingBoxRenderer;
  63975. };
  63976. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  63977. get: function () {
  63978. return this._showBoundingBox || false;
  63979. },
  63980. set: function (value) {
  63981. this._showBoundingBox = value;
  63982. // Lazyly creates a BB renderer if needed.
  63983. if (value) {
  63984. this.getScene().getBoundingBoxRenderer();
  63985. }
  63986. },
  63987. enumerable: true,
  63988. configurable: true
  63989. });
  63990. /**
  63991. * Component responsible of rendering the bounding box of the meshes in a scene.
  63992. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  63993. */
  63994. var BoundingBoxRenderer = /** @class */ (function () {
  63995. /**
  63996. * Instantiates a new bounding box renderer in a scene.
  63997. * @param scene the scene the renderer renders in
  63998. */
  63999. function BoundingBoxRenderer(scene) {
  64000. /**
  64001. * The component name helpfull to identify the component in the list of scene components.
  64002. */
  64003. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  64004. /**
  64005. * Color of the bounding box lines placed in front of an object
  64006. */
  64007. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64008. /**
  64009. * Color of the bounding box lines placed behind an object
  64010. */
  64011. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64012. /**
  64013. * Defines if the renderer should show the back lines or not
  64014. */
  64015. this.showBackLines = true;
  64016. /**
  64017. * @hidden
  64018. */
  64019. this.renderList = new BABYLON.SmartArray(32);
  64020. this._vertexBuffers = {};
  64021. this.scene = scene;
  64022. scene._addComponent(this);
  64023. }
  64024. /**
  64025. * Registers the component in a given scene
  64026. */
  64027. BoundingBoxRenderer.prototype.register = function () {
  64028. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  64029. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  64030. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  64031. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  64032. };
  64033. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  64034. if (mesh.showSubMeshesBoundingBox) {
  64035. var boundingInfo = subMesh.getBoundingInfo();
  64036. if (boundingInfo !== null && boundingInfo !== undefined) {
  64037. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64038. this.renderList.push(boundingInfo.boundingBox);
  64039. }
  64040. }
  64041. };
  64042. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  64043. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  64044. var boundingInfo = sourceMesh.getBoundingInfo();
  64045. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64046. this.renderList.push(boundingInfo.boundingBox);
  64047. }
  64048. };
  64049. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64050. if (this._colorShader) {
  64051. return;
  64052. }
  64053. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  64054. attributes: [BABYLON.VertexBuffer.PositionKind],
  64055. uniforms: ["world", "viewProjection", "color"]
  64056. });
  64057. var engine = this.scene.getEngine();
  64058. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64059. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64060. this._createIndexBuffer();
  64061. };
  64062. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64063. var engine = this.scene.getEngine();
  64064. 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]);
  64065. };
  64066. /**
  64067. * Rebuilds the elements related to this component in case of
  64068. * context lost for instance.
  64069. */
  64070. BoundingBoxRenderer.prototype.rebuild = function () {
  64071. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64072. if (vb) {
  64073. vb._rebuild();
  64074. }
  64075. this._createIndexBuffer();
  64076. };
  64077. /**
  64078. * @hidden
  64079. */
  64080. BoundingBoxRenderer.prototype.reset = function () {
  64081. this.renderList.reset();
  64082. };
  64083. /**
  64084. * Render the bounding boxes of a specific rendering group
  64085. * @param renderingGroupId defines the rendering group to render
  64086. */
  64087. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  64088. if (this.renderList.length === 0) {
  64089. return;
  64090. }
  64091. this._prepareRessources();
  64092. if (!this._colorShader.isReady()) {
  64093. return;
  64094. }
  64095. var engine = this.scene.getEngine();
  64096. engine.setDepthWrite(false);
  64097. this._colorShader._preBind();
  64098. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64099. var boundingBox = this.renderList.data[boundingBoxIndex];
  64100. if (boundingBox._tag !== renderingGroupId) {
  64101. continue;
  64102. }
  64103. var min = boundingBox.minimum;
  64104. var max = boundingBox.maximum;
  64105. var diff = max.subtract(min);
  64106. var median = min.add(diff.scale(0.5));
  64107. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64108. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64109. .multiply(boundingBox.getWorldMatrix());
  64110. // VBOs
  64111. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64112. if (this.showBackLines) {
  64113. // Back
  64114. engine.setDepthFunctionToGreaterOrEqual();
  64115. this.scene.resetCachedMaterial();
  64116. this._colorShader.setColor4("color", this.backColor.toColor4());
  64117. this._colorShader.bind(worldMatrix);
  64118. // Draw order
  64119. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64120. }
  64121. // Front
  64122. engine.setDepthFunctionToLess();
  64123. this.scene.resetCachedMaterial();
  64124. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64125. this._colorShader.bind(worldMatrix);
  64126. // Draw order
  64127. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64128. }
  64129. this._colorShader.unbind();
  64130. engine.setDepthFunctionToLessOrEqual();
  64131. engine.setDepthWrite(true);
  64132. };
  64133. /**
  64134. * In case of occlusion queries, we can render the occlusion bounding box through this method
  64135. * @param mesh Define the mesh to render the occlusion bounding box for
  64136. */
  64137. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64138. this._prepareRessources();
  64139. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  64140. return;
  64141. }
  64142. var engine = this.scene.getEngine();
  64143. engine.setDepthWrite(false);
  64144. engine.setColorWrite(false);
  64145. this._colorShader._preBind();
  64146. var boundingBox = mesh._boundingInfo.boundingBox;
  64147. var min = boundingBox.minimum;
  64148. var max = boundingBox.maximum;
  64149. var diff = max.subtract(min);
  64150. var median = min.add(diff.scale(0.5));
  64151. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64152. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64153. .multiply(boundingBox.getWorldMatrix());
  64154. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64155. engine.setDepthFunctionToLess();
  64156. this.scene.resetCachedMaterial();
  64157. this._colorShader.bind(worldMatrix);
  64158. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64159. this._colorShader.unbind();
  64160. engine.setDepthFunctionToLessOrEqual();
  64161. engine.setDepthWrite(true);
  64162. engine.setColorWrite(true);
  64163. };
  64164. /**
  64165. * Dispose and release the resources attached to this renderer.
  64166. */
  64167. BoundingBoxRenderer.prototype.dispose = function () {
  64168. if (!this._colorShader) {
  64169. return;
  64170. }
  64171. this.renderList.dispose();
  64172. this._colorShader.dispose();
  64173. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64174. if (buffer) {
  64175. buffer.dispose();
  64176. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64177. }
  64178. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  64179. };
  64180. return BoundingBoxRenderer;
  64181. }());
  64182. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64183. })(BABYLON || (BABYLON = {}));
  64184. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64185. var BABYLON;
  64186. (function (BABYLON) {
  64187. BABYLON.Engine.prototype.createTransformFeedback = function () {
  64188. return this._gl.createTransformFeedback();
  64189. };
  64190. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  64191. this._gl.deleteTransformFeedback(value);
  64192. };
  64193. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  64194. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  64195. };
  64196. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  64197. if (usePoints === void 0) { usePoints = true; }
  64198. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  64199. };
  64200. BABYLON.Engine.prototype.endTransformFeedback = function () {
  64201. this._gl.endTransformFeedback();
  64202. };
  64203. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  64204. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  64205. };
  64206. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  64207. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  64208. };
  64209. })(BABYLON || (BABYLON = {}));
  64210. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  64211. var BABYLON;
  64212. (function (BABYLON) {
  64213. /**
  64214. * This represents a GPU particle system in Babylon
  64215. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  64216. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  64217. */
  64218. var GPUParticleSystem = /** @class */ (function (_super) {
  64219. __extends(GPUParticleSystem, _super);
  64220. /**
  64221. * Instantiates a GPU particle system.
  64222. * 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.
  64223. * @param name The name of the particle system
  64224. * @param options The options used to create the system
  64225. * @param scene The scene the particle system belongs to
  64226. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  64227. */
  64228. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  64229. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  64230. var _this = _super.call(this, name) || this;
  64231. /**
  64232. * The layer mask we are rendering the particles through.
  64233. */
  64234. _this.layerMask = 0x0FFFFFFF;
  64235. _this._accumulatedCount = 0;
  64236. _this._targetIndex = 0;
  64237. _this._currentRenderId = -1;
  64238. _this._started = false;
  64239. _this._stopped = false;
  64240. _this._timeDelta = 0;
  64241. _this._attributesStrideSize = 21;
  64242. _this._actualFrame = 0;
  64243. _this._rawTextureWidth = 256;
  64244. /**
  64245. * An event triggered when the system is disposed.
  64246. */
  64247. _this.onDisposeObservable = new BABYLON.Observable();
  64248. /**
  64249. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  64250. * to override the particles.
  64251. */
  64252. _this.forceDepthWrite = false;
  64253. _this._preWarmDone = false;
  64254. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64255. // Setup the default processing configuration to the scene.
  64256. _this._attachImageProcessingConfiguration(null);
  64257. _this._engine = _this._scene.getEngine();
  64258. if (!options.randomTextureSize) {
  64259. delete options.randomTextureSize;
  64260. }
  64261. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  64262. var optionsAsNumber = options;
  64263. if (isFinite(optionsAsNumber)) {
  64264. fullOptions.capacity = optionsAsNumber;
  64265. }
  64266. _this._capacity = fullOptions.capacity;
  64267. _this._activeCount = fullOptions.capacity;
  64268. _this._currentActiveCount = 0;
  64269. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  64270. _this._scene.particleSystems.push(_this);
  64271. _this._updateEffectOptions = {
  64272. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  64273. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  64274. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  64275. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  64276. uniformBuffersNames: [],
  64277. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  64278. defines: "",
  64279. fallbacks: null,
  64280. onCompiled: null,
  64281. onError: null,
  64282. indexParameters: null,
  64283. maxSimultaneousLights: 0,
  64284. transformFeedbackVaryings: []
  64285. };
  64286. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  64287. // Random data
  64288. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  64289. var d = [];
  64290. for (var i = 0; i < maxTextureSize; ++i) {
  64291. d.push(Math.random());
  64292. d.push(Math.random());
  64293. d.push(Math.random());
  64294. d.push(Math.random());
  64295. }
  64296. _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);
  64297. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64298. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64299. d = [];
  64300. for (var i = 0; i < maxTextureSize; ++i) {
  64301. d.push(Math.random());
  64302. d.push(Math.random());
  64303. d.push(Math.random());
  64304. d.push(Math.random());
  64305. }
  64306. _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);
  64307. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64308. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64309. _this._randomTextureSize = maxTextureSize;
  64310. return _this;
  64311. }
  64312. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  64313. /**
  64314. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  64315. */
  64316. get: function () {
  64317. if (!BABYLON.Engine.LastCreatedEngine) {
  64318. return false;
  64319. }
  64320. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  64321. },
  64322. enumerable: true,
  64323. configurable: true
  64324. });
  64325. /**
  64326. * Gets the maximum number of particles active at the same time.
  64327. * @returns The max number of active particles.
  64328. */
  64329. GPUParticleSystem.prototype.getCapacity = function () {
  64330. return this._capacity;
  64331. };
  64332. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  64333. /**
  64334. * Gets or set the number of active particles
  64335. */
  64336. get: function () {
  64337. return this._activeCount;
  64338. },
  64339. set: function (value) {
  64340. this._activeCount = Math.min(value, this._capacity);
  64341. },
  64342. enumerable: true,
  64343. configurable: true
  64344. });
  64345. /**
  64346. * Is this system ready to be used/rendered
  64347. * @return true if the system is ready
  64348. */
  64349. GPUParticleSystem.prototype.isReady = function () {
  64350. if (!this._updateEffect) {
  64351. this._recreateUpdateEffect();
  64352. this._recreateRenderEffect();
  64353. return false;
  64354. }
  64355. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  64356. return false;
  64357. }
  64358. return true;
  64359. };
  64360. /**
  64361. * Gets if the system has been started. (Note: this will still be true after stop is called)
  64362. * @returns True if it has been started, otherwise false.
  64363. */
  64364. GPUParticleSystem.prototype.isStarted = function () {
  64365. return this._started;
  64366. };
  64367. /**
  64368. * Starts the particle system and begins to emit
  64369. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  64370. */
  64371. GPUParticleSystem.prototype.start = function (delay) {
  64372. var _this = this;
  64373. if (delay === void 0) { delay = this.startDelay; }
  64374. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  64375. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  64376. }
  64377. if (delay) {
  64378. setTimeout(function () {
  64379. _this.start(0);
  64380. }, delay);
  64381. return;
  64382. }
  64383. this._started = true;
  64384. this._stopped = false;
  64385. this._preWarmDone = false;
  64386. // Animations
  64387. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  64388. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  64389. }
  64390. };
  64391. /**
  64392. * Stops the particle system.
  64393. */
  64394. GPUParticleSystem.prototype.stop = function () {
  64395. this._stopped = true;
  64396. };
  64397. /**
  64398. * Remove all active particles
  64399. */
  64400. GPUParticleSystem.prototype.reset = function () {
  64401. this._releaseBuffers();
  64402. this._releaseVAOs();
  64403. this._currentActiveCount = 0;
  64404. this._targetIndex = 0;
  64405. };
  64406. /**
  64407. * Returns the string "GPUParticleSystem"
  64408. * @returns a string containing the class name
  64409. */
  64410. GPUParticleSystem.prototype.getClassName = function () {
  64411. return "GPUParticleSystem";
  64412. };
  64413. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  64414. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  64415. this._releaseBuffers();
  64416. return this;
  64417. };
  64418. /**
  64419. * Adds a new color gradient
  64420. * @param gradient defines the gradient to use (between 0 and 1)
  64421. * @param color1 defines the color to affect to the specified gradient
  64422. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  64423. * @returns the current particle system
  64424. */
  64425. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  64426. if (!this._colorGradients) {
  64427. this._colorGradients = [];
  64428. }
  64429. var colorGradient = new BABYLON.ColorGradient();
  64430. colorGradient.gradient = gradient;
  64431. colorGradient.color1 = color1;
  64432. this._colorGradients.push(colorGradient);
  64433. this._colorGradients.sort(function (a, b) {
  64434. if (a.gradient < b.gradient) {
  64435. return -1;
  64436. }
  64437. else if (a.gradient > b.gradient) {
  64438. return 1;
  64439. }
  64440. return 0;
  64441. });
  64442. if (this._colorGradientsTexture) {
  64443. this._colorGradientsTexture.dispose();
  64444. this._colorGradientsTexture = null;
  64445. }
  64446. this._releaseBuffers();
  64447. return this;
  64448. };
  64449. /**
  64450. * Remove a specific color gradient
  64451. * @param gradient defines the gradient to remove
  64452. * @returns the current particle system
  64453. */
  64454. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  64455. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  64456. this._colorGradientsTexture = null;
  64457. return this;
  64458. };
  64459. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  64460. var valueGradient = new BABYLON.FactorGradient();
  64461. valueGradient.gradient = gradient;
  64462. valueGradient.factor1 = factor;
  64463. factorGradients.push(valueGradient);
  64464. factorGradients.sort(function (a, b) {
  64465. if (a.gradient < b.gradient) {
  64466. return -1;
  64467. }
  64468. else if (a.gradient > b.gradient) {
  64469. return 1;
  64470. }
  64471. return 0;
  64472. });
  64473. this._releaseBuffers();
  64474. };
  64475. /**
  64476. * Adds a new size gradient
  64477. * @param gradient defines the gradient to use (between 0 and 1)
  64478. * @param factor defines the size factor to affect to the specified gradient
  64479. * @returns the current particle system
  64480. */
  64481. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  64482. if (!this._sizeGradients) {
  64483. this._sizeGradients = [];
  64484. }
  64485. this._addFactorGradient(this._sizeGradients, gradient, factor);
  64486. if (this._sizeGradientsTexture) {
  64487. this._sizeGradientsTexture.dispose();
  64488. this._sizeGradientsTexture = null;
  64489. }
  64490. this._releaseBuffers();
  64491. return this;
  64492. };
  64493. /**
  64494. * Remove a specific size gradient
  64495. * @param gradient defines the gradient to remove
  64496. * @returns the current particle system
  64497. */
  64498. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  64499. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  64500. this._sizeGradientsTexture = null;
  64501. return this;
  64502. };
  64503. /**
  64504. * Adds a new angular speed gradient
  64505. * @param gradient defines the gradient to use (between 0 and 1)
  64506. * @param factor defines the angular speed to affect to the specified gradient
  64507. * @returns the current particle system
  64508. */
  64509. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  64510. if (!this._angularSpeedGradients) {
  64511. this._angularSpeedGradients = [];
  64512. }
  64513. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  64514. if (this._angularSpeedGradientsTexture) {
  64515. this._angularSpeedGradientsTexture.dispose();
  64516. this._angularSpeedGradientsTexture = null;
  64517. }
  64518. this._releaseBuffers();
  64519. return this;
  64520. };
  64521. /**
  64522. * Remove a specific angular speed gradient
  64523. * @param gradient defines the gradient to remove
  64524. * @returns the current particle system
  64525. */
  64526. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  64527. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  64528. this._angularSpeedGradientsTexture = null;
  64529. return this;
  64530. };
  64531. /**
  64532. * Adds a new velocity gradient
  64533. * @param gradient defines the gradient to use (between 0 and 1)
  64534. * @param factor defines the velocity to affect to the specified gradient
  64535. * @returns the current particle system
  64536. */
  64537. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  64538. if (!this._velocityGradients) {
  64539. this._velocityGradients = [];
  64540. }
  64541. this._addFactorGradient(this._velocityGradients, gradient, factor);
  64542. if (this._velocityGradientsTexture) {
  64543. this._velocityGradientsTexture.dispose();
  64544. this._velocityGradientsTexture = null;
  64545. }
  64546. this._releaseBuffers();
  64547. return this;
  64548. };
  64549. /**
  64550. * Remove a specific velocity gradient
  64551. * @param gradient defines the gradient to remove
  64552. * @returns the current particle system
  64553. */
  64554. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  64555. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  64556. this._velocityGradientsTexture = null;
  64557. return this;
  64558. };
  64559. /**
  64560. * Adds a new limit velocity gradient
  64561. * @param gradient defines the gradient to use (between 0 and 1)
  64562. * @param factor defines the limit velocity value to affect to the specified gradient
  64563. * @returns the current particle system
  64564. */
  64565. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  64566. if (!this._limitVelocityGradients) {
  64567. this._limitVelocityGradients = [];
  64568. }
  64569. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  64570. if (this._limitVelocityGradientsTexture) {
  64571. this._limitVelocityGradientsTexture.dispose();
  64572. this._limitVelocityGradientsTexture = null;
  64573. }
  64574. this._releaseBuffers();
  64575. return this;
  64576. };
  64577. /**
  64578. * Remove a specific limit velocity gradient
  64579. * @param gradient defines the gradient to remove
  64580. * @returns the current particle system
  64581. */
  64582. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  64583. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  64584. this._limitVelocityGradientsTexture = null;
  64585. return this;
  64586. };
  64587. /**
  64588. * Adds a new drag gradient
  64589. * @param gradient defines the gradient to use (between 0 and 1)
  64590. * @param factor defines the drag value to affect to the specified gradient
  64591. * @returns the current particle system
  64592. */
  64593. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  64594. if (!this._dragGradients) {
  64595. this._dragGradients = [];
  64596. }
  64597. this._addFactorGradient(this._dragGradients, gradient, factor);
  64598. if (this._dragGradientsTexture) {
  64599. this._dragGradientsTexture.dispose();
  64600. this._dragGradientsTexture = null;
  64601. }
  64602. this._releaseBuffers();
  64603. return this;
  64604. };
  64605. /**
  64606. * Remove a specific drag gradient
  64607. * @param gradient defines the gradient to remove
  64608. * @returns the current particle system
  64609. */
  64610. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  64611. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  64612. this._dragGradientsTexture = null;
  64613. return this;
  64614. };
  64615. /**
  64616. * Not supported by GPUParticleSystem
  64617. * @param gradient defines the gradient to use (between 0 and 1)
  64618. * @param factor defines the emit rate value to affect to the specified gradient
  64619. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64620. * @returns the current particle system
  64621. */
  64622. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  64623. // Do nothing as emit rate is not supported by GPUParticleSystem
  64624. return this;
  64625. };
  64626. /**
  64627. * Not supported by GPUParticleSystem
  64628. * @param gradient defines the gradient to remove
  64629. * @returns the current particle system
  64630. */
  64631. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  64632. // Do nothing as emit rate is not supported by GPUParticleSystem
  64633. return this;
  64634. };
  64635. /**
  64636. * Not supported by GPUParticleSystem
  64637. * @param gradient defines the gradient to use (between 0 and 1)
  64638. * @param factor defines the start size value to affect to the specified gradient
  64639. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64640. * @returns the current particle system
  64641. */
  64642. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  64643. // Do nothing as start size is not supported by GPUParticleSystem
  64644. return this;
  64645. };
  64646. /**
  64647. * Not supported by GPUParticleSystem
  64648. * @param gradient defines the gradient to remove
  64649. * @returns the current particle system
  64650. */
  64651. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  64652. // Do nothing as start size is not supported by GPUParticleSystem
  64653. return this;
  64654. };
  64655. /**
  64656. * Not supported by GPUParticleSystem
  64657. * @param gradient defines the gradient to use (between 0 and 1)
  64658. * @param min defines the color remap minimal range
  64659. * @param max defines the color remap maximal range
  64660. * @returns the current particle system
  64661. */
  64662. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  64663. // Do nothing as start size is not supported by GPUParticleSystem
  64664. return this;
  64665. };
  64666. /**
  64667. * Not supported by GPUParticleSystem
  64668. * @param gradient defines the gradient to remove
  64669. * @returns the current particle system
  64670. */
  64671. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  64672. // Do nothing as start size is not supported by GPUParticleSystem
  64673. return this;
  64674. };
  64675. /**
  64676. * Not supported by GPUParticleSystem
  64677. * @param gradient defines the gradient to use (between 0 and 1)
  64678. * @param min defines the alpha remap minimal range
  64679. * @param max defines the alpha remap maximal range
  64680. * @returns the current particle system
  64681. */
  64682. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  64683. // Do nothing as start size is not supported by GPUParticleSystem
  64684. return this;
  64685. };
  64686. /**
  64687. * Not supported by GPUParticleSystem
  64688. * @param gradient defines the gradient to remove
  64689. * @returns the current particle system
  64690. */
  64691. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  64692. // Do nothing as start size is not supported by GPUParticleSystem
  64693. return this;
  64694. };
  64695. /**
  64696. * Not supported by GPUParticleSystem
  64697. * @param gradient defines the gradient to use (between 0 and 1)
  64698. * @param color defines the color to affect to the specified gradient
  64699. * @returns the current particle system
  64700. */
  64701. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  64702. //Not supported by GPUParticleSystem
  64703. return this;
  64704. };
  64705. /**
  64706. * Not supported by GPUParticleSystem
  64707. * @param gradient defines the gradient to remove
  64708. * @returns the current particle system
  64709. */
  64710. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  64711. //Not supported by GPUParticleSystem
  64712. return this;
  64713. };
  64714. /**
  64715. * Not supported by GPUParticleSystem
  64716. * @returns the list of ramp gradients
  64717. */
  64718. GPUParticleSystem.prototype.getRampGradients = function () {
  64719. return null;
  64720. };
  64721. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  64722. /**
  64723. * Not supported by GPUParticleSystem
  64724. * Gets or sets a boolean indicating that ramp gradients must be used
  64725. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  64726. */
  64727. get: function () {
  64728. //Not supported by GPUParticleSystem
  64729. return false;
  64730. },
  64731. set: function (value) {
  64732. //Not supported by GPUParticleSystem
  64733. },
  64734. enumerable: true,
  64735. configurable: true
  64736. });
  64737. /**
  64738. * Not supported by GPUParticleSystem
  64739. * @param gradient defines the gradient to use (between 0 and 1)
  64740. * @param factor defines the life time factor to affect to the specified gradient
  64741. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64742. * @returns the current particle system
  64743. */
  64744. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  64745. //Not supported by GPUParticleSystem
  64746. return this;
  64747. };
  64748. /**
  64749. * Not supported by GPUParticleSystem
  64750. * @param gradient defines the gradient to remove
  64751. * @returns the current particle system
  64752. */
  64753. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  64754. //Not supported by GPUParticleSystem
  64755. return this;
  64756. };
  64757. GPUParticleSystem.prototype._reset = function () {
  64758. this._releaseBuffers();
  64759. };
  64760. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  64761. var updateVertexBuffers = {};
  64762. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  64763. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  64764. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  64765. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  64766. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  64767. var offset = 12;
  64768. if (!this._colorGradientsTexture) {
  64769. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  64770. offset += 4;
  64771. }
  64772. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  64773. offset += 3;
  64774. if (!this._isBillboardBased) {
  64775. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  64776. offset += 3;
  64777. }
  64778. if (this._angularSpeedGradientsTexture) {
  64779. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  64780. offset += 1;
  64781. }
  64782. else {
  64783. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  64784. offset += 2;
  64785. }
  64786. if (this._isAnimationSheetEnabled) {
  64787. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  64788. offset += 1;
  64789. if (this.spriteRandomStartCell) {
  64790. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  64791. offset += 1;
  64792. }
  64793. }
  64794. if (this.noiseTexture) {
  64795. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  64796. offset += 3;
  64797. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  64798. offset += 3;
  64799. }
  64800. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  64801. this._engine.bindArrayBuffer(null);
  64802. return vao;
  64803. };
  64804. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  64805. var renderVertexBuffers = {};
  64806. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  64807. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  64808. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  64809. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  64810. var offset = 12;
  64811. if (!this._colorGradientsTexture) {
  64812. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  64813. offset += 4;
  64814. }
  64815. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  64816. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  64817. }
  64818. offset += 3; // Direction
  64819. if (!this._isBillboardBased) {
  64820. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  64821. offset += 3;
  64822. }
  64823. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  64824. if (this._angularSpeedGradientsTexture) {
  64825. offset++;
  64826. }
  64827. else {
  64828. offset += 2;
  64829. }
  64830. if (this._isAnimationSheetEnabled) {
  64831. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  64832. offset += 1;
  64833. if (this.spriteRandomStartCell) {
  64834. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  64835. offset += 1;
  64836. }
  64837. }
  64838. if (this.noiseTexture) {
  64839. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  64840. offset += 3;
  64841. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  64842. offset += 3;
  64843. }
  64844. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  64845. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  64846. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  64847. this._engine.bindArrayBuffer(null);
  64848. return vao;
  64849. };
  64850. GPUParticleSystem.prototype._initialize = function (force) {
  64851. if (force === void 0) { force = false; }
  64852. if (this._buffer0 && !force) {
  64853. return;
  64854. }
  64855. var engine = this._scene.getEngine();
  64856. var data = new Array();
  64857. if (!this.isBillboardBased) {
  64858. this._attributesStrideSize += 3;
  64859. }
  64860. if (this._colorGradientsTexture) {
  64861. this._attributesStrideSize -= 4;
  64862. }
  64863. if (this._angularSpeedGradientsTexture) {
  64864. this._attributesStrideSize -= 1;
  64865. }
  64866. if (this._isAnimationSheetEnabled) {
  64867. this._attributesStrideSize += 1;
  64868. if (this.spriteRandomStartCell) {
  64869. this._attributesStrideSize += 1;
  64870. }
  64871. }
  64872. if (this.noiseTexture) {
  64873. this._attributesStrideSize += 6;
  64874. }
  64875. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  64876. // position
  64877. data.push(0.0);
  64878. data.push(0.0);
  64879. data.push(0.0);
  64880. // Age and life
  64881. data.push(0.0); // create the particle as a dead one to create a new one at start
  64882. data.push(0.0);
  64883. // Seed
  64884. data.push(Math.random());
  64885. data.push(Math.random());
  64886. data.push(Math.random());
  64887. data.push(Math.random());
  64888. // Size
  64889. data.push(0.0);
  64890. data.push(0.0);
  64891. data.push(0.0);
  64892. if (!this._colorGradientsTexture) {
  64893. // color
  64894. data.push(0.0);
  64895. data.push(0.0);
  64896. data.push(0.0);
  64897. data.push(0.0);
  64898. }
  64899. // direction
  64900. data.push(0.0);
  64901. data.push(0.0);
  64902. data.push(0.0);
  64903. if (!this.isBillboardBased) {
  64904. // initialDirection
  64905. data.push(0.0);
  64906. data.push(0.0);
  64907. data.push(0.0);
  64908. }
  64909. // angle
  64910. data.push(0.0);
  64911. if (!this._angularSpeedGradientsTexture) {
  64912. data.push(0.0);
  64913. }
  64914. if (this._isAnimationSheetEnabled) {
  64915. data.push(0.0);
  64916. if (this.spriteRandomStartCell) {
  64917. data.push(0.0);
  64918. }
  64919. }
  64920. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  64921. data.push(Math.random());
  64922. data.push(Math.random());
  64923. data.push(Math.random());
  64924. data.push(Math.random());
  64925. data.push(Math.random());
  64926. data.push(Math.random());
  64927. }
  64928. }
  64929. // Sprite data
  64930. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  64931. -0.5, 0.5, 0, 1,
  64932. -0.5, -0.5, 0, 0,
  64933. 0.5, -0.5, 1, 0]);
  64934. // Buffers
  64935. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64936. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64937. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  64938. // Update VAO
  64939. this._updateVAO = [];
  64940. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  64941. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  64942. // Render VAO
  64943. this._renderVAO = [];
  64944. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  64945. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  64946. // Links
  64947. this._sourceBuffer = this._buffer0;
  64948. this._targetBuffer = this._buffer1;
  64949. };
  64950. /** @hidden */
  64951. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  64952. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  64953. if (this._isBillboardBased) {
  64954. defines += "\n#define BILLBOARD";
  64955. }
  64956. if (this._colorGradientsTexture) {
  64957. defines += "\n#define COLORGRADIENTS";
  64958. }
  64959. if (this._sizeGradientsTexture) {
  64960. defines += "\n#define SIZEGRADIENTS";
  64961. }
  64962. if (this._angularSpeedGradientsTexture) {
  64963. defines += "\n#define ANGULARSPEEDGRADIENTS";
  64964. }
  64965. if (this._velocityGradientsTexture) {
  64966. defines += "\n#define VELOCITYGRADIENTS";
  64967. }
  64968. if (this._limitVelocityGradientsTexture) {
  64969. defines += "\n#define LIMITVELOCITYGRADIENTS";
  64970. }
  64971. if (this._dragGradientsTexture) {
  64972. defines += "\n#define DRAGGRADIENTS";
  64973. }
  64974. if (this.isAnimationSheetEnabled) {
  64975. defines += "\n#define ANIMATESHEET";
  64976. if (this.spriteRandomStartCell) {
  64977. defines += "\n#define ANIMATESHEETRANDOMSTART";
  64978. }
  64979. }
  64980. if (this.noiseTexture) {
  64981. defines += "\n#define NOISE";
  64982. }
  64983. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  64984. return;
  64985. }
  64986. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  64987. if (!this._colorGradientsTexture) {
  64988. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  64989. }
  64990. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  64991. if (!this._isBillboardBased) {
  64992. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  64993. }
  64994. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  64995. if (this.isAnimationSheetEnabled) {
  64996. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  64997. if (this.spriteRandomStartCell) {
  64998. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  64999. }
  65000. }
  65001. if (this.noiseTexture) {
  65002. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  65003. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  65004. }
  65005. this._updateEffectOptions.defines = defines;
  65006. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  65007. };
  65008. /** @hidden */
  65009. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  65010. var defines = "";
  65011. if (this._scene.clipPlane) {
  65012. defines = "\n#define CLIPPLANE";
  65013. }
  65014. if (this._scene.clipPlane2) {
  65015. defines = "\n#define CLIPPLANE2";
  65016. }
  65017. if (this._scene.clipPlane3) {
  65018. defines = "\n#define CLIPPLANE3";
  65019. }
  65020. if (this._scene.clipPlane4) {
  65021. defines = "\n#define CLIPPLANE4";
  65022. }
  65023. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  65024. defines = "\n#define BLENDMULTIPLYMODE";
  65025. }
  65026. if (this._isBillboardBased) {
  65027. defines += "\n#define BILLBOARD";
  65028. switch (this.billboardMode) {
  65029. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  65030. defines += "\n#define BILLBOARDY";
  65031. break;
  65032. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  65033. defines += "\n#define BILLBOARDSTRETCHED";
  65034. break;
  65035. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  65036. default:
  65037. break;
  65038. }
  65039. }
  65040. if (this._colorGradientsTexture) {
  65041. defines += "\n#define COLORGRADIENTS";
  65042. }
  65043. if (this.isAnimationSheetEnabled) {
  65044. defines += "\n#define ANIMATESHEET";
  65045. }
  65046. if (this._imageProcessingConfiguration) {
  65047. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  65048. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  65049. }
  65050. if (this._renderEffect && this._renderEffect.defines === defines) {
  65051. return;
  65052. }
  65053. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  65054. var samplers = ["textureSampler", "colorGradientSampler"];
  65055. if (BABYLON.ImageProcessingConfiguration) {
  65056. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  65057. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  65058. }
  65059. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  65060. };
  65061. /**
  65062. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  65063. * @param preWarm defines if we are in the pre-warmimg phase
  65064. */
  65065. GPUParticleSystem.prototype.animate = function (preWarm) {
  65066. if (preWarm === void 0) { preWarm = false; }
  65067. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  65068. this._actualFrame += this._timeDelta;
  65069. if (!this._stopped) {
  65070. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  65071. this.stop();
  65072. }
  65073. }
  65074. };
  65075. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  65076. var texture = this[textureName];
  65077. if (!factorGradients || !factorGradients.length || texture) {
  65078. return;
  65079. }
  65080. var data = new Float32Array(this._rawTextureWidth);
  65081. for (var x = 0; x < this._rawTextureWidth; x++) {
  65082. var ratio = x / this._rawTextureWidth;
  65083. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  65084. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  65085. });
  65086. }
  65087. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65088. };
  65089. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  65090. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  65091. };
  65092. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  65093. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  65094. };
  65095. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  65096. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  65097. };
  65098. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  65099. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  65100. };
  65101. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  65102. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  65103. };
  65104. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  65105. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  65106. return;
  65107. }
  65108. var data = new Uint8Array(this._rawTextureWidth * 4);
  65109. var tmpColor = BABYLON.Tmp.Color4[0];
  65110. for (var x = 0; x < this._rawTextureWidth; x++) {
  65111. var ratio = x / this._rawTextureWidth;
  65112. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  65113. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  65114. data[x * 4] = tmpColor.r * 255;
  65115. data[x * 4 + 1] = tmpColor.g * 255;
  65116. data[x * 4 + 2] = tmpColor.b * 255;
  65117. data[x * 4 + 3] = tmpColor.a * 255;
  65118. });
  65119. }
  65120. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65121. };
  65122. /**
  65123. * Renders the particle system in its current state
  65124. * @param preWarm defines if the system should only update the particles but not render them
  65125. * @returns the current number of particles
  65126. */
  65127. GPUParticleSystem.prototype.render = function (preWarm) {
  65128. if (preWarm === void 0) { preWarm = false; }
  65129. if (!this._started) {
  65130. return 0;
  65131. }
  65132. this._createColorGradientTexture();
  65133. this._createSizeGradientTexture();
  65134. this._createAngularSpeedGradientTexture();
  65135. this._createVelocityGradientTexture();
  65136. this._createLimitVelocityGradientTexture();
  65137. this._createDragGradientTexture();
  65138. this._recreateUpdateEffect();
  65139. this._recreateRenderEffect();
  65140. if (!this.isReady()) {
  65141. return 0;
  65142. }
  65143. if (!preWarm) {
  65144. if (!this._preWarmDone && this.preWarmCycles) {
  65145. for (var index = 0; index < this.preWarmCycles; index++) {
  65146. this.animate(true);
  65147. this.render(true);
  65148. }
  65149. this._preWarmDone = true;
  65150. }
  65151. if (this._currentRenderId === this._scene.getRenderId()) {
  65152. return 0;
  65153. }
  65154. this._currentRenderId = this._scene.getRenderId();
  65155. }
  65156. // Get everything ready to render
  65157. this._initialize();
  65158. this._accumulatedCount += this.emitRate * this._timeDelta;
  65159. if (this._accumulatedCount > 1) {
  65160. var intPart = this._accumulatedCount | 0;
  65161. this._accumulatedCount -= intPart;
  65162. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  65163. }
  65164. if (!this._currentActiveCount) {
  65165. return 0;
  65166. }
  65167. // Enable update effect
  65168. this._engine.enableEffect(this._updateEffect);
  65169. this._engine.setState(false);
  65170. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  65171. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  65172. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  65173. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  65174. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  65175. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  65176. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  65177. if (!this._colorGradientsTexture) {
  65178. this._updateEffect.setDirectColor4("color1", this.color1);
  65179. this._updateEffect.setDirectColor4("color2", this.color2);
  65180. }
  65181. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  65182. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  65183. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  65184. this._updateEffect.setVector3("gravity", this.gravity);
  65185. if (this._sizeGradientsTexture) {
  65186. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  65187. }
  65188. if (this._angularSpeedGradientsTexture) {
  65189. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  65190. }
  65191. if (this._velocityGradientsTexture) {
  65192. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  65193. }
  65194. if (this._limitVelocityGradientsTexture) {
  65195. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  65196. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  65197. }
  65198. if (this._dragGradientsTexture) {
  65199. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  65200. }
  65201. if (this.particleEmitterType) {
  65202. this.particleEmitterType.applyToShader(this._updateEffect);
  65203. }
  65204. if (this._isAnimationSheetEnabled) {
  65205. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  65206. }
  65207. if (this.noiseTexture) {
  65208. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  65209. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  65210. }
  65211. var emitterWM;
  65212. if (this.emitter.position) {
  65213. var emitterMesh = this.emitter;
  65214. emitterWM = emitterMesh.getWorldMatrix();
  65215. }
  65216. else {
  65217. var emitterPosition = this.emitter;
  65218. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  65219. }
  65220. this._updateEffect.setMatrix("emitterWM", emitterWM);
  65221. // Bind source VAO
  65222. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  65223. // Update
  65224. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  65225. this._engine.setRasterizerState(false);
  65226. this._engine.beginTransformFeedback(true);
  65227. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  65228. this._engine.endTransformFeedback();
  65229. this._engine.setRasterizerState(true);
  65230. this._engine.bindTransformFeedbackBuffer(null);
  65231. if (!preWarm) {
  65232. // Enable render effect
  65233. this._engine.enableEffect(this._renderEffect);
  65234. var viewMatrix = this._scene.getViewMatrix();
  65235. this._renderEffect.setMatrix("view", viewMatrix);
  65236. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65237. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65238. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65239. if (this._colorGradientsTexture) {
  65240. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65241. }
  65242. else {
  65243. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  65244. }
  65245. if (this._isAnimationSheetEnabled && this.particleTexture) {
  65246. var baseSize = this.particleTexture.getBaseSize();
  65247. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  65248. }
  65249. if (this._isBillboardBased) {
  65250. var camera = this._scene.activeCamera;
  65251. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  65252. }
  65253. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  65254. var invView = viewMatrix.clone();
  65255. invView.invert();
  65256. this._renderEffect.setMatrix("invView", invView);
  65257. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  65258. }
  65259. // image processing
  65260. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  65261. this._imageProcessingConfiguration.bind(this._renderEffect);
  65262. }
  65263. // Draw order
  65264. switch (this.blendMode) {
  65265. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  65266. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  65267. break;
  65268. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  65269. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  65270. break;
  65271. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  65272. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65273. break;
  65274. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  65275. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  65276. break;
  65277. }
  65278. if (this.forceDepthWrite) {
  65279. this._engine.setDepthWrite(true);
  65280. }
  65281. // Bind source VAO
  65282. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  65283. // Render
  65284. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  65285. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65286. }
  65287. // Switch VAOs
  65288. this._targetIndex++;
  65289. if (this._targetIndex === 2) {
  65290. this._targetIndex = 0;
  65291. }
  65292. // Switch buffers
  65293. var tmpBuffer = this._sourceBuffer;
  65294. this._sourceBuffer = this._targetBuffer;
  65295. this._targetBuffer = tmpBuffer;
  65296. return this._currentActiveCount;
  65297. };
  65298. /**
  65299. * Rebuilds the particle system
  65300. */
  65301. GPUParticleSystem.prototype.rebuild = function () {
  65302. this._initialize(true);
  65303. };
  65304. GPUParticleSystem.prototype._releaseBuffers = function () {
  65305. if (this._buffer0) {
  65306. this._buffer0.dispose();
  65307. this._buffer0 = null;
  65308. }
  65309. if (this._buffer1) {
  65310. this._buffer1.dispose();
  65311. this._buffer1 = null;
  65312. }
  65313. if (this._spriteBuffer) {
  65314. this._spriteBuffer.dispose();
  65315. this._spriteBuffer = null;
  65316. }
  65317. };
  65318. GPUParticleSystem.prototype._releaseVAOs = function () {
  65319. if (!this._updateVAO) {
  65320. return;
  65321. }
  65322. for (var index = 0; index < this._updateVAO.length; index++) {
  65323. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  65324. }
  65325. this._updateVAO = [];
  65326. for (var index = 0; index < this._renderVAO.length; index++) {
  65327. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  65328. }
  65329. this._renderVAO = [];
  65330. };
  65331. /**
  65332. * Disposes the particle system and free the associated resources
  65333. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  65334. */
  65335. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  65336. if (disposeTexture === void 0) { disposeTexture = true; }
  65337. var index = this._scene.particleSystems.indexOf(this);
  65338. if (index > -1) {
  65339. this._scene.particleSystems.splice(index, 1);
  65340. }
  65341. this._releaseBuffers();
  65342. this._releaseVAOs();
  65343. if (this._colorGradientsTexture) {
  65344. this._colorGradientsTexture.dispose();
  65345. this._colorGradientsTexture = null;
  65346. }
  65347. if (this._sizeGradientsTexture) {
  65348. this._sizeGradientsTexture.dispose();
  65349. this._sizeGradientsTexture = null;
  65350. }
  65351. if (this._angularSpeedGradientsTexture) {
  65352. this._angularSpeedGradientsTexture.dispose();
  65353. this._angularSpeedGradientsTexture = null;
  65354. }
  65355. if (this._velocityGradientsTexture) {
  65356. this._velocityGradientsTexture.dispose();
  65357. this._velocityGradientsTexture = null;
  65358. }
  65359. if (this._limitVelocityGradientsTexture) {
  65360. this._limitVelocityGradientsTexture.dispose();
  65361. this._limitVelocityGradientsTexture = null;
  65362. }
  65363. if (this._dragGradientsTexture) {
  65364. this._dragGradientsTexture.dispose();
  65365. this._dragGradientsTexture = null;
  65366. }
  65367. if (this._randomTexture) {
  65368. this._randomTexture.dispose();
  65369. this._randomTexture = null;
  65370. }
  65371. if (this._randomTexture2) {
  65372. this._randomTexture2.dispose();
  65373. this._randomTexture2 = null;
  65374. }
  65375. if (disposeTexture && this.particleTexture) {
  65376. this.particleTexture.dispose();
  65377. this.particleTexture = null;
  65378. }
  65379. if (disposeTexture && this.noiseTexture) {
  65380. this.noiseTexture.dispose();
  65381. this.noiseTexture = null;
  65382. }
  65383. // Callback
  65384. this.onDisposeObservable.notifyObservers(this);
  65385. this.onDisposeObservable.clear();
  65386. };
  65387. /**
  65388. * Clones the particle system.
  65389. * @param name The name of the cloned object
  65390. * @param newEmitter The new emitter to use
  65391. * @returns the cloned particle system
  65392. */
  65393. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  65394. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  65395. BABYLON.Tools.DeepCopy(this, result);
  65396. if (newEmitter === undefined) {
  65397. newEmitter = this.emitter;
  65398. }
  65399. result.emitter = newEmitter;
  65400. if (this.particleTexture) {
  65401. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  65402. }
  65403. return result;
  65404. };
  65405. /**
  65406. * Serializes the particle system to a JSON object.
  65407. * @returns the JSON object
  65408. */
  65409. GPUParticleSystem.prototype.serialize = function () {
  65410. var serializationObject = {};
  65411. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  65412. serializationObject.activeParticleCount = this.activeParticleCount;
  65413. return serializationObject;
  65414. };
  65415. /**
  65416. * Parses a JSON object to create a GPU particle system.
  65417. * @param parsedParticleSystem The JSON object to parse
  65418. * @param scene The scene to create the particle system in
  65419. * @param rootUrl The root url to use to load external dependencies like texture
  65420. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  65421. * @returns the parsed GPU particle system
  65422. */
  65423. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  65424. if (doNotStart === void 0) { doNotStart = false; }
  65425. var name = parsedParticleSystem.name;
  65426. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  65427. if (parsedParticleSystem.activeParticleCount) {
  65428. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  65429. }
  65430. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  65431. // Auto start
  65432. if (parsedParticleSystem.preventAutoStart) {
  65433. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  65434. }
  65435. if (!doNotStart && !particleSystem.preventAutoStart) {
  65436. particleSystem.start();
  65437. }
  65438. return particleSystem;
  65439. };
  65440. return GPUParticleSystem;
  65441. }(BABYLON.BaseParticleSystem));
  65442. BABYLON.GPUParticleSystem = GPUParticleSystem;
  65443. })(BABYLON || (BABYLON = {}));
  65444. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  65445. var BABYLON;
  65446. (function (BABYLON) {
  65447. /**
  65448. * Represents one particle of a solid particle system.
  65449. */
  65450. var SolidParticle = /** @class */ (function () {
  65451. /**
  65452. * Creates a Solid Particle object.
  65453. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  65454. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  65455. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  65456. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  65457. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  65458. * @param shapeId (integer) is the model shape identifier in the SPS.
  65459. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  65460. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  65461. */
  65462. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  65463. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  65464. /**
  65465. * particle global index
  65466. */
  65467. this.idx = 0;
  65468. /**
  65469. * The color of the particle
  65470. */
  65471. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65472. /**
  65473. * The world space position of the particle.
  65474. */
  65475. this.position = BABYLON.Vector3.Zero();
  65476. /**
  65477. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  65478. */
  65479. this.rotation = BABYLON.Vector3.Zero();
  65480. /**
  65481. * The scaling of the particle.
  65482. */
  65483. this.scaling = BABYLON.Vector3.One();
  65484. /**
  65485. * The uvs of the particle.
  65486. */
  65487. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  65488. /**
  65489. * The current speed of the particle.
  65490. */
  65491. this.velocity = BABYLON.Vector3.Zero();
  65492. /**
  65493. * The pivot point in the particle local space.
  65494. */
  65495. this.pivot = BABYLON.Vector3.Zero();
  65496. /**
  65497. * Must the particle be translated from its pivot point in its local space ?
  65498. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  65499. * Default : false
  65500. */
  65501. this.translateFromPivot = false;
  65502. /**
  65503. * Is the particle active or not ?
  65504. */
  65505. this.alive = true;
  65506. /**
  65507. * Is the particle visible or not ?
  65508. */
  65509. this.isVisible = true;
  65510. /**
  65511. * Index of this particle in the global "positions" array (Internal use)
  65512. * @hidden
  65513. */
  65514. this._pos = 0;
  65515. /**
  65516. * @hidden Index of this particle in the global "indices" array (Internal use)
  65517. */
  65518. this._ind = 0;
  65519. /**
  65520. * ModelShape id of this particle
  65521. */
  65522. this.shapeId = 0;
  65523. /**
  65524. * Index of the particle in its shape id (Internal use)
  65525. */
  65526. this.idxInShape = 0;
  65527. /**
  65528. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  65529. */
  65530. this._stillInvisible = false;
  65531. /**
  65532. * @hidden Last computed particle rotation matrix
  65533. */
  65534. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  65535. /**
  65536. * Parent particle Id, if any.
  65537. * Default null.
  65538. */
  65539. this.parentId = null;
  65540. /**
  65541. * @hidden Internal global position in the SPS.
  65542. */
  65543. this._globalPosition = BABYLON.Vector3.Zero();
  65544. this.idx = particleIndex;
  65545. this._pos = positionIndex;
  65546. this._ind = indiceIndex;
  65547. this._model = model;
  65548. this.shapeId = shapeId;
  65549. this.idxInShape = idxInShape;
  65550. this._sps = sps;
  65551. if (modelBoundingInfo) {
  65552. this._modelBoundingInfo = modelBoundingInfo;
  65553. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  65554. }
  65555. }
  65556. Object.defineProperty(SolidParticle.prototype, "scale", {
  65557. /**
  65558. * Legacy support, changed scale to scaling
  65559. */
  65560. get: function () {
  65561. return this.scaling;
  65562. },
  65563. /**
  65564. * Legacy support, changed scale to scaling
  65565. */
  65566. set: function (scale) {
  65567. this.scaling = scale;
  65568. },
  65569. enumerable: true,
  65570. configurable: true
  65571. });
  65572. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  65573. /**
  65574. * Legacy support, changed quaternion to rotationQuaternion
  65575. */
  65576. get: function () {
  65577. return this.rotationQuaternion;
  65578. },
  65579. /**
  65580. * Legacy support, changed quaternion to rotationQuaternion
  65581. */
  65582. set: function (q) {
  65583. this.rotationQuaternion = q;
  65584. },
  65585. enumerable: true,
  65586. configurable: true
  65587. });
  65588. /**
  65589. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  65590. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  65591. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  65592. * @returns true if it intersects
  65593. */
  65594. SolidParticle.prototype.intersectsMesh = function (target) {
  65595. if (!this._boundingInfo || !target._boundingInfo) {
  65596. return false;
  65597. }
  65598. if (this._sps._bSphereOnly) {
  65599. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  65600. }
  65601. return this._boundingInfo.intersects(target._boundingInfo, false);
  65602. };
  65603. return SolidParticle;
  65604. }());
  65605. BABYLON.SolidParticle = SolidParticle;
  65606. /**
  65607. * Represents the shape of the model used by one particle of a solid particle system.
  65608. * SPS internal tool, don't use it manually.
  65609. */
  65610. var ModelShape = /** @class */ (function () {
  65611. /**
  65612. * 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.
  65613. * SPS internal tool, don't use it manually.
  65614. * @hidden
  65615. */
  65616. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  65617. /**
  65618. * length of the shape in the model indices array (internal use)
  65619. * @hidden
  65620. */
  65621. this._indicesLength = 0;
  65622. this.shapeID = id;
  65623. this._shape = shape;
  65624. this._indicesLength = indicesLength;
  65625. this._shapeUV = shapeUV;
  65626. this._positionFunction = posFunction;
  65627. this._vertexFunction = vtxFunction;
  65628. }
  65629. return ModelShape;
  65630. }());
  65631. BABYLON.ModelShape = ModelShape;
  65632. /**
  65633. * Represents a Depth Sorted Particle in the solid particle system.
  65634. */
  65635. var DepthSortedParticle = /** @class */ (function () {
  65636. function DepthSortedParticle() {
  65637. /**
  65638. * Index of the particle in the "indices" array
  65639. */
  65640. this.ind = 0;
  65641. /**
  65642. * Length of the particle shape in the "indices" array
  65643. */
  65644. this.indicesLength = 0;
  65645. /**
  65646. * Squared distance from the particle to the camera
  65647. */
  65648. this.sqDistance = 0.0;
  65649. }
  65650. return DepthSortedParticle;
  65651. }());
  65652. BABYLON.DepthSortedParticle = DepthSortedParticle;
  65653. })(BABYLON || (BABYLON = {}));
  65654. //# sourceMappingURL=babylon.solidParticle.js.map
  65655. var BABYLON;
  65656. (function (BABYLON) {
  65657. /**
  65658. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  65659. *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.
  65660. * The SPS is also a particle system. It provides some methods to manage the particles.
  65661. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  65662. *
  65663. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  65664. */
  65665. var SolidParticleSystem = /** @class */ (function () {
  65666. /**
  65667. * Creates a SPS (Solid Particle System) object.
  65668. * @param name (String) is the SPS name, this will be the underlying mesh name.
  65669. * @param scene (Scene) is the scene in which the SPS is added.
  65670. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  65671. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  65672. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  65673. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  65674. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  65675. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  65676. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  65677. */
  65678. function SolidParticleSystem(name, scene, options) {
  65679. /**
  65680. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  65681. * Example : var p = SPS.particles[i];
  65682. */
  65683. this.particles = new Array();
  65684. /**
  65685. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  65686. */
  65687. this.nbParticles = 0;
  65688. /**
  65689. * If the particles must ever face the camera (default false). Useful for planar particles.
  65690. */
  65691. this.billboard = false;
  65692. /**
  65693. * Recompute normals when adding a shape
  65694. */
  65695. this.recomputeNormals = true;
  65696. /**
  65697. * This a counter ofr your own usage. It's not set by any SPS functions.
  65698. */
  65699. this.counter = 0;
  65700. /**
  65701. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  65702. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  65703. */
  65704. this.vars = {};
  65705. /**
  65706. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  65707. * @hidden
  65708. */
  65709. this._bSphereOnly = false;
  65710. /**
  65711. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  65712. * @hidden
  65713. */
  65714. this._bSphereRadiusFactor = 1.0;
  65715. this._positions = new Array();
  65716. this._indices = new Array();
  65717. this._normals = new Array();
  65718. this._colors = new Array();
  65719. this._uvs = new Array();
  65720. this._index = 0; // indices index
  65721. this._updatable = true;
  65722. this._pickable = false;
  65723. this._isVisibilityBoxLocked = false;
  65724. this._alwaysVisible = false;
  65725. this._depthSort = false;
  65726. this._shapeCounter = 0;
  65727. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  65728. this._color = new BABYLON.Color4(0, 0, 0, 0);
  65729. this._computeParticleColor = true;
  65730. this._computeParticleTexture = true;
  65731. this._computeParticleRotation = true;
  65732. this._computeParticleVertex = false;
  65733. this._computeBoundingBox = false;
  65734. this._depthSortParticles = true;
  65735. this._cam_axisZ = BABYLON.Vector3.Zero();
  65736. this._cam_axisY = BABYLON.Vector3.Zero();
  65737. this._cam_axisX = BABYLON.Vector3.Zero();
  65738. this._axisZ = BABYLON.Axis.Z;
  65739. this._camDir = BABYLON.Vector3.Zero();
  65740. this._camInvertedPosition = BABYLON.Vector3.Zero();
  65741. this._rotMatrix = new BABYLON.Matrix();
  65742. this._invertMatrix = new BABYLON.Matrix();
  65743. this._rotated = BABYLON.Vector3.Zero();
  65744. this._quaternion = new BABYLON.Quaternion();
  65745. this._vertex = BABYLON.Vector3.Zero();
  65746. this._normal = BABYLON.Vector3.Zero();
  65747. this._yaw = 0.0;
  65748. this._pitch = 0.0;
  65749. this._roll = 0.0;
  65750. this._halfroll = 0.0;
  65751. this._halfpitch = 0.0;
  65752. this._halfyaw = 0.0;
  65753. this._sinRoll = 0.0;
  65754. this._cosRoll = 0.0;
  65755. this._sinPitch = 0.0;
  65756. this._cosPitch = 0.0;
  65757. this._sinYaw = 0.0;
  65758. this._cosYaw = 0.0;
  65759. this._mustUnrotateFixedNormals = false;
  65760. this._minimum = BABYLON.Vector3.Zero();
  65761. this._maximum = BABYLON.Vector3.Zero();
  65762. this._minBbox = BABYLON.Vector3.Zero();
  65763. this._maxBbox = BABYLON.Vector3.Zero();
  65764. this._particlesIntersect = false;
  65765. this._depthSortFunction = function (p1, p2) {
  65766. return (p2.sqDistance - p1.sqDistance);
  65767. };
  65768. this._needs32Bits = false;
  65769. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  65770. this._scaledPivot = BABYLON.Vector3.Zero();
  65771. this._particleHasParent = false;
  65772. this.name = name;
  65773. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65774. this._camera = scene.activeCamera;
  65775. this._pickable = options ? options.isPickable : false;
  65776. this._depthSort = options ? options.enableDepthSort : false;
  65777. this._particlesIntersect = options ? options.particleIntersection : false;
  65778. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  65779. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  65780. if (options && options.updatable !== undefined) {
  65781. this._updatable = options.updatable;
  65782. }
  65783. else {
  65784. this._updatable = true;
  65785. }
  65786. if (this._pickable) {
  65787. this.pickedParticles = [];
  65788. }
  65789. if (this._depthSort) {
  65790. this.depthSortedParticles = [];
  65791. }
  65792. }
  65793. /**
  65794. * Builds the SPS underlying mesh. Returns a standard Mesh.
  65795. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  65796. * @returns the created mesh
  65797. */
  65798. SolidParticleSystem.prototype.buildMesh = function () {
  65799. if (this.nbParticles === 0) {
  65800. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  65801. this.addShape(triangle, 1);
  65802. triangle.dispose();
  65803. }
  65804. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  65805. this._positions32 = new Float32Array(this._positions);
  65806. this._uvs32 = new Float32Array(this._uvs);
  65807. this._colors32 = new Float32Array(this._colors);
  65808. if (this.recomputeNormals) {
  65809. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  65810. }
  65811. this._normals32 = new Float32Array(this._normals);
  65812. this._fixedNormal32 = new Float32Array(this._normals);
  65813. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  65814. this._unrotateFixedNormals();
  65815. }
  65816. var vertexData = new BABYLON.VertexData();
  65817. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  65818. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  65819. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  65820. if (this._uvs32.length > 0) {
  65821. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  65822. }
  65823. if (this._colors32.length > 0) {
  65824. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  65825. }
  65826. var mesh = new BABYLON.Mesh(this.name, this._scene);
  65827. vertexData.applyToMesh(mesh, this._updatable);
  65828. this.mesh = mesh;
  65829. this.mesh.isPickable = this._pickable;
  65830. // free memory
  65831. if (!this._depthSort) {
  65832. this._indices = null;
  65833. }
  65834. this._positions = null;
  65835. this._normals = null;
  65836. this._uvs = null;
  65837. this._colors = null;
  65838. if (!this._updatable) {
  65839. this.particles.length = 0;
  65840. }
  65841. return mesh;
  65842. };
  65843. /**
  65844. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  65845. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  65846. * Thus the particles generated from `digest()` have their property `position` set yet.
  65847. * @param mesh ( Mesh ) is the mesh to be digested
  65848. * @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
  65849. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  65850. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  65851. * @returns the current SPS
  65852. */
  65853. SolidParticleSystem.prototype.digest = function (mesh, options) {
  65854. var size = (options && options.facetNb) || 1;
  65855. var number = (options && options.number) || 0;
  65856. var delta = (options && options.delta) || 0;
  65857. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65858. var meshInd = mesh.getIndices();
  65859. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65860. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65861. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65862. var f = 0; // facet counter
  65863. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  65864. // compute size from number
  65865. if (number) {
  65866. number = (number > totalFacets) ? totalFacets : number;
  65867. size = Math.round(totalFacets / number);
  65868. delta = 0;
  65869. }
  65870. else {
  65871. size = (size > totalFacets) ? totalFacets : size;
  65872. }
  65873. var facetPos = []; // submesh positions
  65874. var facetInd = []; // submesh indices
  65875. var facetUV = []; // submesh UV
  65876. var facetCol = []; // submesh colors
  65877. var barycenter = BABYLON.Vector3.Zero();
  65878. var sizeO = size;
  65879. while (f < totalFacets) {
  65880. size = sizeO + Math.floor((1 + delta) * Math.random());
  65881. if (f > totalFacets - size) {
  65882. size = totalFacets - f;
  65883. }
  65884. // reset temp arrays
  65885. facetPos.length = 0;
  65886. facetInd.length = 0;
  65887. facetUV.length = 0;
  65888. facetCol.length = 0;
  65889. // iterate over "size" facets
  65890. var fi = 0;
  65891. for (var j = f * 3; j < (f + size) * 3; j++) {
  65892. facetInd.push(fi);
  65893. var i = meshInd[j];
  65894. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  65895. if (meshUV) {
  65896. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  65897. }
  65898. if (meshCol) {
  65899. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  65900. }
  65901. fi++;
  65902. }
  65903. // create a model shape for each single particle
  65904. var idx = this.nbParticles;
  65905. var shape = this._posToShape(facetPos);
  65906. var shapeUV = this._uvsToShapeUV(facetUV);
  65907. // compute the barycenter of the shape
  65908. var v;
  65909. for (v = 0; v < shape.length; v++) {
  65910. barycenter.addInPlace(shape[v]);
  65911. }
  65912. barycenter.scaleInPlace(1 / shape.length);
  65913. // shift the shape from its barycenter to the origin
  65914. for (v = 0; v < shape.length; v++) {
  65915. shape[v].subtractInPlace(barycenter);
  65916. }
  65917. var bInfo;
  65918. if (this._particlesIntersect) {
  65919. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  65920. }
  65921. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  65922. // add the particle in the SPS
  65923. var currentPos = this._positions.length;
  65924. var currentInd = this._indices.length;
  65925. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  65926. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  65927. // initialize the particle position
  65928. this.particles[this.nbParticles].position.addInPlace(barycenter);
  65929. this._index += shape.length;
  65930. idx++;
  65931. this.nbParticles++;
  65932. this._shapeCounter++;
  65933. f += size;
  65934. }
  65935. return this;
  65936. };
  65937. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  65938. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  65939. var index = 0;
  65940. var idx = 0;
  65941. for (var p = 0; p < this.particles.length; p++) {
  65942. this._particle = this.particles[p];
  65943. this._shape = this._particle._model._shape;
  65944. if (this._particle.rotationQuaternion) {
  65945. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65946. }
  65947. else {
  65948. this._yaw = this._particle.rotation.y;
  65949. this._pitch = this._particle.rotation.x;
  65950. this._roll = this._particle.rotation.z;
  65951. this._quaternionRotationYPR();
  65952. }
  65953. this._quaternionToRotationMatrix();
  65954. this._rotMatrix.invertToRef(this._invertMatrix);
  65955. for (var pt = 0; pt < this._shape.length; pt++) {
  65956. idx = index + pt * 3;
  65957. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  65958. this._fixedNormal32[idx] = this._normal.x;
  65959. this._fixedNormal32[idx + 1] = this._normal.y;
  65960. this._fixedNormal32[idx + 2] = this._normal.z;
  65961. }
  65962. index = idx + 3;
  65963. }
  65964. };
  65965. //reset copy
  65966. SolidParticleSystem.prototype._resetCopy = function () {
  65967. this._copy.position.x = 0;
  65968. this._copy.position.y = 0;
  65969. this._copy.position.z = 0;
  65970. this._copy.rotation.x = 0;
  65971. this._copy.rotation.y = 0;
  65972. this._copy.rotation.z = 0;
  65973. this._copy.rotationQuaternion = null;
  65974. this._copy.scaling.x = 1.0;
  65975. this._copy.scaling.y = 1.0;
  65976. this._copy.scaling.z = 1.0;
  65977. this._copy.uvs.x = 0;
  65978. this._copy.uvs.y = 0;
  65979. this._copy.uvs.z = 1.0;
  65980. this._copy.uvs.w = 1.0;
  65981. this._copy.color = null;
  65982. this._copy.translateFromPivot = false;
  65983. };
  65984. // _meshBuilder : inserts the shape model in the global SPS mesh
  65985. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  65986. var i;
  65987. var u = 0;
  65988. var c = 0;
  65989. var n = 0;
  65990. this._resetCopy();
  65991. if (options && options.positionFunction) { // call to custom positionFunction
  65992. options.positionFunction(this._copy, idx, idxInShape);
  65993. this._mustUnrotateFixedNormals = true;
  65994. }
  65995. if (this._copy.rotationQuaternion) {
  65996. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65997. }
  65998. else {
  65999. this._yaw = this._copy.rotation.y;
  66000. this._pitch = this._copy.rotation.x;
  66001. this._roll = this._copy.rotation.z;
  66002. this._quaternionRotationYPR();
  66003. }
  66004. this._quaternionToRotationMatrix();
  66005. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  66006. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  66007. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  66008. if (this._copy.translateFromPivot) {
  66009. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66010. }
  66011. else {
  66012. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66013. }
  66014. for (i = 0; i < shape.length; i++) {
  66015. this._vertex.x = shape[i].x;
  66016. this._vertex.y = shape[i].y;
  66017. this._vertex.z = shape[i].z;
  66018. if (options && options.vertexFunction) {
  66019. options.vertexFunction(this._copy, this._vertex, i);
  66020. }
  66021. this._vertex.x *= this._copy.scaling.x;
  66022. this._vertex.y *= this._copy.scaling.y;
  66023. this._vertex.z *= this._copy.scaling.z;
  66024. this._vertex.x -= this._scaledPivot.x;
  66025. this._vertex.y -= this._scaledPivot.y;
  66026. this._vertex.z -= this._scaledPivot.z;
  66027. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66028. this._rotated.addInPlace(this._pivotBackTranslation);
  66029. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  66030. if (meshUV) {
  66031. 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);
  66032. u += 2;
  66033. }
  66034. if (this._copy.color) {
  66035. this._color = this._copy.color;
  66036. }
  66037. else if (meshCol && meshCol[c] !== undefined) {
  66038. this._color.r = meshCol[c];
  66039. this._color.g = meshCol[c + 1];
  66040. this._color.b = meshCol[c + 2];
  66041. this._color.a = meshCol[c + 3];
  66042. }
  66043. else {
  66044. this._color.r = 1.0;
  66045. this._color.g = 1.0;
  66046. this._color.b = 1.0;
  66047. this._color.a = 1.0;
  66048. }
  66049. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  66050. c += 4;
  66051. if (!this.recomputeNormals && meshNor) {
  66052. this._normal.x = meshNor[n];
  66053. this._normal.y = meshNor[n + 1];
  66054. this._normal.z = meshNor[n + 2];
  66055. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  66056. normals.push(this._normal.x, this._normal.y, this._normal.z);
  66057. n += 3;
  66058. }
  66059. }
  66060. for (i = 0; i < meshInd.length; i++) {
  66061. var current_ind = p + meshInd[i];
  66062. indices.push(current_ind);
  66063. if (current_ind > 65535) {
  66064. this._needs32Bits = true;
  66065. }
  66066. }
  66067. if (this._pickable) {
  66068. var nbfaces = meshInd.length / 3;
  66069. for (i = 0; i < nbfaces; i++) {
  66070. this.pickedParticles.push({ idx: idx, faceId: i });
  66071. }
  66072. }
  66073. if (this._depthSort) {
  66074. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  66075. }
  66076. return this._copy;
  66077. };
  66078. // returns a shape array from positions array
  66079. SolidParticleSystem.prototype._posToShape = function (positions) {
  66080. var shape = [];
  66081. for (var i = 0; i < positions.length; i += 3) {
  66082. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  66083. }
  66084. return shape;
  66085. };
  66086. // returns a shapeUV array from a Vector4 uvs
  66087. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  66088. var shapeUV = [];
  66089. if (uvs) {
  66090. for (var i = 0; i < uvs.length; i++)
  66091. shapeUV.push(uvs[i]);
  66092. }
  66093. return shapeUV;
  66094. };
  66095. // adds a new particle object in the particles array
  66096. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  66097. if (bInfo === void 0) { bInfo = null; }
  66098. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  66099. this.particles.push(sp);
  66100. return sp;
  66101. };
  66102. /**
  66103. * Adds some particles to the SPS from the model shape. Returns the shape id.
  66104. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  66105. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  66106. * @param nb (positive integer) the number of particles to be created from this model
  66107. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  66108. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  66109. * @returns the number of shapes in the system
  66110. */
  66111. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  66112. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66113. var meshInd = mesh.getIndices();
  66114. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66115. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66116. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66117. var bbInfo;
  66118. if (this._particlesIntersect) {
  66119. bbInfo = mesh.getBoundingInfo();
  66120. }
  66121. var shape = this._posToShape(meshPos);
  66122. var shapeUV = this._uvsToShapeUV(meshUV);
  66123. var posfunc = options ? options.positionFunction : null;
  66124. var vtxfunc = options ? options.vertexFunction : null;
  66125. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  66126. // particles
  66127. var sp;
  66128. var currentCopy;
  66129. var idx = this.nbParticles;
  66130. for (var i = 0; i < nb; i++) {
  66131. var currentPos = this._positions.length;
  66132. var currentInd = this._indices.length;
  66133. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  66134. if (this._updatable) {
  66135. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  66136. sp.position.copyFrom(currentCopy.position);
  66137. sp.rotation.copyFrom(currentCopy.rotation);
  66138. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  66139. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  66140. }
  66141. if (currentCopy.color && sp.color) {
  66142. sp.color.copyFrom(currentCopy.color);
  66143. }
  66144. sp.scaling.copyFrom(currentCopy.scaling);
  66145. sp.uvs.copyFrom(currentCopy.uvs);
  66146. }
  66147. this._index += shape.length;
  66148. idx++;
  66149. }
  66150. this.nbParticles += nb;
  66151. this._shapeCounter++;
  66152. return this._shapeCounter - 1;
  66153. };
  66154. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  66155. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  66156. this._resetCopy();
  66157. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  66158. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  66159. }
  66160. if (this._copy.rotationQuaternion) {
  66161. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66162. }
  66163. else {
  66164. this._yaw = this._copy.rotation.y;
  66165. this._pitch = this._copy.rotation.x;
  66166. this._roll = this._copy.rotation.z;
  66167. this._quaternionRotationYPR();
  66168. }
  66169. this._quaternionToRotationMatrix();
  66170. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66171. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66172. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66173. if (this._copy.translateFromPivot) {
  66174. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66175. }
  66176. else {
  66177. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66178. }
  66179. this._shape = particle._model._shape;
  66180. for (var pt = 0; pt < this._shape.length; pt++) {
  66181. this._vertex.x = this._shape[pt].x;
  66182. this._vertex.y = this._shape[pt].y;
  66183. this._vertex.z = this._shape[pt].z;
  66184. if (particle._model._vertexFunction) {
  66185. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  66186. }
  66187. this._vertex.x *= this._copy.scaling.x;
  66188. this._vertex.y *= this._copy.scaling.y;
  66189. this._vertex.z *= this._copy.scaling.z;
  66190. this._vertex.x -= this._scaledPivot.x;
  66191. this._vertex.y -= this._scaledPivot.y;
  66192. this._vertex.z -= this._scaledPivot.z;
  66193. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66194. this._rotated.addInPlace(this._pivotBackTranslation);
  66195. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  66196. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  66197. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  66198. }
  66199. particle.position.x = 0.0;
  66200. particle.position.y = 0.0;
  66201. particle.position.z = 0.0;
  66202. particle.rotation.x = 0.0;
  66203. particle.rotation.y = 0.0;
  66204. particle.rotation.z = 0.0;
  66205. particle.rotationQuaternion = null;
  66206. particle.scaling.x = 1.0;
  66207. particle.scaling.y = 1.0;
  66208. particle.scaling.z = 1.0;
  66209. particle.uvs.x = 0.0;
  66210. particle.uvs.y = 0.0;
  66211. particle.uvs.z = 1.0;
  66212. particle.uvs.w = 1.0;
  66213. particle.pivot.x = 0.0;
  66214. particle.pivot.y = 0.0;
  66215. particle.pivot.z = 0.0;
  66216. particle.translateFromPivot = false;
  66217. particle.parentId = null;
  66218. };
  66219. /**
  66220. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  66221. * @returns the SPS.
  66222. */
  66223. SolidParticleSystem.prototype.rebuildMesh = function () {
  66224. for (var p = 0; p < this.particles.length; p++) {
  66225. this._rebuildParticle(this.particles[p]);
  66226. }
  66227. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66228. return this;
  66229. };
  66230. /**
  66231. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  66232. * This method calls `updateParticle()` for each particle of the SPS.
  66233. * For an animated SPS, it is usually called within the render loop.
  66234. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66235. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66236. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66237. * @returns the SPS.
  66238. */
  66239. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66240. if (start === void 0) { start = 0; }
  66241. if (end === void 0) { end = this.nbParticles - 1; }
  66242. if (update === void 0) { update = true; }
  66243. if (!this._updatable) {
  66244. return this;
  66245. }
  66246. // custom beforeUpdate
  66247. this.beforeUpdateParticles(start, end, update);
  66248. this._cam_axisX.x = 1.0;
  66249. this._cam_axisX.y = 0.0;
  66250. this._cam_axisX.z = 0.0;
  66251. this._cam_axisY.x = 0.0;
  66252. this._cam_axisY.y = 1.0;
  66253. this._cam_axisY.z = 0.0;
  66254. this._cam_axisZ.x = 0.0;
  66255. this._cam_axisZ.y = 0.0;
  66256. this._cam_axisZ.z = 1.0;
  66257. // cases when the World Matrix is to be computed first
  66258. if (this.billboard || this._depthSort) {
  66259. this.mesh.computeWorldMatrix(true);
  66260. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  66261. }
  66262. // if the particles will always face the camera
  66263. if (this.billboard) {
  66264. // compute the camera position and un-rotate it by the current mesh rotation
  66265. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  66266. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  66267. this._cam_axisZ.normalize();
  66268. // same for camera up vector extracted from the cam view matrix
  66269. var view = this._camera.getViewMatrix(true);
  66270. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  66271. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  66272. this._cam_axisY.normalize();
  66273. this._cam_axisX.normalize();
  66274. }
  66275. // if depthSort, compute the camera global position in the mesh local system
  66276. if (this._depthSort) {
  66277. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  66278. }
  66279. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  66280. var idx = 0; // current position index in the global array positions32
  66281. var index = 0; // position start index in the global array positions32 of the current particle
  66282. var colidx = 0; // current color index in the global array colors32
  66283. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  66284. var uvidx = 0; // current uv index in the global array uvs32
  66285. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  66286. var pt = 0; // current index in the particle model shape
  66287. if (this.mesh.isFacetDataEnabled) {
  66288. this._computeBoundingBox = true;
  66289. }
  66290. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  66291. if (this._computeBoundingBox) {
  66292. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  66293. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  66294. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  66295. }
  66296. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  66297. if (this.mesh._boundingInfo) {
  66298. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  66299. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  66300. }
  66301. }
  66302. }
  66303. // particle loop
  66304. index = this.particles[start]._pos;
  66305. var vpos = (index / 3) | 0;
  66306. colorIndex = vpos * 4;
  66307. uvIndex = vpos * 2;
  66308. for (var p = start; p <= end; p++) {
  66309. this._particle = this.particles[p];
  66310. this._shape = this._particle._model._shape;
  66311. this._shapeUV = this._particle._model._shapeUV;
  66312. // call to custom user function to update the particle properties
  66313. this.updateParticle(this._particle);
  66314. // camera-particle distance for depth sorting
  66315. if (this._depthSort && this._depthSortParticles) {
  66316. var dsp = this.depthSortedParticles[p];
  66317. dsp.ind = this._particle._ind;
  66318. dsp.indicesLength = this._particle._model._indicesLength;
  66319. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  66320. }
  66321. // skip the computations for inactive or already invisible particles
  66322. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  66323. // increment indexes for the next particle
  66324. pt = this._shape.length;
  66325. index += pt * 3;
  66326. colorIndex += pt * 4;
  66327. uvIndex += pt * 2;
  66328. continue;
  66329. }
  66330. if (this._particle.isVisible) {
  66331. this._particle._stillInvisible = false; // un-mark permanent invisibility
  66332. this._particleHasParent = (this._particle.parentId !== null);
  66333. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66334. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66335. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66336. // particle rotation matrix
  66337. if (this.billboard) {
  66338. this._particle.rotation.x = 0.0;
  66339. this._particle.rotation.y = 0.0;
  66340. }
  66341. if (this._computeParticleRotation || this.billboard) {
  66342. if (this._particle.rotationQuaternion) {
  66343. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66344. }
  66345. else {
  66346. this._yaw = this._particle.rotation.y;
  66347. this._pitch = this._particle.rotation.x;
  66348. this._roll = this._particle.rotation.z;
  66349. this._quaternionRotationYPR();
  66350. }
  66351. this._quaternionToRotationMatrix();
  66352. }
  66353. if (this._particleHasParent) {
  66354. this._parent = this.particles[this._particle.parentId];
  66355. 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];
  66356. 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];
  66357. 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];
  66358. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  66359. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  66360. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  66361. if (this._computeParticleRotation || this.billboard) {
  66362. 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];
  66363. 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];
  66364. 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];
  66365. 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];
  66366. 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];
  66367. 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];
  66368. 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];
  66369. 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];
  66370. 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];
  66371. }
  66372. }
  66373. else {
  66374. this._particle._globalPosition.x = this._particle.position.x;
  66375. this._particle._globalPosition.y = this._particle.position.y;
  66376. this._particle._globalPosition.z = this._particle.position.z;
  66377. if (this._computeParticleRotation || this.billboard) {
  66378. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  66379. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  66380. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  66381. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  66382. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  66383. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  66384. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  66385. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  66386. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  66387. }
  66388. }
  66389. if (this._particle.translateFromPivot) {
  66390. this._pivotBackTranslation.x = 0.0;
  66391. this._pivotBackTranslation.y = 0.0;
  66392. this._pivotBackTranslation.z = 0.0;
  66393. }
  66394. else {
  66395. this._pivotBackTranslation.x = this._scaledPivot.x;
  66396. this._pivotBackTranslation.y = this._scaledPivot.y;
  66397. this._pivotBackTranslation.z = this._scaledPivot.z;
  66398. }
  66399. // particle vertex loop
  66400. for (pt = 0; pt < this._shape.length; pt++) {
  66401. idx = index + pt * 3;
  66402. colidx = colorIndex + pt * 4;
  66403. uvidx = uvIndex + pt * 2;
  66404. this._vertex.x = this._shape[pt].x;
  66405. this._vertex.y = this._shape[pt].y;
  66406. this._vertex.z = this._shape[pt].z;
  66407. if (this._computeParticleVertex) {
  66408. this.updateParticleVertex(this._particle, this._vertex, pt);
  66409. }
  66410. // positions
  66411. this._vertex.x *= this._particle.scaling.x;
  66412. this._vertex.y *= this._particle.scaling.y;
  66413. this._vertex.z *= this._particle.scaling.z;
  66414. this._vertex.x -= this._scaledPivot.x;
  66415. this._vertex.y -= this._scaledPivot.y;
  66416. this._vertex.z -= this._scaledPivot.z;
  66417. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66418. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66419. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66420. this._rotated.x += this._pivotBackTranslation.x;
  66421. this._rotated.y += this._pivotBackTranslation.y;
  66422. this._rotated.z += this._pivotBackTranslation.z;
  66423. 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;
  66424. 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;
  66425. 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;
  66426. if (this._computeBoundingBox) {
  66427. if (this._positions32[idx] < this._minimum.x) {
  66428. this._minimum.x = this._positions32[idx];
  66429. }
  66430. if (this._positions32[idx] > this._maximum.x) {
  66431. this._maximum.x = this._positions32[idx];
  66432. }
  66433. if (this._positions32[idx + 1] < this._minimum.y) {
  66434. this._minimum.y = this._positions32[idx + 1];
  66435. }
  66436. if (this._positions32[idx + 1] > this._maximum.y) {
  66437. this._maximum.y = this._positions32[idx + 1];
  66438. }
  66439. if (this._positions32[idx + 2] < this._minimum.z) {
  66440. this._minimum.z = this._positions32[idx + 2];
  66441. }
  66442. if (this._positions32[idx + 2] > this._maximum.z) {
  66443. this._maximum.z = this._positions32[idx + 2];
  66444. }
  66445. }
  66446. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  66447. if (!this._computeParticleVertex) {
  66448. this._normal.x = this._fixedNormal32[idx];
  66449. this._normal.y = this._fixedNormal32[idx + 1];
  66450. this._normal.z = this._fixedNormal32[idx + 2];
  66451. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  66452. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  66453. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  66454. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  66455. 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;
  66456. 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;
  66457. }
  66458. if (this._computeParticleColor && this._particle.color) {
  66459. this._colors32[colidx] = this._particle.color.r;
  66460. this._colors32[colidx + 1] = this._particle.color.g;
  66461. this._colors32[colidx + 2] = this._particle.color.b;
  66462. this._colors32[colidx + 3] = this._particle.color.a;
  66463. }
  66464. if (this._computeParticleTexture) {
  66465. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66466. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66467. }
  66468. }
  66469. }
  66470. // particle just set invisible : scaled to zero and positioned at the origin
  66471. else {
  66472. this._particle._stillInvisible = true; // mark the particle as invisible
  66473. for (pt = 0; pt < this._shape.length; pt++) {
  66474. idx = index + pt * 3;
  66475. colidx = colorIndex + pt * 4;
  66476. uvidx = uvIndex + pt * 2;
  66477. this._positions32[idx] = 0.0;
  66478. this._positions32[idx + 1] = 0.0;
  66479. this._positions32[idx + 2] = 0.0;
  66480. this._normals32[idx] = 0.0;
  66481. this._normals32[idx + 1] = 0.0;
  66482. this._normals32[idx + 2] = 0.0;
  66483. if (this._computeParticleColor && this._particle.color) {
  66484. this._colors32[colidx] = this._particle.color.r;
  66485. this._colors32[colidx + 1] = this._particle.color.g;
  66486. this._colors32[colidx + 2] = this._particle.color.b;
  66487. this._colors32[colidx + 3] = this._particle.color.a;
  66488. }
  66489. if (this._computeParticleTexture) {
  66490. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66491. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66492. }
  66493. }
  66494. }
  66495. // if the particle intersections must be computed : update the bbInfo
  66496. if (this._particlesIntersect) {
  66497. var bInfo = this._particle._boundingInfo;
  66498. var bBox = bInfo.boundingBox;
  66499. var bSphere = bInfo.boundingSphere;
  66500. if (!this._bSphereOnly) {
  66501. // place, scale and rotate the particle bbox within the SPS local system, then update it
  66502. for (var b = 0; b < bBox.vectors.length; b++) {
  66503. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  66504. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  66505. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  66506. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66507. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66508. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66509. 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;
  66510. 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;
  66511. 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;
  66512. }
  66513. bBox._update(this.mesh._worldMatrix);
  66514. }
  66515. // place and scale the particle bouding sphere in the SPS local system, then update it
  66516. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  66517. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  66518. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  66519. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  66520. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  66521. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  66522. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  66523. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  66524. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  66525. 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));
  66526. bSphere._update(this.mesh._worldMatrix);
  66527. }
  66528. // increment indexes for the next particle
  66529. index = idx + 3;
  66530. colorIndex = colidx + 4;
  66531. uvIndex = uvidx + 2;
  66532. }
  66533. // if the VBO must be updated
  66534. if (update) {
  66535. if (this._computeParticleColor) {
  66536. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  66537. }
  66538. if (this._computeParticleTexture) {
  66539. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  66540. }
  66541. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66542. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  66543. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  66544. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  66545. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  66546. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  66547. for (var i = 0; i < this._normals32.length; i++) {
  66548. this._fixedNormal32[i] = this._normals32[i];
  66549. }
  66550. }
  66551. if (!this.mesh.areNormalsFrozen) {
  66552. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  66553. }
  66554. }
  66555. if (this._depthSort && this._depthSortParticles) {
  66556. this.depthSortedParticles.sort(this._depthSortFunction);
  66557. var dspl = this.depthSortedParticles.length;
  66558. var sorted = 0;
  66559. var lind = 0;
  66560. var sind = 0;
  66561. var sid = 0;
  66562. for (sorted = 0; sorted < dspl; sorted++) {
  66563. lind = this.depthSortedParticles[sorted].indicesLength;
  66564. sind = this.depthSortedParticles[sorted].ind;
  66565. for (var i = 0; i < lind; i++) {
  66566. this._indices32[sid] = this._indices[sind + i];
  66567. sid++;
  66568. }
  66569. }
  66570. this.mesh.updateIndices(this._indices32);
  66571. }
  66572. }
  66573. if (this._computeBoundingBox) {
  66574. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  66575. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  66576. }
  66577. this.afterUpdateParticles(start, end, update);
  66578. return this;
  66579. };
  66580. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  66581. this._halfroll = this._roll * 0.5;
  66582. this._halfpitch = this._pitch * 0.5;
  66583. this._halfyaw = this._yaw * 0.5;
  66584. this._sinRoll = Math.sin(this._halfroll);
  66585. this._cosRoll = Math.cos(this._halfroll);
  66586. this._sinPitch = Math.sin(this._halfpitch);
  66587. this._cosPitch = Math.cos(this._halfpitch);
  66588. this._sinYaw = Math.sin(this._halfyaw);
  66589. this._cosYaw = Math.cos(this._halfyaw);
  66590. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  66591. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  66592. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  66593. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  66594. };
  66595. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  66596. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  66597. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  66598. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  66599. this._rotMatrix.m[3] = 0;
  66600. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  66601. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  66602. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  66603. this._rotMatrix.m[7] = 0;
  66604. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  66605. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  66606. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  66607. this._rotMatrix.m[11] = 0;
  66608. this._rotMatrix.m[12] = 0;
  66609. this._rotMatrix.m[13] = 0;
  66610. this._rotMatrix.m[14] = 0;
  66611. this._rotMatrix.m[15] = 1.0;
  66612. };
  66613. /**
  66614. * Disposes the SPS.
  66615. */
  66616. SolidParticleSystem.prototype.dispose = function () {
  66617. this.mesh.dispose();
  66618. this.vars = null;
  66619. // drop references to internal big arrays for the GC
  66620. this._positions = null;
  66621. this._indices = null;
  66622. this._normals = null;
  66623. this._uvs = null;
  66624. this._colors = null;
  66625. this._indices32 = null;
  66626. this._positions32 = null;
  66627. this._normals32 = null;
  66628. this._fixedNormal32 = null;
  66629. this._uvs32 = null;
  66630. this._colors32 = null;
  66631. this.pickedParticles = null;
  66632. };
  66633. /**
  66634. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  66635. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66636. * @returns the SPS.
  66637. */
  66638. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  66639. if (!this._isVisibilityBoxLocked) {
  66640. this.mesh.refreshBoundingInfo();
  66641. }
  66642. return this;
  66643. };
  66644. /**
  66645. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  66646. * @param size the size (float) of the visibility box
  66647. * note : this doesn't lock the SPS mesh bounding box.
  66648. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66649. */
  66650. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  66651. var vis = size / 2;
  66652. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  66653. };
  66654. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  66655. /**
  66656. * Gets whether the SPS as always visible or not
  66657. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66658. */
  66659. get: function () {
  66660. return this._alwaysVisible;
  66661. },
  66662. /**
  66663. * Sets the SPS as always visible or not
  66664. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66665. */
  66666. set: function (val) {
  66667. this._alwaysVisible = val;
  66668. this.mesh.alwaysSelectAsActiveMesh = val;
  66669. },
  66670. enumerable: true,
  66671. configurable: true
  66672. });
  66673. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  66674. /**
  66675. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66676. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66677. */
  66678. get: function () {
  66679. return this._isVisibilityBoxLocked;
  66680. },
  66681. /**
  66682. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66683. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66684. */
  66685. set: function (val) {
  66686. this._isVisibilityBoxLocked = val;
  66687. var boundingInfo = this.mesh.getBoundingInfo();
  66688. boundingInfo.isLocked = val;
  66689. },
  66690. enumerable: true,
  66691. configurable: true
  66692. });
  66693. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  66694. /**
  66695. * Gets if `setParticles()` computes the particle rotations or not.
  66696. * Default value : true. The SPS is faster when it's set to false.
  66697. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66698. */
  66699. get: function () {
  66700. return this._computeParticleRotation;
  66701. },
  66702. /**
  66703. * Tells to `setParticles()` to compute the particle rotations or not.
  66704. * Default value : true. The SPS is faster when it's set to false.
  66705. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66706. */
  66707. set: function (val) {
  66708. this._computeParticleRotation = val;
  66709. },
  66710. enumerable: true,
  66711. configurable: true
  66712. });
  66713. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  66714. /**
  66715. * Gets if `setParticles()` computes the particle colors or not.
  66716. * Default value : true. The SPS is faster when it's set to false.
  66717. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66718. */
  66719. get: function () {
  66720. return this._computeParticleColor;
  66721. },
  66722. /**
  66723. * Tells to `setParticles()` to compute the particle colors or not.
  66724. * Default value : true. The SPS is faster when it's set to false.
  66725. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66726. */
  66727. set: function (val) {
  66728. this._computeParticleColor = val;
  66729. },
  66730. enumerable: true,
  66731. configurable: true
  66732. });
  66733. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  66734. /**
  66735. * Gets if `setParticles()` computes the particle textures or not.
  66736. * Default value : true. The SPS is faster when it's set to false.
  66737. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  66738. */
  66739. get: function () {
  66740. return this._computeParticleTexture;
  66741. },
  66742. set: function (val) {
  66743. this._computeParticleTexture = val;
  66744. },
  66745. enumerable: true,
  66746. configurable: true
  66747. });
  66748. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  66749. /**
  66750. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  66751. * Default value : false. The SPS is faster when it's set to false.
  66752. * Note : the particle custom vertex positions aren't stored values.
  66753. */
  66754. get: function () {
  66755. return this._computeParticleVertex;
  66756. },
  66757. /**
  66758. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  66759. * Default value : false. The SPS is faster when it's set to false.
  66760. * Note : the particle custom vertex positions aren't stored values.
  66761. */
  66762. set: function (val) {
  66763. this._computeParticleVertex = val;
  66764. },
  66765. enumerable: true,
  66766. configurable: true
  66767. });
  66768. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  66769. /**
  66770. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  66771. */
  66772. get: function () {
  66773. return this._computeBoundingBox;
  66774. },
  66775. /**
  66776. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  66777. */
  66778. set: function (val) {
  66779. this._computeBoundingBox = val;
  66780. },
  66781. enumerable: true,
  66782. configurable: true
  66783. });
  66784. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  66785. /**
  66786. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  66787. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66788. * Default : `true`
  66789. */
  66790. get: function () {
  66791. return this._depthSortParticles;
  66792. },
  66793. /**
  66794. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  66795. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66796. * Default : `true`
  66797. */
  66798. set: function (val) {
  66799. this._depthSortParticles = val;
  66800. },
  66801. enumerable: true,
  66802. configurable: true
  66803. });
  66804. // =======================================================================
  66805. // Particle behavior logic
  66806. // these following methods may be overwritten by the user to fit his needs
  66807. /**
  66808. * This function does nothing. It may be overwritten to set all the particle first values.
  66809. * The SPS doesn't call this function, you may have to call it by your own.
  66810. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66811. */
  66812. SolidParticleSystem.prototype.initParticles = function () {
  66813. };
  66814. /**
  66815. * This function does nothing. It may be overwritten to recycle a particle.
  66816. * The SPS doesn't call this function, you may have to call it by your own.
  66817. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66818. * @param particle The particle to recycle
  66819. * @returns the recycled particle
  66820. */
  66821. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  66822. return particle;
  66823. };
  66824. /**
  66825. * Updates a particle : this function should be overwritten by the user.
  66826. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  66827. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66828. * @example : just set a particle position or velocity and recycle conditions
  66829. * @param particle The particle to update
  66830. * @returns the updated particle
  66831. */
  66832. SolidParticleSystem.prototype.updateParticle = function (particle) {
  66833. return particle;
  66834. };
  66835. /**
  66836. * Updates a vertex of a particle : it can be overwritten by the user.
  66837. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  66838. * @param particle the current particle
  66839. * @param vertex the current index of the current particle
  66840. * @param pt the index of the current vertex in the particle shape
  66841. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  66842. * @example : just set a vertex particle position
  66843. * @returns the updated vertex
  66844. */
  66845. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  66846. return vertex;
  66847. };
  66848. /**
  66849. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  66850. * This does nothing and may be overwritten by the user.
  66851. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66852. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66853. * @param update the boolean update value actually passed to setParticles()
  66854. */
  66855. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  66856. };
  66857. /**
  66858. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  66859. * This will be passed three parameters.
  66860. * This does nothing and may be overwritten by the user.
  66861. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66862. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66863. * @param update the boolean update value actually passed to setParticles()
  66864. */
  66865. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  66866. };
  66867. return SolidParticleSystem;
  66868. }());
  66869. BABYLON.SolidParticleSystem = SolidParticleSystem;
  66870. })(BABYLON || (BABYLON = {}));
  66871. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  66872. var BABYLON;
  66873. (function (BABYLON) {
  66874. /**
  66875. * Class containing static functions to help procedurally build meshes
  66876. */
  66877. var MeshBuilder = /** @class */ (function () {
  66878. function MeshBuilder() {
  66879. }
  66880. MeshBuilder.updateSideOrientation = function (orientation) {
  66881. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  66882. return BABYLON.Mesh.DOUBLESIDE;
  66883. }
  66884. if (orientation === undefined || orientation === null) {
  66885. return BABYLON.Mesh.FRONTSIDE;
  66886. }
  66887. return orientation;
  66888. };
  66889. /**
  66890. * Creates a box mesh
  66891. * * The parameter `size` sets the size (float) of each box side (default 1)
  66892. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  66893. * * 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)
  66894. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66895. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66896. * * 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
  66897. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66898. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  66899. * @param name defines the name of the mesh
  66900. * @param options defines the options used to create the mesh
  66901. * @param scene defines the hosting scene
  66902. * @returns the box mesh
  66903. */
  66904. MeshBuilder.CreateBox = function (name, options, scene) {
  66905. if (scene === void 0) { scene = null; }
  66906. var box = new BABYLON.Mesh(name, scene);
  66907. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66908. box._originalBuilderSideOrientation = options.sideOrientation;
  66909. var vertexData = BABYLON.VertexData.CreateBox(options);
  66910. vertexData.applyToMesh(box, options.updatable);
  66911. return box;
  66912. };
  66913. /**
  66914. * Creates a sphere mesh
  66915. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  66916. * * 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 of `diameter`)
  66917. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  66918. * * 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
  66919. * * 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)
  66920. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66921. * * 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
  66922. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66923. * @param name defines the name of the mesh
  66924. * @param options defines the options used to create the mesh
  66925. * @param scene defines the hosting scene
  66926. * @returns the sphere mesh
  66927. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  66928. */
  66929. MeshBuilder.CreateSphere = function (name, options, scene) {
  66930. var sphere = new BABYLON.Mesh(name, scene);
  66931. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66932. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66933. var vertexData = BABYLON.VertexData.CreateSphere(options);
  66934. vertexData.applyToMesh(sphere, options.updatable);
  66935. return sphere;
  66936. };
  66937. /**
  66938. * Creates a plane polygonal mesh. By default, this is a disc
  66939. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  66940. * * 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
  66941. * * 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
  66942. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66943. * * 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
  66944. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66945. * @param name defines the name of the mesh
  66946. * @param options defines the options used to create the mesh
  66947. * @param scene defines the hosting scene
  66948. * @returns the plane polygonal mesh
  66949. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  66950. */
  66951. MeshBuilder.CreateDisc = function (name, options, scene) {
  66952. if (scene === void 0) { scene = null; }
  66953. var disc = new BABYLON.Mesh(name, scene);
  66954. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66955. disc._originalBuilderSideOrientation = options.sideOrientation;
  66956. var vertexData = BABYLON.VertexData.CreateDisc(options);
  66957. vertexData.applyToMesh(disc, options.updatable);
  66958. return disc;
  66959. };
  66960. /**
  66961. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  66962. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  66963. * * 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 of `radius`)
  66964. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  66965. * * 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
  66966. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66967. * * 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
  66968. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66969. * @param name defines the name of the mesh
  66970. * @param options defines the options used to create the mesh
  66971. * @param scene defines the hosting scene
  66972. * @returns the icosahedron mesh
  66973. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  66974. */
  66975. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  66976. var sphere = new BABYLON.Mesh(name, scene);
  66977. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66978. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66979. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  66980. vertexData.applyToMesh(sphere, options.updatable);
  66981. return sphere;
  66982. };
  66983. ;
  66984. /**
  66985. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66986. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  66987. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  66988. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  66989. * * 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
  66990. * * 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
  66991. * * 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
  66992. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66993. * * 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
  66994. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66995. * * 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
  66996. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  66997. * * 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
  66998. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  66999. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67000. * @param name defines the name of the mesh
  67001. * @param options defines the options used to create the mesh
  67002. * @param scene defines the hosting scene
  67003. * @returns the ribbon mesh
  67004. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  67005. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67006. */
  67007. MeshBuilder.CreateRibbon = function (name, options, scene) {
  67008. if (scene === void 0) { scene = null; }
  67009. var pathArray = options.pathArray;
  67010. var closeArray = options.closeArray;
  67011. var closePath = options.closePath;
  67012. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67013. var instance = options.instance;
  67014. var updatable = options.updatable;
  67015. if (instance) { // existing ribbon instance update
  67016. // positionFunction : ribbon case
  67017. // only pathArray and sideOrientation parameters are taken into account for positions update
  67018. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  67019. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  67020. var positionFunction = function (positions) {
  67021. var minlg = pathArray[0].length;
  67022. var mesh = instance;
  67023. var i = 0;
  67024. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  67025. for (var si = 1; si <= ns; si++) {
  67026. for (var p = 0; p < pathArray.length; p++) {
  67027. var path = pathArray[p];
  67028. var l = path.length;
  67029. minlg = (minlg < l) ? minlg : l;
  67030. var j = 0;
  67031. while (j < minlg) {
  67032. positions[i] = path[j].x;
  67033. positions[i + 1] = path[j].y;
  67034. positions[i + 2] = path[j].z;
  67035. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  67036. BABYLON.Tmp.Vector3[0].x = path[j].x;
  67037. }
  67038. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  67039. BABYLON.Tmp.Vector3[1].x = path[j].x;
  67040. }
  67041. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  67042. BABYLON.Tmp.Vector3[0].y = path[j].y;
  67043. }
  67044. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  67045. BABYLON.Tmp.Vector3[1].y = path[j].y;
  67046. }
  67047. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  67048. BABYLON.Tmp.Vector3[0].z = path[j].z;
  67049. }
  67050. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  67051. BABYLON.Tmp.Vector3[1].z = path[j].z;
  67052. }
  67053. j++;
  67054. i += 3;
  67055. }
  67056. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  67057. positions[i] = path[0].x;
  67058. positions[i + 1] = path[0].y;
  67059. positions[i + 2] = path[0].z;
  67060. i += 3;
  67061. }
  67062. }
  67063. }
  67064. };
  67065. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67066. positionFunction(positions);
  67067. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  67068. instance._boundingInfo.update(instance._worldMatrix);
  67069. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67070. if (options.colors) {
  67071. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67072. for (var c = 0; c < options.colors.length; c++) {
  67073. colors[c * 4] = options.colors[c].r;
  67074. colors[c * 4 + 1] = options.colors[c].g;
  67075. colors[c * 4 + 2] = options.colors[c].b;
  67076. colors[c * 4 + 3] = options.colors[c].a;
  67077. }
  67078. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  67079. }
  67080. if (options.uvs) {
  67081. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67082. for (var i = 0; i < options.uvs.length; i++) {
  67083. uvs[i * 2] = options.uvs[i].x;
  67084. uvs[i * 2 + 1] = options.uvs[i].y;
  67085. }
  67086. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  67087. }
  67088. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  67089. var indices = instance.getIndices();
  67090. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67091. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  67092. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  67093. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  67094. var indexFirst = 0;
  67095. var indexLast = 0;
  67096. for (var p = 0; p < pathArray.length; p++) {
  67097. indexFirst = instance._creationDataStorage.idx[p] * 3;
  67098. if (p + 1 < pathArray.length) {
  67099. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  67100. }
  67101. else {
  67102. indexLast = normals.length - 3;
  67103. }
  67104. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  67105. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  67106. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  67107. normals[indexLast] = normals[indexFirst];
  67108. normals[indexLast + 1] = normals[indexFirst + 1];
  67109. normals[indexLast + 2] = normals[indexFirst + 2];
  67110. }
  67111. }
  67112. if (!(instance.areNormalsFrozen)) {
  67113. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  67114. }
  67115. }
  67116. return instance;
  67117. }
  67118. else { // new ribbon creation
  67119. var ribbon = new BABYLON.Mesh(name, scene);
  67120. ribbon._originalBuilderSideOrientation = sideOrientation;
  67121. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  67122. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  67123. if (closePath) {
  67124. ribbon._creationDataStorage.idx = vertexData._idx;
  67125. }
  67126. ribbon._creationDataStorage.closePath = closePath;
  67127. ribbon._closeArray = closeArray;
  67128. vertexData.applyToMesh(ribbon, updatable);
  67129. return ribbon;
  67130. }
  67131. };
  67132. /**
  67133. * Creates a cylinder or a cone mesh
  67134. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  67135. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  67136. * * 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.
  67137. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  67138. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  67139. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  67140. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  67141. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  67142. * * 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).
  67143. * * 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
  67144. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  67145. * * 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
  67146. * * 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.
  67147. * * If `enclose` is false, a ring surface is one element.
  67148. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  67149. * * 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
  67150. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67151. * * 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
  67152. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67153. * @param name defines the name of the mesh
  67154. * @param options defines the options used to create the mesh
  67155. * @param scene defines the hosting scene
  67156. * @returns the cylinder mesh
  67157. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  67158. */
  67159. MeshBuilder.CreateCylinder = function (name, options, scene) {
  67160. var cylinder = new BABYLON.Mesh(name, scene);
  67161. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67162. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  67163. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  67164. vertexData.applyToMesh(cylinder, options.updatable);
  67165. return cylinder;
  67166. };
  67167. /**
  67168. * Creates a torus mesh
  67169. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  67170. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  67171. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  67172. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67173. * * 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
  67174. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67175. * @param name defines the name of the mesh
  67176. * @param options defines the options used to create the mesh
  67177. * @param scene defines the hosting scene
  67178. * @returns the torus mesh
  67179. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  67180. */
  67181. MeshBuilder.CreateTorus = function (name, options, scene) {
  67182. var torus = new BABYLON.Mesh(name, scene);
  67183. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67184. torus._originalBuilderSideOrientation = options.sideOrientation;
  67185. var vertexData = BABYLON.VertexData.CreateTorus(options);
  67186. vertexData.applyToMesh(torus, options.updatable);
  67187. return torus;
  67188. };
  67189. /**
  67190. * Creates a torus knot mesh
  67191. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  67192. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  67193. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  67194. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  67195. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67196. * * 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
  67197. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67198. * @param name defines the name of the mesh
  67199. * @param options defines the options used to create the mesh
  67200. * @param scene defines the hosting scene
  67201. * @returns the torus knot mesh
  67202. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  67203. */
  67204. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  67205. var torusKnot = new BABYLON.Mesh(name, scene);
  67206. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67207. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  67208. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  67209. vertexData.applyToMesh(torusKnot, options.updatable);
  67210. return torusKnot;
  67211. };
  67212. /**
  67213. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  67214. * * 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
  67215. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  67216. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  67217. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  67218. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  67219. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  67220. * * 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
  67221. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  67222. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67223. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  67224. * @param name defines the name of the new line system
  67225. * @param options defines the options used to create the line system
  67226. * @param scene defines the hosting scene
  67227. * @returns a new line system mesh
  67228. */
  67229. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  67230. var instance = options.instance;
  67231. var lines = options.lines;
  67232. var colors = options.colors;
  67233. if (instance) { // lines update
  67234. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67235. var vertexColor;
  67236. var lineColors;
  67237. if (colors) {
  67238. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67239. }
  67240. var i = 0;
  67241. var c = 0;
  67242. for (var l = 0; l < lines.length; l++) {
  67243. var points = lines[l];
  67244. for (var p = 0; p < points.length; p++) {
  67245. positions[i] = points[p].x;
  67246. positions[i + 1] = points[p].y;
  67247. positions[i + 2] = points[p].z;
  67248. if (colors && vertexColor) {
  67249. lineColors = colors[l];
  67250. vertexColor[c] = lineColors[p].r;
  67251. vertexColor[c + 1] = lineColors[p].g;
  67252. vertexColor[c + 2] = lineColors[p].b;
  67253. vertexColor[c + 3] = lineColors[p].a;
  67254. c += 4;
  67255. }
  67256. i += 3;
  67257. }
  67258. }
  67259. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67260. if (colors && vertexColor) {
  67261. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  67262. }
  67263. return instance;
  67264. }
  67265. // line system creation
  67266. var useVertexColor = (colors) ? true : false;
  67267. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  67268. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  67269. vertexData.applyToMesh(lineSystem, options.updatable);
  67270. return lineSystem;
  67271. };
  67272. /**
  67273. * Creates a line mesh
  67274. * 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
  67275. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67276. * * The parameter `points` is an array successive Vector3
  67277. * * 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
  67278. * * The optional parameter `colors` is an array of successive Color4, one per line point
  67279. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  67280. * * When updating an instance, remember that only point positions can change, not the number of points
  67281. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67282. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  67283. * @param name defines the name of the new line system
  67284. * @param options defines the options used to create the line system
  67285. * @param scene defines the hosting scene
  67286. * @returns a new line mesh
  67287. */
  67288. MeshBuilder.CreateLines = function (name, options, scene) {
  67289. if (scene === void 0) { scene = null; }
  67290. var colors = (options.colors) ? [options.colors] : null;
  67291. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  67292. return lines;
  67293. };
  67294. /**
  67295. * Creates a dashed line mesh
  67296. * * 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
  67297. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67298. * * The parameter `points` is an array successive Vector3
  67299. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  67300. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  67301. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  67302. * * 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
  67303. * * When updating an instance, remember that only point positions can change, not the number of points
  67304. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67305. * @param name defines the name of the mesh
  67306. * @param options defines the options used to create the mesh
  67307. * @param scene defines the hosting scene
  67308. * @returns the dashed line mesh
  67309. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  67310. */
  67311. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  67312. if (scene === void 0) { scene = null; }
  67313. var points = options.points;
  67314. var instance = options.instance;
  67315. var gapSize = options.gapSize || 1;
  67316. var dashSize = options.dashSize || 3;
  67317. if (instance) { // dashed lines update
  67318. var positionFunction = function (positions) {
  67319. var curvect = BABYLON.Vector3.Zero();
  67320. var nbSeg = positions.length / 6;
  67321. var lg = 0;
  67322. var nb = 0;
  67323. var shft = 0;
  67324. var dashshft = 0;
  67325. var curshft = 0;
  67326. var p = 0;
  67327. var i = 0;
  67328. var j = 0;
  67329. for (i = 0; i < points.length - 1; i++) {
  67330. points[i + 1].subtractToRef(points[i], curvect);
  67331. lg += curvect.length();
  67332. }
  67333. shft = lg / nbSeg;
  67334. var dashSize = instance._creationDataStorage.dashSize;
  67335. var gapSize = instance._creationDataStorage.gapSize;
  67336. dashshft = dashSize * shft / (dashSize + gapSize);
  67337. for (i = 0; i < points.length - 1; i++) {
  67338. points[i + 1].subtractToRef(points[i], curvect);
  67339. nb = Math.floor(curvect.length() / shft);
  67340. curvect.normalize();
  67341. j = 0;
  67342. while (j < nb && p < positions.length) {
  67343. curshft = shft * j;
  67344. positions[p] = points[i].x + curshft * curvect.x;
  67345. positions[p + 1] = points[i].y + curshft * curvect.y;
  67346. positions[p + 2] = points[i].z + curshft * curvect.z;
  67347. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  67348. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  67349. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  67350. p += 6;
  67351. j++;
  67352. }
  67353. }
  67354. while (p < positions.length) {
  67355. positions[p] = points[i].x;
  67356. positions[p + 1] = points[i].y;
  67357. positions[p + 2] = points[i].z;
  67358. p += 3;
  67359. }
  67360. };
  67361. instance.updateMeshPositions(positionFunction, false);
  67362. return instance;
  67363. }
  67364. // dashed lines creation
  67365. var dashedLines = new BABYLON.LinesMesh(name, scene);
  67366. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  67367. vertexData.applyToMesh(dashedLines, options.updatable);
  67368. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  67369. dashedLines._creationDataStorage.dashSize = dashSize;
  67370. dashedLines._creationDataStorage.gapSize = gapSize;
  67371. return dashedLines;
  67372. };
  67373. /**
  67374. * 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.
  67375. * * 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.
  67376. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67377. * * 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.
  67378. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  67379. * * 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
  67380. * * 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
  67381. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  67382. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67383. * * 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
  67384. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  67385. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67386. * @param name defines the name of the mesh
  67387. * @param options defines the options used to create the mesh
  67388. * @param scene defines the hosting scene
  67389. * @returns the extruded shape mesh
  67390. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67391. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67392. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67393. */
  67394. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  67395. if (scene === void 0) { scene = null; }
  67396. var path = options.path;
  67397. var shape = options.shape;
  67398. var scale = options.scale || 1;
  67399. var rotation = options.rotation || 0;
  67400. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67401. var updatable = options.updatable;
  67402. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67403. var instance = options.instance || null;
  67404. var invertUV = options.invertUV || false;
  67405. 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);
  67406. };
  67407. /**
  67408. * Creates an custom extruded shape mesh.
  67409. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  67410. * * 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.
  67411. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67412. * * 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
  67413. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  67414. * * 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
  67415. * * It must returns a float value that will be the scale value applied to the shape on each path point
  67416. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  67417. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  67418. * * 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
  67419. * * 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
  67420. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  67421. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67422. * * 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
  67423. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67424. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67425. * @param name defines the name of the mesh
  67426. * @param options defines the options used to create the mesh
  67427. * @param scene defines the hosting scene
  67428. * @returns the custom extruded shape mesh
  67429. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  67430. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67431. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67432. */
  67433. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  67434. var path = options.path;
  67435. var shape = options.shape;
  67436. var scaleFunction = options.scaleFunction || (function () { return 1; });
  67437. var rotationFunction = options.rotationFunction || (function () { return 0; });
  67438. var ribbonCloseArray = options.ribbonCloseArray || false;
  67439. var ribbonClosePath = options.ribbonClosePath || false;
  67440. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67441. var updatable = options.updatable;
  67442. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67443. var instance = options.instance;
  67444. var invertUV = options.invertUV || false;
  67445. 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);
  67446. };
  67447. /**
  67448. * Creates lathe mesh.
  67449. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  67450. * * 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
  67451. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  67452. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  67453. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  67454. * * 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
  67455. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  67456. * * 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
  67457. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67458. * * 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
  67459. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67460. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67461. * @param name defines the name of the mesh
  67462. * @param options defines the options used to create the mesh
  67463. * @param scene defines the hosting scene
  67464. * @returns the lathe mesh
  67465. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  67466. */
  67467. MeshBuilder.CreateLathe = function (name, options, scene) {
  67468. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  67469. var closed = (options.closed === undefined) ? true : options.closed;
  67470. var shape = options.shape;
  67471. var radius = options.radius || 1;
  67472. var tessellation = options.tessellation || 64;
  67473. var clip = options.clip || 0;
  67474. var updatable = options.updatable;
  67475. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67476. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67477. var pi2 = Math.PI * 2;
  67478. var paths = new Array();
  67479. var invertUV = options.invertUV || false;
  67480. var i = 0;
  67481. var p = 0;
  67482. var step = pi2 / tessellation * arc;
  67483. var rotated;
  67484. var path = new Array();
  67485. for (i = 0; i <= tessellation - clip; i++) {
  67486. var path = [];
  67487. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  67488. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  67489. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  67490. }
  67491. for (p = 0; p < shape.length; p++) {
  67492. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  67493. path.push(rotated);
  67494. }
  67495. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  67496. 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));
  67497. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  67498. }
  67499. paths.push(path);
  67500. }
  67501. // lathe ribbon
  67502. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67503. return lathe;
  67504. };
  67505. /**
  67506. * Creates a plane mesh
  67507. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  67508. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  67509. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  67510. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67511. * * 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
  67512. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67513. * @param name defines the name of the mesh
  67514. * @param options defines the options used to create the mesh
  67515. * @param scene defines the hosting scene
  67516. * @returns the plane mesh
  67517. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67518. */
  67519. MeshBuilder.CreatePlane = function (name, options, scene) {
  67520. var plane = new BABYLON.Mesh(name, scene);
  67521. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67522. plane._originalBuilderSideOrientation = options.sideOrientation;
  67523. var vertexData = BABYLON.VertexData.CreatePlane(options);
  67524. vertexData.applyToMesh(plane, options.updatable);
  67525. if (options.sourcePlane) {
  67526. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  67527. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  67528. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  67529. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  67530. plane.rotate(vectorProduct, product);
  67531. }
  67532. }
  67533. return plane;
  67534. };
  67535. /**
  67536. * Creates a ground mesh
  67537. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  67538. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  67539. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67540. * @param name defines the name of the mesh
  67541. * @param options defines the options used to create the mesh
  67542. * @param scene defines the hosting scene
  67543. * @returns the ground mesh
  67544. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67545. */
  67546. MeshBuilder.CreateGround = function (name, options, scene) {
  67547. var ground = new BABYLON.GroundMesh(name, scene);
  67548. ground._setReady(false);
  67549. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  67550. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  67551. ground._width = options.width || 1;
  67552. ground._height = options.height || 1;
  67553. ground._maxX = ground._width / 2;
  67554. ground._maxZ = ground._height / 2;
  67555. ground._minX = -ground._maxX;
  67556. ground._minZ = -ground._maxZ;
  67557. var vertexData = BABYLON.VertexData.CreateGround(options);
  67558. vertexData.applyToMesh(ground, options.updatable);
  67559. ground._setReady(true);
  67560. return ground;
  67561. };
  67562. /**
  67563. * Creates a tiled ground mesh
  67564. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  67565. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  67566. * * 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
  67567. * * 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
  67568. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67569. * @param name defines the name of the mesh
  67570. * @param options defines the options used to create the mesh
  67571. * @param scene defines the hosting scene
  67572. * @returns the tiled ground mesh
  67573. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  67574. */
  67575. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  67576. var tiledGround = new BABYLON.Mesh(name, scene);
  67577. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  67578. vertexData.applyToMesh(tiledGround, options.updatable);
  67579. return tiledGround;
  67580. };
  67581. /**
  67582. * Creates a ground mesh from a height map
  67583. * * The parameter `url` sets the URL of the height map image resource.
  67584. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  67585. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  67586. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  67587. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  67588. * * 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.
  67589. * * 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).
  67590. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  67591. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67592. * @param name defines the name of the mesh
  67593. * @param url defines the url to the height map
  67594. * @param options defines the options used to create the mesh
  67595. * @param scene defines the hosting scene
  67596. * @returns the ground mesh
  67597. * @see http://doc.babylonjs.com/babylon101/height_map
  67598. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  67599. */
  67600. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  67601. var width = options.width || 10.0;
  67602. var height = options.height || 10.0;
  67603. var subdivisions = options.subdivisions || 1 | 0;
  67604. var minHeight = options.minHeight || 0.0;
  67605. var maxHeight = options.maxHeight || 1.0;
  67606. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  67607. var alphaFilter = options.alphaFilter || 0.0;
  67608. var updatable = options.updatable;
  67609. var onReady = options.onReady;
  67610. var ground = new BABYLON.GroundMesh(name, scene);
  67611. ground._subdivisionsX = subdivisions;
  67612. ground._subdivisionsY = subdivisions;
  67613. ground._width = width;
  67614. ground._height = height;
  67615. ground._maxX = ground._width / 2.0;
  67616. ground._maxZ = ground._height / 2.0;
  67617. ground._minX = -ground._maxX;
  67618. ground._minZ = -ground._maxZ;
  67619. ground._setReady(false);
  67620. var onload = function (img) {
  67621. // Getting height map data
  67622. var canvas = document.createElement("canvas");
  67623. var context = canvas.getContext("2d");
  67624. if (!context) {
  67625. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  67626. }
  67627. if (scene.isDisposed) {
  67628. return;
  67629. }
  67630. var bufferWidth = img.width;
  67631. var bufferHeight = img.height;
  67632. canvas.width = bufferWidth;
  67633. canvas.height = bufferHeight;
  67634. context.drawImage(img, 0, 0);
  67635. // Create VertexData from map data
  67636. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  67637. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  67638. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  67639. width: width, height: height,
  67640. subdivisions: subdivisions,
  67641. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  67642. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  67643. alphaFilter: alphaFilter
  67644. });
  67645. vertexData.applyToMesh(ground, updatable);
  67646. //execute ready callback, if set
  67647. if (onReady) {
  67648. onReady(ground);
  67649. }
  67650. ground._setReady(true);
  67651. };
  67652. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  67653. return ground;
  67654. };
  67655. /**
  67656. * Creates a polygon mesh
  67657. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  67658. * * 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
  67659. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67660. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67661. * * 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)
  67662. * * Remember you can only change the shape positions, not their number when updating a polygon
  67663. * @param name defines the name of the mesh
  67664. * @param options defines the options used to create the mesh
  67665. * @param scene defines the hosting scene
  67666. * @returns the polygon mesh
  67667. */
  67668. MeshBuilder.CreatePolygon = function (name, options, scene) {
  67669. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67670. var shape = options.shape;
  67671. var holes = options.holes || [];
  67672. var depth = options.depth || 0;
  67673. var contours = [];
  67674. var hole = [];
  67675. for (var i = 0; i < shape.length; i++) {
  67676. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  67677. }
  67678. var epsilon = 0.00000001;
  67679. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  67680. contours.pop();
  67681. }
  67682. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  67683. for (var hNb = 0; hNb < holes.length; hNb++) {
  67684. hole = [];
  67685. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  67686. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  67687. }
  67688. polygonTriangulation.addHole(hole);
  67689. }
  67690. var polygon = polygonTriangulation.build(options.updatable, depth);
  67691. polygon._originalBuilderSideOrientation = options.sideOrientation;
  67692. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  67693. vertexData.applyToMesh(polygon, options.updatable);
  67694. return polygon;
  67695. };
  67696. ;
  67697. /**
  67698. * Creates an extruded polygon mesh, with depth in the Y direction.
  67699. * * 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)
  67700. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67701. * @param name defines the name of the mesh
  67702. * @param options defines the options used to create the mesh
  67703. * @param scene defines the hosting scene
  67704. * @returns the polygon mesh
  67705. */
  67706. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  67707. return MeshBuilder.CreatePolygon(name, options, scene);
  67708. };
  67709. ;
  67710. /**
  67711. * Creates a tube mesh.
  67712. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67713. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  67714. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  67715. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  67716. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  67717. * * 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)
  67718. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  67719. * * 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
  67720. * * 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
  67721. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67722. * * 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
  67723. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67724. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67725. * @param name defines the name of the mesh
  67726. * @param options defines the options used to create the mesh
  67727. * @param scene defines the hosting scene
  67728. * @returns the tube mesh
  67729. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67730. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  67731. */
  67732. MeshBuilder.CreateTube = function (name, options, scene) {
  67733. var path = options.path;
  67734. var instance = options.instance;
  67735. var radius = 1.0;
  67736. if (options.radius !== undefined) {
  67737. radius = options.radius;
  67738. }
  67739. else if (instance) {
  67740. radius = instance._creationDataStorage.radius;
  67741. }
  67742. var tessellation = options.tessellation || 64 | 0;
  67743. var radiusFunction = options.radiusFunction || null;
  67744. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67745. var invertUV = options.invertUV || false;
  67746. var updatable = options.updatable;
  67747. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67748. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  67749. // tube geometry
  67750. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  67751. var tangents = path3D.getTangents();
  67752. var normals = path3D.getNormals();
  67753. var distances = path3D.getDistances();
  67754. var pi2 = Math.PI * 2;
  67755. var step = pi2 / tessellation * arc;
  67756. var returnRadius = function () { return radius; };
  67757. var radiusFunctionFinal = radiusFunction || returnRadius;
  67758. var circlePath;
  67759. var rad;
  67760. var normal;
  67761. var rotated;
  67762. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67763. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67764. for (var i = 0; i < path.length; i++) {
  67765. rad = radiusFunctionFinal(i, distances[i]); // current radius
  67766. circlePath = Array(); // current circle array
  67767. normal = normals[i]; // current normal
  67768. for (var t = 0; t < tessellation; t++) {
  67769. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  67770. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  67771. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  67772. rotated.scaleInPlace(rad).addInPlace(path[i]);
  67773. circlePath[t] = rotated;
  67774. }
  67775. circlePaths[index] = circlePath;
  67776. index++;
  67777. }
  67778. // cap
  67779. var capPath = function (nbPoints, pathIndex) {
  67780. var pointCap = Array();
  67781. for (var i = 0; i < nbPoints; i++) {
  67782. pointCap.push(path[pathIndex]);
  67783. }
  67784. return pointCap;
  67785. };
  67786. switch (cap) {
  67787. case BABYLON.Mesh.NO_CAP:
  67788. break;
  67789. case BABYLON.Mesh.CAP_START:
  67790. circlePaths[0] = capPath(tessellation, 0);
  67791. circlePaths[1] = circlePaths[2].slice(0);
  67792. break;
  67793. case BABYLON.Mesh.CAP_END:
  67794. circlePaths[index] = circlePaths[index - 1].slice(0);
  67795. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67796. break;
  67797. case BABYLON.Mesh.CAP_ALL:
  67798. circlePaths[0] = capPath(tessellation, 0);
  67799. circlePaths[1] = circlePaths[2].slice(0);
  67800. circlePaths[index] = circlePaths[index - 1].slice(0);
  67801. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67802. break;
  67803. default:
  67804. break;
  67805. }
  67806. return circlePaths;
  67807. };
  67808. var path3D;
  67809. var pathArray;
  67810. if (instance) { // tube update
  67811. var arc = options.arc || instance.arc;
  67812. var storage = instance._creationDataStorage;
  67813. path3D = storage.path3D.update(path);
  67814. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  67815. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  67816. // Update mode, no need to recreate the storage.
  67817. storage.path3D = path3D;
  67818. storage.pathArray = pathArray;
  67819. storage.arc = arc;
  67820. storage.radius = radius;
  67821. return instance;
  67822. }
  67823. // tube creation
  67824. path3D = new BABYLON.Path3D(path);
  67825. var newPathArray = new Array();
  67826. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67827. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  67828. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67829. tube._creationDataStorage = new BABYLON._CreationDataStorage();
  67830. tube._creationDataStorage.pathArray = pathArray;
  67831. tube._creationDataStorage.path3D = path3D;
  67832. tube._creationDataStorage.tessellation = tessellation;
  67833. tube._creationDataStorage.cap = cap;
  67834. tube._creationDataStorage.arc = options.arc;
  67835. tube._creationDataStorage.radius = radius;
  67836. return tube;
  67837. };
  67838. /**
  67839. * Creates a polyhedron mesh
  67840. * * 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
  67841. * * The parameter `size` (positive float, default 1) sets the polygon size
  67842. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  67843. * * 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`
  67844. * * 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
  67845. * * 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)`)
  67846. * * 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
  67847. * * 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
  67848. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67849. * * 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
  67850. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67851. * @param name defines the name of the mesh
  67852. * @param options defines the options used to create the mesh
  67853. * @param scene defines the hosting scene
  67854. * @returns the polyhedron mesh
  67855. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  67856. */
  67857. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  67858. var polyhedron = new BABYLON.Mesh(name, scene);
  67859. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67860. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  67861. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  67862. vertexData.applyToMesh(polyhedron, options.updatable);
  67863. return polyhedron;
  67864. };
  67865. /**
  67866. * Creates a decal mesh.
  67867. * 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
  67868. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  67869. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  67870. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  67871. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  67872. * @param name defines the name of the mesh
  67873. * @param sourceMesh defines the mesh where the decal must be applied
  67874. * @param options defines the options used to create the mesh
  67875. * @param scene defines the hosting scene
  67876. * @returns the decal mesh
  67877. * @see http://doc.babylonjs.com/how_to/decals
  67878. */
  67879. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  67880. var indices = sourceMesh.getIndices();
  67881. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67882. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67883. var position = options.position || BABYLON.Vector3.Zero();
  67884. var normal = options.normal || BABYLON.Vector3.Up();
  67885. var size = options.size || BABYLON.Vector3.One();
  67886. var angle = options.angle || 0;
  67887. // Getting correct rotation
  67888. if (!normal) {
  67889. var target = new BABYLON.Vector3(0, 0, 1);
  67890. var camera = sourceMesh.getScene().activeCamera;
  67891. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  67892. normal = camera.globalPosition.subtract(cameraWorldTarget);
  67893. }
  67894. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  67895. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  67896. var pitch = Math.atan2(normal.y, len);
  67897. // Matrix
  67898. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  67899. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  67900. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  67901. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  67902. var vertexData = new BABYLON.VertexData();
  67903. vertexData.indices = [];
  67904. vertexData.positions = [];
  67905. vertexData.normals = [];
  67906. vertexData.uvs = [];
  67907. var currentVertexDataIndex = 0;
  67908. var extractDecalVector3 = function (indexId) {
  67909. var result = new BABYLON.PositionNormalVertex();
  67910. if (!indices || !positions || !normals) {
  67911. return result;
  67912. }
  67913. var vertexId = indices[indexId];
  67914. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  67915. // Send vector to decal local world
  67916. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  67917. // Get normal
  67918. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  67919. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  67920. return result;
  67921. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  67922. var clip = function (vertices, axis) {
  67923. if (vertices.length === 0) {
  67924. return vertices;
  67925. }
  67926. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  67927. var clipVertices = function (v0, v1) {
  67928. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  67929. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  67930. };
  67931. var result = new Array();
  67932. for (var index = 0; index < vertices.length; index += 3) {
  67933. var v1Out;
  67934. var v2Out;
  67935. var v3Out;
  67936. var total = 0;
  67937. var nV1 = null;
  67938. var nV2 = null;
  67939. var nV3 = null;
  67940. var nV4 = null;
  67941. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  67942. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  67943. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  67944. v1Out = d1 > 0;
  67945. v2Out = d2 > 0;
  67946. v3Out = d3 > 0;
  67947. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  67948. switch (total) {
  67949. case 0:
  67950. result.push(vertices[index]);
  67951. result.push(vertices[index + 1]);
  67952. result.push(vertices[index + 2]);
  67953. break;
  67954. case 1:
  67955. if (v1Out) {
  67956. nV1 = vertices[index + 1];
  67957. nV2 = vertices[index + 2];
  67958. nV3 = clipVertices(vertices[index], nV1);
  67959. nV4 = clipVertices(vertices[index], nV2);
  67960. }
  67961. if (v2Out) {
  67962. nV1 = vertices[index];
  67963. nV2 = vertices[index + 2];
  67964. nV3 = clipVertices(vertices[index + 1], nV1);
  67965. nV4 = clipVertices(vertices[index + 1], nV2);
  67966. result.push(nV3);
  67967. result.push(nV2.clone());
  67968. result.push(nV1.clone());
  67969. result.push(nV2.clone());
  67970. result.push(nV3.clone());
  67971. result.push(nV4);
  67972. break;
  67973. }
  67974. if (v3Out) {
  67975. nV1 = vertices[index];
  67976. nV2 = vertices[index + 1];
  67977. nV3 = clipVertices(vertices[index + 2], nV1);
  67978. nV4 = clipVertices(vertices[index + 2], nV2);
  67979. }
  67980. if (nV1 && nV2 && nV3 && nV4) {
  67981. result.push(nV1.clone());
  67982. result.push(nV2.clone());
  67983. result.push(nV3);
  67984. result.push(nV4);
  67985. result.push(nV3.clone());
  67986. result.push(nV2.clone());
  67987. }
  67988. break;
  67989. case 2:
  67990. if (!v1Out) {
  67991. nV1 = vertices[index].clone();
  67992. nV2 = clipVertices(nV1, vertices[index + 1]);
  67993. nV3 = clipVertices(nV1, vertices[index + 2]);
  67994. result.push(nV1);
  67995. result.push(nV2);
  67996. result.push(nV3);
  67997. }
  67998. if (!v2Out) {
  67999. nV1 = vertices[index + 1].clone();
  68000. nV2 = clipVertices(nV1, vertices[index + 2]);
  68001. nV3 = clipVertices(nV1, vertices[index]);
  68002. result.push(nV1);
  68003. result.push(nV2);
  68004. result.push(nV3);
  68005. }
  68006. if (!v3Out) {
  68007. nV1 = vertices[index + 2].clone();
  68008. nV2 = clipVertices(nV1, vertices[index]);
  68009. nV3 = clipVertices(nV1, vertices[index + 1]);
  68010. result.push(nV1);
  68011. result.push(nV2);
  68012. result.push(nV3);
  68013. }
  68014. break;
  68015. case 3:
  68016. break;
  68017. }
  68018. }
  68019. return result;
  68020. };
  68021. for (var index = 0; index < indices.length; index += 3) {
  68022. var faceVertices = new Array();
  68023. faceVertices.push(extractDecalVector3(index));
  68024. faceVertices.push(extractDecalVector3(index + 1));
  68025. faceVertices.push(extractDecalVector3(index + 2));
  68026. // Clip
  68027. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  68028. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  68029. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  68030. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  68031. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  68032. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  68033. if (faceVertices.length === 0) {
  68034. continue;
  68035. }
  68036. // Add UVs and get back to world
  68037. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  68038. var vertex = faceVertices[vIndex];
  68039. //TODO check for Int32Array | Uint32Array | Uint16Array
  68040. vertexData.indices.push(currentVertexDataIndex);
  68041. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  68042. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  68043. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  68044. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  68045. currentVertexDataIndex++;
  68046. }
  68047. }
  68048. // Return mesh
  68049. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  68050. vertexData.applyToMesh(decal);
  68051. decal.position = position.clone();
  68052. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  68053. return decal;
  68054. };
  68055. // Privates
  68056. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  68057. // extrusion geometry
  68058. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  68059. var tangents = path3D.getTangents();
  68060. var normals = path3D.getNormals();
  68061. var binormals = path3D.getBinormals();
  68062. var distances = path3D.getDistances();
  68063. var angle = 0;
  68064. var returnScale = function () { return scale !== null ? scale : 1; };
  68065. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  68066. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  68067. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  68068. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68069. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68070. for (var i = 0; i < curve.length; i++) {
  68071. var shapePath = new Array();
  68072. var angleStep = rotate(i, distances[i]);
  68073. var scaleRatio = scl(i, distances[i]);
  68074. for (var p = 0; p < shape.length; p++) {
  68075. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  68076. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  68077. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  68078. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  68079. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  68080. shapePath[p] = rotated;
  68081. }
  68082. shapePaths[index] = shapePath;
  68083. angle += angleStep;
  68084. index++;
  68085. }
  68086. // cap
  68087. var capPath = function (shapePath) {
  68088. var pointCap = Array();
  68089. var barycenter = BABYLON.Vector3.Zero();
  68090. var i;
  68091. for (i = 0; i < shapePath.length; i++) {
  68092. barycenter.addInPlace(shapePath[i]);
  68093. }
  68094. barycenter.scaleInPlace(1.0 / shapePath.length);
  68095. for (i = 0; i < shapePath.length; i++) {
  68096. pointCap.push(barycenter);
  68097. }
  68098. return pointCap;
  68099. };
  68100. switch (cap) {
  68101. case BABYLON.Mesh.NO_CAP:
  68102. break;
  68103. case BABYLON.Mesh.CAP_START:
  68104. shapePaths[0] = capPath(shapePaths[2]);
  68105. shapePaths[1] = shapePaths[2];
  68106. break;
  68107. case BABYLON.Mesh.CAP_END:
  68108. shapePaths[index] = shapePaths[index - 1];
  68109. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68110. break;
  68111. case BABYLON.Mesh.CAP_ALL:
  68112. shapePaths[0] = capPath(shapePaths[2]);
  68113. shapePaths[1] = shapePaths[2];
  68114. shapePaths[index] = shapePaths[index - 1];
  68115. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68116. break;
  68117. default:
  68118. break;
  68119. }
  68120. return shapePaths;
  68121. };
  68122. var path3D;
  68123. var pathArray;
  68124. if (instance) { // instance update
  68125. var storage = instance._creationDataStorage;
  68126. path3D = storage.path3D.update(curve);
  68127. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  68128. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  68129. return instance;
  68130. }
  68131. // extruded shape creation
  68132. path3D = new BABYLON.Path3D(curve);
  68133. var newShapePaths = new Array();
  68134. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68135. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  68136. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  68137. extrudedGeneric._creationDataStorage = new BABYLON._CreationDataStorage();
  68138. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  68139. extrudedGeneric._creationDataStorage.path3D = path3D;
  68140. extrudedGeneric._creationDataStorage.cap = cap;
  68141. return extrudedGeneric;
  68142. };
  68143. return MeshBuilder;
  68144. }());
  68145. BABYLON.MeshBuilder = MeshBuilder;
  68146. })(BABYLON || (BABYLON = {}));
  68147. //# sourceMappingURL=babylon.meshBuilder.js.map
  68148. var BABYLON;
  68149. (function (BABYLON) {
  68150. /**
  68151. * Draco compression (https://google.github.io/draco/)
  68152. *
  68153. * This class wraps the Draco module.
  68154. *
  68155. * **Encoder**
  68156. *
  68157. * The encoder is not currently implemented.
  68158. *
  68159. * **Decoder**
  68160. *
  68161. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  68162. *
  68163. * To update the configuration, use the following code:
  68164. * ```javascript
  68165. * BABYLON.DracoCompression.Configuration = {
  68166. * decoder: {
  68167. * wasmUrl: "<url to the WebAssembly library>",
  68168. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  68169. * fallbackUrl: "<url to the fallback JavaScript library>",
  68170. * }
  68171. * };
  68172. * ```
  68173. *
  68174. * 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.
  68175. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  68176. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  68177. *
  68178. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  68179. * ```javascript
  68180. * var dracoCompression = new BABYLON.DracoCompression();
  68181. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  68182. * [BABYLON.VertexBuffer.PositionKind]: 0
  68183. * });
  68184. * ```
  68185. *
  68186. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  68187. */
  68188. var DracoCompression = /** @class */ (function () {
  68189. /**
  68190. * Constructor
  68191. */
  68192. function DracoCompression() {
  68193. }
  68194. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  68195. /**
  68196. * Returns true if the decoder is available.
  68197. */
  68198. get: function () {
  68199. if (typeof DracoDecoderModule !== "undefined") {
  68200. return true;
  68201. }
  68202. var decoder = DracoCompression.Configuration.decoder;
  68203. if (decoder) {
  68204. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68205. return true;
  68206. }
  68207. if (decoder.fallbackUrl) {
  68208. return true;
  68209. }
  68210. }
  68211. return false;
  68212. },
  68213. enumerable: true,
  68214. configurable: true
  68215. });
  68216. /**
  68217. * Stop all async operations and release resources.
  68218. */
  68219. DracoCompression.prototype.dispose = function () {
  68220. };
  68221. /**
  68222. * Decode Draco compressed mesh data to vertex data.
  68223. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  68224. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  68225. * @returns A promise that resolves with the decoded vertex data
  68226. */
  68227. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  68228. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  68229. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  68230. var module = wrappedModule.module;
  68231. var vertexData = new BABYLON.VertexData();
  68232. var buffer = new module.DecoderBuffer();
  68233. buffer.Init(dataView, dataView.byteLength);
  68234. var decoder = new module.Decoder();
  68235. var geometry;
  68236. var status;
  68237. try {
  68238. var type = decoder.GetEncodedGeometryType(buffer);
  68239. switch (type) {
  68240. case module.TRIANGULAR_MESH:
  68241. geometry = new module.Mesh();
  68242. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68243. break;
  68244. case module.POINT_CLOUD:
  68245. geometry = new module.PointCloud();
  68246. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  68247. break;
  68248. default:
  68249. throw new Error("Invalid geometry type " + type);
  68250. }
  68251. if (!status.ok() || !geometry.ptr) {
  68252. throw new Error(status.error_msg());
  68253. }
  68254. var numPoints = geometry.num_points();
  68255. if (type === module.TRIANGULAR_MESH) {
  68256. var numFaces = geometry.num_faces();
  68257. var faceIndices = new module.DracoInt32Array();
  68258. try {
  68259. var indices = new Uint32Array(numFaces * 3);
  68260. for (var i = 0; i < numFaces; i++) {
  68261. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  68262. var offset = i * 3;
  68263. indices[offset + 0] = faceIndices.GetValue(0);
  68264. indices[offset + 1] = faceIndices.GetValue(1);
  68265. indices[offset + 2] = faceIndices.GetValue(2);
  68266. }
  68267. vertexData.indices = indices;
  68268. }
  68269. finally {
  68270. module.destroy(faceIndices);
  68271. }
  68272. }
  68273. for (var kind in attributes) {
  68274. var uniqueId = attributes[kind];
  68275. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  68276. var dracoData = new module.DracoFloat32Array();
  68277. try {
  68278. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  68279. var babylonData = new Float32Array(numPoints * attribute.num_components());
  68280. for (var i = 0; i < babylonData.length; i++) {
  68281. babylonData[i] = dracoData.GetValue(i);
  68282. }
  68283. vertexData.set(babylonData, kind);
  68284. }
  68285. finally {
  68286. module.destroy(dracoData);
  68287. }
  68288. }
  68289. }
  68290. finally {
  68291. if (geometry) {
  68292. module.destroy(geometry);
  68293. }
  68294. module.destroy(decoder);
  68295. module.destroy(buffer);
  68296. }
  68297. return vertexData;
  68298. });
  68299. };
  68300. DracoCompression._GetDecoderModule = function () {
  68301. if (!DracoCompression._DecoderModulePromise) {
  68302. var promise = null;
  68303. var config_1 = {};
  68304. if (typeof DracoDecoderModule !== "undefined") {
  68305. promise = Promise.resolve();
  68306. }
  68307. else {
  68308. var decoder = DracoCompression.Configuration.decoder;
  68309. if (decoder) {
  68310. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68311. promise = Promise.all([
  68312. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  68313. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  68314. config_1.wasmBinary = data;
  68315. })
  68316. ]);
  68317. }
  68318. else if (decoder.fallbackUrl) {
  68319. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  68320. }
  68321. }
  68322. }
  68323. if (!promise) {
  68324. throw new Error("Draco decoder module is not available");
  68325. }
  68326. DracoCompression._DecoderModulePromise = promise.then(function () {
  68327. return new Promise(function (resolve) {
  68328. config_1.onModuleLoaded = function (decoderModule) {
  68329. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  68330. resolve({ module: decoderModule });
  68331. };
  68332. DracoDecoderModule(config_1);
  68333. });
  68334. });
  68335. }
  68336. return DracoCompression._DecoderModulePromise;
  68337. };
  68338. DracoCompression._LoadScriptAsync = function (url) {
  68339. return new Promise(function (resolve, reject) {
  68340. BABYLON.Tools.LoadScript(url, function () {
  68341. resolve();
  68342. }, function (message) {
  68343. reject(new Error(message));
  68344. });
  68345. });
  68346. };
  68347. DracoCompression._LoadFileAsync = function (url) {
  68348. return new Promise(function (resolve, reject) {
  68349. BABYLON.Tools.LoadFile(url, function (data) {
  68350. resolve(data);
  68351. }, undefined, undefined, true, function (request, exception) {
  68352. reject(exception);
  68353. });
  68354. });
  68355. };
  68356. /**
  68357. * The configuration. Defaults to the following urls:
  68358. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  68359. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  68360. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68361. */
  68362. DracoCompression.Configuration = {
  68363. decoder: {
  68364. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  68365. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  68366. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68367. }
  68368. };
  68369. return DracoCompression;
  68370. }());
  68371. BABYLON.DracoCompression = DracoCompression;
  68372. })(BABYLON || (BABYLON = {}));
  68373. //# sourceMappingURL=babylon.dracoCompression.js.map
  68374. var BABYLON;
  68375. (function (BABYLON) {
  68376. // Sets the default audio engine to Babylon JS.
  68377. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  68378. /**
  68379. * This represents the default audio engine used in babylon.
  68380. * It is responsible to play, synchronize and analyse sounds throughout the application.
  68381. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68382. */
  68383. var AudioEngine = /** @class */ (function () {
  68384. /**
  68385. * Instantiates a new audio engine.
  68386. *
  68387. * There should be only one per page as some browsers restrict the number
  68388. * of audio contexts you can create.
  68389. * @param engine defines the hosting engine
  68390. */
  68391. function AudioEngine(engine) {
  68392. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  68393. var _this = this;
  68394. this._audioContext = null;
  68395. this._audioContextInitialized = false;
  68396. this._muteButton = null;
  68397. /**
  68398. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  68399. */
  68400. this.canUseWebAudio = false;
  68401. /**
  68402. * Defines if Babylon should emit a warning if WebAudio is not supported.
  68403. * @ignoreNaming
  68404. */
  68405. this.WarnedWebAudioUnsupported = false;
  68406. /**
  68407. * Gets whether or not mp3 are supported by your browser.
  68408. */
  68409. this.isMP3supported = false;
  68410. /**
  68411. * Gets whether or not ogg are supported by your browser.
  68412. */
  68413. this.isOGGsupported = false;
  68414. /**
  68415. * Gets whether audio has been unlocked on the device.
  68416. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  68417. * a user interaction has happened.
  68418. */
  68419. this.unlocked = true;
  68420. /**
  68421. * Defines if the audio engine relies on a custom unlocked button.
  68422. * In this case, the embedded button will not be displayed.
  68423. */
  68424. this.useCustomUnlockedButton = false;
  68425. /**
  68426. * Event raised when audio has been unlocked on the browser.
  68427. */
  68428. this.onAudioUnlockedObservable = new BABYLON.Observable();
  68429. /**
  68430. * Event raised when audio has been locked on the browser.
  68431. */
  68432. this.onAudioLockedObservable = new BABYLON.Observable();
  68433. this._tryToRun = false;
  68434. this._onResize = function () {
  68435. _this._moveButtonToTopLeft();
  68436. };
  68437. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  68438. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  68439. this.canUseWebAudio = true;
  68440. }
  68441. var audioElem = document.createElement('audio');
  68442. this._engine = engine;
  68443. try {
  68444. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  68445. this.isMP3supported = true;
  68446. }
  68447. }
  68448. catch (e) {
  68449. // protect error during capability check.
  68450. }
  68451. try {
  68452. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  68453. this.isOGGsupported = true;
  68454. }
  68455. }
  68456. catch (e) {
  68457. // protect error during capability check.
  68458. }
  68459. }
  68460. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  68461. /**
  68462. * Gets the current AudioContext if available.
  68463. */
  68464. get: function () {
  68465. if (!this._audioContextInitialized) {
  68466. this._initializeAudioContext();
  68467. }
  68468. else {
  68469. if (!this.unlocked && !this._muteButton) {
  68470. this._displayMuteButton();
  68471. }
  68472. }
  68473. return this._audioContext;
  68474. },
  68475. enumerable: true,
  68476. configurable: true
  68477. });
  68478. /**
  68479. * Flags the audio engine in Locked state.
  68480. * This happens due to new browser policies preventing audio to autoplay.
  68481. */
  68482. AudioEngine.prototype.lock = function () {
  68483. this._triggerSuspendedState();
  68484. };
  68485. /**
  68486. * Unlocks the audio engine once a user action has been done on the dom.
  68487. * This is helpful to resume play once browser policies have been satisfied.
  68488. */
  68489. AudioEngine.prototype.unlock = function () {
  68490. this._triggerRunningState();
  68491. };
  68492. AudioEngine.prototype._resumeAudioContext = function () {
  68493. var result;
  68494. if (this._audioContext.resume) {
  68495. result = this._audioContext.resume();
  68496. }
  68497. return result || Promise.resolve();
  68498. };
  68499. AudioEngine.prototype._initializeAudioContext = function () {
  68500. var _this = this;
  68501. try {
  68502. if (this.canUseWebAudio) {
  68503. this._audioContext = new AudioContext();
  68504. // create a global volume gain node
  68505. this.masterGain = this._audioContext.createGain();
  68506. this.masterGain.gain.value = 1;
  68507. this.masterGain.connect(this._audioContext.destination);
  68508. this._audioContextInitialized = true;
  68509. if (this._audioContext.state === "running") {
  68510. // Do not wait for the promise to unlock.
  68511. this._triggerRunningState();
  68512. }
  68513. else {
  68514. if (this._audioContext && this._audioContext.resume) {
  68515. this._resumeAudioContext().then(function () {
  68516. _this._triggerRunningState();
  68517. }).catch(function () {
  68518. // Can not resume automatically
  68519. // Needs user action
  68520. _this.lock();
  68521. });
  68522. }
  68523. }
  68524. }
  68525. }
  68526. catch (e) {
  68527. this.canUseWebAudio = false;
  68528. BABYLON.Tools.Error("Web Audio: " + e.message);
  68529. }
  68530. };
  68531. AudioEngine.prototype._triggerRunningState = function () {
  68532. var _this = this;
  68533. if (this._tryToRun) {
  68534. return;
  68535. }
  68536. this._tryToRun = true;
  68537. this._resumeAudioContext()
  68538. .then(function () {
  68539. _this._tryToRun = false;
  68540. _this.unlocked = true;
  68541. if (_this._muteButton) {
  68542. _this._hideMuteButton();
  68543. }
  68544. // Notify users that the audio stack is unlocked/unmuted
  68545. _this.onAudioUnlockedObservable.notifyObservers(_this);
  68546. }).catch(function () {
  68547. _this._tryToRun = false;
  68548. _this.unlocked = false;
  68549. });
  68550. };
  68551. AudioEngine.prototype._triggerSuspendedState = function () {
  68552. this.unlocked = false;
  68553. this.onAudioLockedObservable.notifyObservers(this);
  68554. this._displayMuteButton();
  68555. };
  68556. AudioEngine.prototype._displayMuteButton = function () {
  68557. var _this = this;
  68558. if (this.useCustomUnlockedButton) {
  68559. return;
  68560. }
  68561. this._canvas = this._engine.getRenderingCanvas();
  68562. this._muteButton = document.createElement("BUTTON");
  68563. this._muteButton.className = "babylonUnmuteIcon";
  68564. this._muteButton.id = "babylonUnmuteIconBtn";
  68565. this._muteButton.title = "Unmute";
  68566. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  68567. var style = document.createElement('style');
  68568. style.appendChild(document.createTextNode(css));
  68569. document.getElementsByTagName('head')[0].appendChild(style);
  68570. document.body.appendChild(this._muteButton);
  68571. this._moveButtonToTopLeft();
  68572. this._muteButton.addEventListener('mousedown', function () {
  68573. _this._triggerRunningState();
  68574. }, true);
  68575. this._muteButton.addEventListener('touchend', function () {
  68576. _this._triggerRunningState();
  68577. }, true);
  68578. this._muteButton.addEventListener('click', function () {
  68579. _this._triggerRunningState();
  68580. }, true);
  68581. window.addEventListener("resize", this._onResize);
  68582. };
  68583. AudioEngine.prototype._moveButtonToTopLeft = function () {
  68584. if (this._canvas && this._muteButton) {
  68585. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  68586. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  68587. }
  68588. };
  68589. AudioEngine.prototype._hideMuteButton = function () {
  68590. if (this._muteButton) {
  68591. document.body.removeChild(this._muteButton);
  68592. this._muteButton = null;
  68593. }
  68594. };
  68595. /**
  68596. * Destroy and release the resources associated with the audio ccontext.
  68597. */
  68598. AudioEngine.prototype.dispose = function () {
  68599. if (this.canUseWebAudio && this._audioContextInitialized) {
  68600. if (this._connectedAnalyser && this._audioContext) {
  68601. this._connectedAnalyser.stopDebugCanvas();
  68602. this._connectedAnalyser.dispose();
  68603. this.masterGain.disconnect();
  68604. this.masterGain.connect(this._audioContext.destination);
  68605. this._connectedAnalyser = null;
  68606. }
  68607. this.masterGain.gain.value = 1;
  68608. }
  68609. this.WarnedWebAudioUnsupported = false;
  68610. this._hideMuteButton();
  68611. window.removeEventListener("resize", this._onResize);
  68612. this.onAudioUnlockedObservable.clear();
  68613. this.onAudioLockedObservable.clear();
  68614. };
  68615. /**
  68616. * Gets the global volume sets on the master gain.
  68617. * @returns the global volume if set or -1 otherwise
  68618. */
  68619. AudioEngine.prototype.getGlobalVolume = function () {
  68620. if (this.canUseWebAudio && this._audioContextInitialized) {
  68621. return this.masterGain.gain.value;
  68622. }
  68623. else {
  68624. return -1;
  68625. }
  68626. };
  68627. /**
  68628. * Sets the global volume of your experience (sets on the master gain).
  68629. * @param newVolume Defines the new global volume of the application
  68630. */
  68631. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  68632. if (this.canUseWebAudio && this._audioContextInitialized) {
  68633. this.masterGain.gain.value = newVolume;
  68634. }
  68635. };
  68636. /**
  68637. * Connect the audio engine to an audio analyser allowing some amazing
  68638. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68639. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68640. * @param analyser The analyser to connect to the engine
  68641. */
  68642. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  68643. if (this._connectedAnalyser) {
  68644. this._connectedAnalyser.stopDebugCanvas();
  68645. }
  68646. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  68647. this._connectedAnalyser = analyser;
  68648. this.masterGain.disconnect();
  68649. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  68650. }
  68651. };
  68652. return AudioEngine;
  68653. }());
  68654. BABYLON.AudioEngine = AudioEngine;
  68655. })(BABYLON || (BABYLON = {}));
  68656. //# sourceMappingURL=babylon.audioEngine.js.map
  68657. var BABYLON;
  68658. (function (BABYLON) {
  68659. /**
  68660. * Defines a sound that can be played in the application.
  68661. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  68662. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68663. */
  68664. var Sound = /** @class */ (function () {
  68665. /**
  68666. * Create a sound and attach it to a scene
  68667. * @param name Name of your sound
  68668. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  68669. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  68670. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  68671. */
  68672. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  68673. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  68674. var _this = this;
  68675. /**
  68676. * Does the sound autoplay once loaded.
  68677. */
  68678. this.autoplay = false;
  68679. /**
  68680. * Does the sound loop after it finishes playing once.
  68681. */
  68682. this.loop = false;
  68683. /**
  68684. * Does the sound use a custom attenuation curve to simulate the falloff
  68685. * happening when the source gets further away from the camera.
  68686. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68687. */
  68688. this.useCustomAttenuation = false;
  68689. /**
  68690. * Is this sound currently played.
  68691. */
  68692. this.isPlaying = false;
  68693. /**
  68694. * Is this sound currently paused.
  68695. */
  68696. this.isPaused = false;
  68697. /**
  68698. * Does this sound enables spatial sound.
  68699. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68700. */
  68701. this.spatialSound = false;
  68702. /**
  68703. * Define the reference distance the sound should be heard perfectly.
  68704. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68705. */
  68706. this.refDistance = 1;
  68707. /**
  68708. * Define the roll off factor of spatial sounds.
  68709. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68710. */
  68711. this.rolloffFactor = 1;
  68712. /**
  68713. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  68714. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68715. */
  68716. this.maxDistance = 100;
  68717. /**
  68718. * Define the distance attenuation model the sound will follow.
  68719. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68720. */
  68721. this.distanceModel = "linear";
  68722. /**
  68723. * Observable event when the current playing sound finishes.
  68724. */
  68725. this.onEndedObservable = new BABYLON.Observable();
  68726. this._panningModel = "equalpower";
  68727. this._playbackRate = 1;
  68728. this._streaming = false;
  68729. this._startTime = 0;
  68730. this._startOffset = 0;
  68731. this._position = BABYLON.Vector3.Zero();
  68732. /** @hidden */
  68733. this._positionInEmitterSpace = false;
  68734. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  68735. this._volume = 1;
  68736. this._isReadyToPlay = false;
  68737. this._isDirectional = false;
  68738. // Used if you'd like to create a directional sound.
  68739. // If not set, the sound will be omnidirectional
  68740. this._coneInnerAngle = 360;
  68741. this._coneOuterAngle = 360;
  68742. this._coneOuterGain = 0;
  68743. this._isOutputConnected = false;
  68744. this._urlType = "Unknown";
  68745. this.name = name;
  68746. this._scene = scene;
  68747. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68748. if (!compo) {
  68749. compo = new BABYLON.AudioSceneComponent(scene);
  68750. scene._addComponent(compo);
  68751. }
  68752. this._readyToPlayCallback = readyToPlayCallback;
  68753. // Default custom attenuation function is a linear attenuation
  68754. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  68755. if (currentDistance < maxDistance) {
  68756. return currentVolume * (1 - currentDistance / maxDistance);
  68757. }
  68758. else {
  68759. return 0;
  68760. }
  68761. };
  68762. if (options) {
  68763. this.autoplay = options.autoplay || false;
  68764. this.loop = options.loop || false;
  68765. // if volume === 0, we need another way to check this option
  68766. if (options.volume !== undefined) {
  68767. this._volume = options.volume;
  68768. }
  68769. this.spatialSound = options.spatialSound || false;
  68770. this.maxDistance = options.maxDistance || 100;
  68771. this.useCustomAttenuation = options.useCustomAttenuation || false;
  68772. this.rolloffFactor = options.rolloffFactor || 1;
  68773. this.refDistance = options.refDistance || 1;
  68774. this.distanceModel = options.distanceModel || "linear";
  68775. this._playbackRate = options.playbackRate || 1;
  68776. this._streaming = options.streaming || false;
  68777. }
  68778. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68779. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  68780. this._soundGain.gain.value = this._volume;
  68781. this._inputAudioNode = this._soundGain;
  68782. this._outputAudioNode = this._soundGain;
  68783. if (this.spatialSound) {
  68784. this._createSpatialParameters();
  68785. }
  68786. this._scene.mainSoundTrack.AddSound(this);
  68787. var validParameter = true;
  68788. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  68789. if (urlOrArrayBuffer) {
  68790. try {
  68791. if (typeof (urlOrArrayBuffer) === "string") {
  68792. this._urlType = "String";
  68793. }
  68794. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  68795. this._urlType = "ArrayBuffer";
  68796. }
  68797. else if (urlOrArrayBuffer instanceof MediaStream) {
  68798. this._urlType = "MediaStream";
  68799. }
  68800. else if (Array.isArray(urlOrArrayBuffer)) {
  68801. this._urlType = "Array";
  68802. }
  68803. var urls = [];
  68804. var codecSupportedFound = false;
  68805. switch (this._urlType) {
  68806. case "MediaStream":
  68807. this._streaming = true;
  68808. this._isReadyToPlay = true;
  68809. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  68810. if (this.autoplay) {
  68811. this.play();
  68812. }
  68813. if (this._readyToPlayCallback) {
  68814. this._readyToPlayCallback();
  68815. }
  68816. break;
  68817. case "ArrayBuffer":
  68818. if (urlOrArrayBuffer.byteLength > 0) {
  68819. codecSupportedFound = true;
  68820. this._soundLoaded(urlOrArrayBuffer);
  68821. }
  68822. break;
  68823. case "String":
  68824. urls.push(urlOrArrayBuffer);
  68825. case "Array":
  68826. if (urls.length === 0)
  68827. urls = urlOrArrayBuffer;
  68828. // If we found a supported format, we load it immediately and stop the loop
  68829. for (var i = 0; i < urls.length; i++) {
  68830. var url = urls[i];
  68831. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  68832. codecSupportedFound = true;
  68833. }
  68834. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  68835. codecSupportedFound = true;
  68836. }
  68837. if (url.indexOf(".wav", url.length - 4) !== -1) {
  68838. codecSupportedFound = true;
  68839. }
  68840. if (url.indexOf("blob:") !== -1) {
  68841. codecSupportedFound = true;
  68842. }
  68843. if (codecSupportedFound) {
  68844. // Loading sound using XHR2
  68845. if (!this._streaming) {
  68846. this._scene._loadFile(url, function (data) {
  68847. _this._soundLoaded(data);
  68848. }, undefined, true, true, function (exception) {
  68849. if (exception) {
  68850. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  68851. }
  68852. BABYLON.Tools.Error("Sound creation aborted.");
  68853. _this._scene.mainSoundTrack.RemoveSound(_this);
  68854. });
  68855. }
  68856. // Streaming sound using HTML5 Audio tag
  68857. else {
  68858. this._htmlAudioElement = new Audio(url);
  68859. this._htmlAudioElement.controls = false;
  68860. this._htmlAudioElement.loop = this.loop;
  68861. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  68862. this._htmlAudioElement.preload = "auto";
  68863. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  68864. _this._isReadyToPlay = true;
  68865. if (_this.autoplay) {
  68866. _this.play();
  68867. }
  68868. if (_this._readyToPlayCallback) {
  68869. _this._readyToPlayCallback();
  68870. }
  68871. });
  68872. document.body.appendChild(this._htmlAudioElement);
  68873. this._htmlAudioElement.load();
  68874. }
  68875. break;
  68876. }
  68877. }
  68878. break;
  68879. default:
  68880. validParameter = false;
  68881. break;
  68882. }
  68883. if (!validParameter) {
  68884. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  68885. }
  68886. else {
  68887. if (!codecSupportedFound) {
  68888. this._isReadyToPlay = true;
  68889. // Simulating a ready to play event to avoid breaking code path
  68890. if (this._readyToPlayCallback) {
  68891. window.setTimeout(function () {
  68892. if (_this._readyToPlayCallback) {
  68893. _this._readyToPlayCallback();
  68894. }
  68895. }, 1000);
  68896. }
  68897. }
  68898. }
  68899. }
  68900. catch (ex) {
  68901. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  68902. this._scene.mainSoundTrack.RemoveSound(this);
  68903. }
  68904. }
  68905. }
  68906. else {
  68907. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  68908. this._scene.mainSoundTrack.AddSound(this);
  68909. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  68910. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  68911. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  68912. }
  68913. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  68914. if (this._readyToPlayCallback) {
  68915. window.setTimeout(function () {
  68916. if (_this._readyToPlayCallback) {
  68917. _this._readyToPlayCallback();
  68918. }
  68919. }, 1000);
  68920. }
  68921. }
  68922. }
  68923. /**
  68924. * Release the sound and its associated resources
  68925. */
  68926. Sound.prototype.dispose = function () {
  68927. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68928. if (this.isPlaying) {
  68929. this.stop();
  68930. }
  68931. this._isReadyToPlay = false;
  68932. if (this.soundTrackId === -1) {
  68933. this._scene.mainSoundTrack.RemoveSound(this);
  68934. }
  68935. else if (this._scene.soundTracks) {
  68936. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  68937. }
  68938. if (this._soundGain) {
  68939. this._soundGain.disconnect();
  68940. this._soundGain = null;
  68941. }
  68942. if (this._soundPanner) {
  68943. this._soundPanner.disconnect();
  68944. this._soundPanner = null;
  68945. }
  68946. if (this._soundSource) {
  68947. this._soundSource.disconnect();
  68948. this._soundSource = null;
  68949. }
  68950. this._audioBuffer = null;
  68951. if (this._htmlAudioElement) {
  68952. this._htmlAudioElement.pause();
  68953. this._htmlAudioElement.src = "";
  68954. document.body.removeChild(this._htmlAudioElement);
  68955. }
  68956. if (this._streamingSource) {
  68957. this._streamingSource.disconnect();
  68958. }
  68959. if (this._connectedMesh && this._registerFunc) {
  68960. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68961. this._connectedMesh = null;
  68962. }
  68963. }
  68964. };
  68965. /**
  68966. * Gets if the sounds is ready to be played or not.
  68967. * @returns true if ready, otherwise false
  68968. */
  68969. Sound.prototype.isReady = function () {
  68970. return this._isReadyToPlay;
  68971. };
  68972. Sound.prototype._soundLoaded = function (audioData) {
  68973. var _this = this;
  68974. if (!BABYLON.Engine.audioEngine.audioContext) {
  68975. return;
  68976. }
  68977. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  68978. _this._audioBuffer = buffer;
  68979. _this._isReadyToPlay = true;
  68980. if (_this.autoplay) {
  68981. _this.play();
  68982. }
  68983. if (_this._readyToPlayCallback) {
  68984. _this._readyToPlayCallback();
  68985. }
  68986. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  68987. };
  68988. /**
  68989. * Sets the data of the sound from an audiobuffer
  68990. * @param audioBuffer The audioBuffer containing the data
  68991. */
  68992. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  68993. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68994. this._audioBuffer = audioBuffer;
  68995. this._isReadyToPlay = true;
  68996. }
  68997. };
  68998. /**
  68999. * Updates the current sounds options such as maxdistance, loop...
  69000. * @param options A JSON object containing values named as the object properties
  69001. */
  69002. Sound.prototype.updateOptions = function (options) {
  69003. if (options) {
  69004. this.loop = options.loop || this.loop;
  69005. this.maxDistance = options.maxDistance || this.maxDistance;
  69006. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69007. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69008. this.refDistance = options.refDistance || this.refDistance;
  69009. this.distanceModel = options.distanceModel || this.distanceModel;
  69010. this._playbackRate = options.playbackRate || this._playbackRate;
  69011. this._updateSpatialParameters();
  69012. if (this.isPlaying) {
  69013. if (this._streaming && this._htmlAudioElement) {
  69014. this._htmlAudioElement.playbackRate = this._playbackRate;
  69015. }
  69016. else {
  69017. if (this._soundSource) {
  69018. this._soundSource.playbackRate.value = this._playbackRate;
  69019. }
  69020. }
  69021. }
  69022. }
  69023. };
  69024. Sound.prototype._createSpatialParameters = function () {
  69025. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69026. if (this._scene.headphone) {
  69027. this._panningModel = "HRTF";
  69028. }
  69029. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  69030. this._updateSpatialParameters();
  69031. this._soundPanner.connect(this._outputAudioNode);
  69032. this._inputAudioNode = this._soundPanner;
  69033. }
  69034. };
  69035. Sound.prototype._updateSpatialParameters = function () {
  69036. if (this.spatialSound && this._soundPanner) {
  69037. if (this.useCustomAttenuation) {
  69038. // Tricks to disable in a way embedded Web Audio attenuation
  69039. this._soundPanner.distanceModel = "linear";
  69040. this._soundPanner.maxDistance = Number.MAX_VALUE;
  69041. this._soundPanner.refDistance = 1;
  69042. this._soundPanner.rolloffFactor = 1;
  69043. this._soundPanner.panningModel = this._panningModel;
  69044. }
  69045. else {
  69046. this._soundPanner.distanceModel = this.distanceModel;
  69047. this._soundPanner.maxDistance = this.maxDistance;
  69048. this._soundPanner.refDistance = this.refDistance;
  69049. this._soundPanner.rolloffFactor = this.rolloffFactor;
  69050. this._soundPanner.panningModel = this._panningModel;
  69051. }
  69052. }
  69053. };
  69054. /**
  69055. * Switch the panning model to HRTF:
  69056. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69057. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69058. */
  69059. Sound.prototype.switchPanningModelToHRTF = function () {
  69060. this._panningModel = "HRTF";
  69061. this._switchPanningModel();
  69062. };
  69063. /**
  69064. * Switch the panning model to Equal Power:
  69065. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69066. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69067. */
  69068. Sound.prototype.switchPanningModelToEqualPower = function () {
  69069. this._panningModel = "equalpower";
  69070. this._switchPanningModel();
  69071. };
  69072. Sound.prototype._switchPanningModel = function () {
  69073. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69074. this._soundPanner.panningModel = this._panningModel;
  69075. }
  69076. };
  69077. /**
  69078. * Connect this sound to a sound track audio node like gain...
  69079. * @param soundTrackAudioNode the sound track audio node to connect to
  69080. */
  69081. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  69082. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69083. if (this._isOutputConnected) {
  69084. this._outputAudioNode.disconnect();
  69085. }
  69086. this._outputAudioNode.connect(soundTrackAudioNode);
  69087. this._isOutputConnected = true;
  69088. }
  69089. };
  69090. /**
  69091. * Transform this sound into a directional source
  69092. * @param coneInnerAngle Size of the inner cone in degree
  69093. * @param coneOuterAngle Size of the outer cone in degree
  69094. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  69095. */
  69096. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  69097. if (coneOuterAngle < coneInnerAngle) {
  69098. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  69099. return;
  69100. }
  69101. this._coneInnerAngle = coneInnerAngle;
  69102. this._coneOuterAngle = coneOuterAngle;
  69103. this._coneOuterGain = coneOuterGain;
  69104. this._isDirectional = true;
  69105. if (this.isPlaying && this.loop) {
  69106. this.stop();
  69107. this.play();
  69108. }
  69109. };
  69110. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  69111. /**
  69112. * Gets or sets the inner angle for the directional cone.
  69113. */
  69114. get: function () {
  69115. return this._coneInnerAngle;
  69116. },
  69117. /**
  69118. * Gets or sets the inner angle for the directional cone.
  69119. */
  69120. set: function (value) {
  69121. if (value != this._coneInnerAngle) {
  69122. if (this._coneOuterAngle < value) {
  69123. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69124. return;
  69125. }
  69126. this._coneInnerAngle = value;
  69127. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69128. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69129. }
  69130. }
  69131. },
  69132. enumerable: true,
  69133. configurable: true
  69134. });
  69135. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  69136. /**
  69137. * Gets or sets the outer angle for the directional cone.
  69138. */
  69139. get: function () {
  69140. return this._coneOuterAngle;
  69141. },
  69142. /**
  69143. * Gets or sets the outer angle for the directional cone.
  69144. */
  69145. set: function (value) {
  69146. if (value != this._coneOuterAngle) {
  69147. if (value < this._coneInnerAngle) {
  69148. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69149. return;
  69150. }
  69151. this._coneOuterAngle = value;
  69152. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69153. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69154. }
  69155. }
  69156. },
  69157. enumerable: true,
  69158. configurable: true
  69159. });
  69160. /**
  69161. * Sets the position of the emitter if spatial sound is enabled
  69162. * @param newPosition Defines the new posisiton
  69163. */
  69164. Sound.prototype.setPosition = function (newPosition) {
  69165. this._position = newPosition;
  69166. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69167. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69168. }
  69169. };
  69170. /**
  69171. * Sets the local direction of the emitter if spatial sound is enabled
  69172. * @param newLocalDirection Defines the new local direction
  69173. */
  69174. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  69175. this._localDirection = newLocalDirection;
  69176. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  69177. this._updateDirection();
  69178. }
  69179. };
  69180. Sound.prototype._updateDirection = function () {
  69181. if (!this._connectedMesh || !this._soundPanner) {
  69182. return;
  69183. }
  69184. var mat = this._connectedMesh.getWorldMatrix();
  69185. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  69186. direction.normalize();
  69187. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  69188. };
  69189. /** @hidden */
  69190. Sound.prototype.updateDistanceFromListener = function () {
  69191. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  69192. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  69193. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  69194. }
  69195. };
  69196. /**
  69197. * Sets a new custom attenuation function for the sound.
  69198. * @param callback Defines the function used for the attenuation
  69199. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69200. */
  69201. Sound.prototype.setAttenuationFunction = function (callback) {
  69202. this._customAttenuationFunction = callback;
  69203. };
  69204. /**
  69205. * Play the sound
  69206. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  69207. * @param offset (optional) Start the sound setting it at a specific time
  69208. */
  69209. Sound.prototype.play = function (time, offset) {
  69210. var _this = this;
  69211. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  69212. try {
  69213. if (this._startOffset < 0) {
  69214. time = -this._startOffset;
  69215. this._startOffset = 0;
  69216. }
  69217. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69218. if (!this._soundSource || !this._streamingSource) {
  69219. if (this.spatialSound && this._soundPanner) {
  69220. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69221. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69222. }
  69223. if (this._isDirectional) {
  69224. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69225. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69226. this._soundPanner.coneOuterGain = this._coneOuterGain;
  69227. if (this._connectedMesh) {
  69228. this._updateDirection();
  69229. }
  69230. else {
  69231. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  69232. }
  69233. }
  69234. }
  69235. }
  69236. if (this._streaming) {
  69237. if (!this._streamingSource) {
  69238. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69239. this._htmlAudioElement.onended = function () { _this._onended(); };
  69240. this._htmlAudioElement.playbackRate = this._playbackRate;
  69241. }
  69242. this._streamingSource.disconnect();
  69243. this._streamingSource.connect(this._inputAudioNode);
  69244. if (this._htmlAudioElement) {
  69245. // required to manage properly the new suspended default state of Chrome
  69246. // When the option 'streaming: true' is used, we need first to wait for
  69247. // the audio engine to be unlocked by a user gesture before trying to play
  69248. // an HTML Audio elememt
  69249. var tryToPlay = function () {
  69250. if (BABYLON.Engine.audioEngine.unlocked) {
  69251. var playPromise = _this._htmlAudioElement.play();
  69252. // In browsers that don’t yet support this functionality,
  69253. // playPromise won’t be defined.
  69254. if (playPromise !== undefined) {
  69255. playPromise.catch(function (error) {
  69256. // Automatic playback failed.
  69257. // Waiting for the audio engine to be unlocked by user click on unmute
  69258. BABYLON.Engine.audioEngine.lock();
  69259. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69260. });
  69261. }
  69262. }
  69263. else {
  69264. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69265. }
  69266. };
  69267. tryToPlay();
  69268. }
  69269. }
  69270. else {
  69271. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  69272. this._soundSource.buffer = this._audioBuffer;
  69273. this._soundSource.connect(this._inputAudioNode);
  69274. this._soundSource.loop = this.loop;
  69275. this._soundSource.playbackRate.value = this._playbackRate;
  69276. this._soundSource.onended = function () { _this._onended(); };
  69277. if (this._soundSource.buffer) {
  69278. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  69279. }
  69280. }
  69281. this._startTime = startTime;
  69282. this.isPlaying = true;
  69283. this.isPaused = false;
  69284. }
  69285. catch (ex) {
  69286. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  69287. }
  69288. }
  69289. };
  69290. Sound.prototype._onended = function () {
  69291. this.isPlaying = false;
  69292. if (this.onended) {
  69293. this.onended();
  69294. }
  69295. this.onEndedObservable.notifyObservers(this);
  69296. };
  69297. /**
  69298. * Stop the sound
  69299. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  69300. */
  69301. Sound.prototype.stop = function (time) {
  69302. if (this.isPlaying) {
  69303. if (this._streaming) {
  69304. if (this._htmlAudioElement) {
  69305. this._htmlAudioElement.pause();
  69306. // Test needed for Firefox or it will generate an Invalid State Error
  69307. if (this._htmlAudioElement.currentTime > 0) {
  69308. this._htmlAudioElement.currentTime = 0;
  69309. }
  69310. }
  69311. else {
  69312. this._streamingSource.disconnect();
  69313. }
  69314. }
  69315. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  69316. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69317. this._soundSource.stop(stopTime);
  69318. this._soundSource.onended = function () { };
  69319. if (!this.isPaused) {
  69320. this._startOffset = 0;
  69321. }
  69322. }
  69323. this.isPlaying = false;
  69324. }
  69325. };
  69326. /**
  69327. * Put the sound in pause
  69328. */
  69329. Sound.prototype.pause = function () {
  69330. if (this.isPlaying) {
  69331. this.isPaused = true;
  69332. if (this._streaming) {
  69333. if (this._htmlAudioElement) {
  69334. this._htmlAudioElement.pause();
  69335. }
  69336. else {
  69337. this._streamingSource.disconnect();
  69338. }
  69339. }
  69340. else if (BABYLON.Engine.audioEngine.audioContext) {
  69341. this.stop(0);
  69342. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  69343. }
  69344. }
  69345. };
  69346. /**
  69347. * Sets a dedicated volume for this sounds
  69348. * @param newVolume Define the new volume of the sound
  69349. * @param time Define in how long the sound should be at this value
  69350. */
  69351. Sound.prototype.setVolume = function (newVolume, time) {
  69352. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  69353. if (time && BABYLON.Engine.audioEngine.audioContext) {
  69354. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  69355. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  69356. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  69357. }
  69358. else {
  69359. this._soundGain.gain.value = newVolume;
  69360. }
  69361. }
  69362. this._volume = newVolume;
  69363. };
  69364. /**
  69365. * Set the sound play back rate
  69366. * @param newPlaybackRate Define the playback rate the sound should be played at
  69367. */
  69368. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  69369. this._playbackRate = newPlaybackRate;
  69370. if (this.isPlaying) {
  69371. if (this._streaming && this._htmlAudioElement) {
  69372. this._htmlAudioElement.playbackRate = this._playbackRate;
  69373. }
  69374. else if (this._soundSource) {
  69375. this._soundSource.playbackRate.value = this._playbackRate;
  69376. }
  69377. }
  69378. };
  69379. /**
  69380. * Gets the volume of the sound.
  69381. * @returns the volume of the sound
  69382. */
  69383. Sound.prototype.getVolume = function () {
  69384. return this._volume;
  69385. };
  69386. /**
  69387. * Attach the sound to a dedicated mesh
  69388. * @param meshToConnectTo The mesh to connect the sound with
  69389. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69390. */
  69391. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  69392. var _this = this;
  69393. if (this._connectedMesh && this._registerFunc) {
  69394. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69395. this._registerFunc = null;
  69396. }
  69397. this._connectedMesh = meshToConnectTo;
  69398. if (!this.spatialSound) {
  69399. this.spatialSound = true;
  69400. this._createSpatialParameters();
  69401. if (this.isPlaying && this.loop) {
  69402. this.stop();
  69403. this.play();
  69404. }
  69405. }
  69406. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  69407. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  69408. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  69409. };
  69410. /**
  69411. * Detach the sound from the previously attached mesh
  69412. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69413. */
  69414. Sound.prototype.detachFromMesh = function () {
  69415. if (this._connectedMesh && this._registerFunc) {
  69416. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69417. this._registerFunc = null;
  69418. this._connectedMesh = null;
  69419. }
  69420. };
  69421. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  69422. if (!node.getBoundingInfo) {
  69423. return;
  69424. }
  69425. var mesh = node;
  69426. if (this._positionInEmitterSpace) {
  69427. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  69428. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  69429. }
  69430. else {
  69431. var boundingInfo = mesh.getBoundingInfo();
  69432. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  69433. }
  69434. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  69435. this._updateDirection();
  69436. }
  69437. };
  69438. /**
  69439. * Clone the current sound in the scene.
  69440. * @returns the new sound clone
  69441. */
  69442. Sound.prototype.clone = function () {
  69443. var _this = this;
  69444. if (!this._streaming) {
  69445. var setBufferAndRun = function () {
  69446. if (_this._isReadyToPlay) {
  69447. clonedSound._audioBuffer = _this.getAudioBuffer();
  69448. clonedSound._isReadyToPlay = true;
  69449. if (clonedSound.autoplay) {
  69450. clonedSound.play();
  69451. }
  69452. }
  69453. else {
  69454. window.setTimeout(setBufferAndRun, 300);
  69455. }
  69456. };
  69457. var currentOptions = {
  69458. autoplay: this.autoplay, loop: this.loop,
  69459. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  69460. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  69461. refDistance: this.refDistance, distanceModel: this.distanceModel
  69462. };
  69463. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  69464. if (this.useCustomAttenuation) {
  69465. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  69466. }
  69467. clonedSound.setPosition(this._position);
  69468. clonedSound.setPlaybackRate(this._playbackRate);
  69469. setBufferAndRun();
  69470. return clonedSound;
  69471. }
  69472. // Can't clone a streaming sound
  69473. else {
  69474. return null;
  69475. }
  69476. };
  69477. /**
  69478. * Gets the current underlying audio buffer containing the data
  69479. * @returns the audio buffer
  69480. */
  69481. Sound.prototype.getAudioBuffer = function () {
  69482. return this._audioBuffer;
  69483. };
  69484. /**
  69485. * Serializes the Sound in a JSON representation
  69486. * @returns the JSON representation of the sound
  69487. */
  69488. Sound.prototype.serialize = function () {
  69489. var serializationObject = {
  69490. name: this.name,
  69491. url: this.name,
  69492. autoplay: this.autoplay,
  69493. loop: this.loop,
  69494. volume: this._volume,
  69495. spatialSound: this.spatialSound,
  69496. maxDistance: this.maxDistance,
  69497. rolloffFactor: this.rolloffFactor,
  69498. refDistance: this.refDistance,
  69499. distanceModel: this.distanceModel,
  69500. playbackRate: this._playbackRate,
  69501. panningModel: this._panningModel,
  69502. soundTrackId: this.soundTrackId
  69503. };
  69504. if (this.spatialSound) {
  69505. if (this._connectedMesh)
  69506. serializationObject.connectedMeshId = this._connectedMesh.id;
  69507. serializationObject.position = this._position.asArray();
  69508. serializationObject.refDistance = this.refDistance;
  69509. serializationObject.distanceModel = this.distanceModel;
  69510. serializationObject.isDirectional = this._isDirectional;
  69511. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  69512. serializationObject.coneInnerAngle = this._coneInnerAngle;
  69513. serializationObject.coneOuterAngle = this._coneOuterAngle;
  69514. serializationObject.coneOuterGain = this._coneOuterGain;
  69515. }
  69516. return serializationObject;
  69517. };
  69518. /**
  69519. * Parse a JSON representation of a sound to innstantiate in a given scene
  69520. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  69521. * @param scene Define the scene the new parsed sound should be created in
  69522. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  69523. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  69524. * @returns the newly parsed sound
  69525. */
  69526. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  69527. var soundName = parsedSound.name;
  69528. var soundUrl;
  69529. if (parsedSound.url) {
  69530. soundUrl = rootUrl + parsedSound.url;
  69531. }
  69532. else {
  69533. soundUrl = rootUrl + soundName;
  69534. }
  69535. var options = {
  69536. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  69537. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  69538. rolloffFactor: parsedSound.rolloffFactor,
  69539. refDistance: parsedSound.refDistance,
  69540. distanceModel: parsedSound.distanceModel,
  69541. playbackRate: parsedSound.playbackRate
  69542. };
  69543. var newSound;
  69544. if (!sourceSound) {
  69545. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  69546. scene._addPendingData(newSound);
  69547. }
  69548. else {
  69549. var setBufferAndRun = function () {
  69550. if (sourceSound._isReadyToPlay) {
  69551. newSound._audioBuffer = sourceSound.getAudioBuffer();
  69552. newSound._isReadyToPlay = true;
  69553. if (newSound.autoplay) {
  69554. newSound.play();
  69555. }
  69556. }
  69557. else {
  69558. window.setTimeout(setBufferAndRun, 300);
  69559. }
  69560. };
  69561. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  69562. setBufferAndRun();
  69563. }
  69564. if (parsedSound.position) {
  69565. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  69566. newSound.setPosition(soundPosition);
  69567. }
  69568. if (parsedSound.isDirectional) {
  69569. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  69570. if (parsedSound.localDirectionToMesh) {
  69571. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  69572. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  69573. }
  69574. }
  69575. if (parsedSound.connectedMeshId) {
  69576. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  69577. if (connectedMesh) {
  69578. newSound.attachToMesh(connectedMesh);
  69579. }
  69580. }
  69581. return newSound;
  69582. };
  69583. return Sound;
  69584. }());
  69585. BABYLON.Sound = Sound;
  69586. })(BABYLON || (BABYLON = {}));
  69587. //# sourceMappingURL=babylon.sound.js.map
  69588. var BABYLON;
  69589. (function (BABYLON) {
  69590. /**
  69591. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  69592. * It will be also used in a future release to apply effects on a specific track.
  69593. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69594. */
  69595. var SoundTrack = /** @class */ (function () {
  69596. /**
  69597. * Creates a new sound track.
  69598. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69599. * @param scene Define the scene the sound track belongs to
  69600. * @param options
  69601. */
  69602. function SoundTrack(scene, options) {
  69603. if (options === void 0) { options = {}; }
  69604. /**
  69605. * The unique identifier of the sound track in the scene.
  69606. */
  69607. this.id = -1;
  69608. this._isMainTrack = false;
  69609. this._isInitialized = false;
  69610. this._scene = scene;
  69611. this.soundCollection = new Array();
  69612. this._options = options;
  69613. if (!this._isMainTrack && this._scene.soundTracks) {
  69614. this._scene.soundTracks.push(this);
  69615. this.id = this._scene.soundTracks.length - 1;
  69616. }
  69617. }
  69618. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  69619. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69620. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  69621. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  69622. if (this._options) {
  69623. if (this._options.volume) {
  69624. this._outputAudioNode.gain.value = this._options.volume;
  69625. }
  69626. if (this._options.mainTrack) {
  69627. this._isMainTrack = this._options.mainTrack;
  69628. }
  69629. }
  69630. this._isInitialized = true;
  69631. }
  69632. };
  69633. /**
  69634. * Release the sound track and its associated resources
  69635. */
  69636. SoundTrack.prototype.dispose = function () {
  69637. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  69638. if (this._connectedAnalyser) {
  69639. this._connectedAnalyser.stopDebugCanvas();
  69640. }
  69641. while (this.soundCollection.length) {
  69642. this.soundCollection[0].dispose();
  69643. }
  69644. if (this._outputAudioNode) {
  69645. this._outputAudioNode.disconnect();
  69646. }
  69647. this._outputAudioNode = null;
  69648. }
  69649. };
  69650. /**
  69651. * Adds a sound to this sound track
  69652. * @param sound define the cound to add
  69653. * @ignoreNaming
  69654. */
  69655. SoundTrack.prototype.AddSound = function (sound) {
  69656. if (!this._isInitialized) {
  69657. this._initializeSoundTrackAudioGraph();
  69658. }
  69659. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69660. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  69661. }
  69662. if (sound.soundTrackId) {
  69663. if (sound.soundTrackId === -1) {
  69664. this._scene.mainSoundTrack.RemoveSound(sound);
  69665. }
  69666. else if (this._scene.soundTracks) {
  69667. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  69668. }
  69669. }
  69670. this.soundCollection.push(sound);
  69671. sound.soundTrackId = this.id;
  69672. };
  69673. /**
  69674. * Removes a sound to this sound track
  69675. * @param sound define the cound to remove
  69676. * @ignoreNaming
  69677. */
  69678. SoundTrack.prototype.RemoveSound = function (sound) {
  69679. var index = this.soundCollection.indexOf(sound);
  69680. if (index !== -1) {
  69681. this.soundCollection.splice(index, 1);
  69682. }
  69683. };
  69684. /**
  69685. * Set a global volume for the full sound track.
  69686. * @param newVolume Define the new volume of the sound track
  69687. */
  69688. SoundTrack.prototype.setVolume = function (newVolume) {
  69689. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69690. this._outputAudioNode.gain.value = newVolume;
  69691. }
  69692. };
  69693. /**
  69694. * Switch the panning model to HRTF:
  69695. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69696. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69697. */
  69698. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  69699. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69700. for (var i = 0; i < this.soundCollection.length; i++) {
  69701. this.soundCollection[i].switchPanningModelToHRTF();
  69702. }
  69703. }
  69704. };
  69705. /**
  69706. * Switch the panning model to Equal Power:
  69707. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69708. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69709. */
  69710. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  69711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69712. for (var i = 0; i < this.soundCollection.length; i++) {
  69713. this.soundCollection[i].switchPanningModelToEqualPower();
  69714. }
  69715. }
  69716. };
  69717. /**
  69718. * Connect the sound track to an audio analyser allowing some amazing
  69719. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69720. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69721. * @param analyser The analyser to connect to the engine
  69722. */
  69723. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  69724. if (this._connectedAnalyser) {
  69725. this._connectedAnalyser.stopDebugCanvas();
  69726. }
  69727. this._connectedAnalyser = analyser;
  69728. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69729. this._outputAudioNode.disconnect();
  69730. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  69731. }
  69732. };
  69733. return SoundTrack;
  69734. }());
  69735. BABYLON.SoundTrack = SoundTrack;
  69736. })(BABYLON || (BABYLON = {}));
  69737. //# sourceMappingURL=babylon.soundtrack.js.map
  69738. var BABYLON;
  69739. (function (BABYLON) {
  69740. /**
  69741. * Class used to work with sound analyzer using fast fourier transform (FFT)
  69742. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69743. */
  69744. var Analyser = /** @class */ (function () {
  69745. /**
  69746. * Creates a new analyser
  69747. * @param scene defines hosting scene
  69748. */
  69749. function Analyser(scene) {
  69750. /**
  69751. * Gets or sets the smoothing
  69752. * @ignorenaming
  69753. */
  69754. this.SMOOTHING = 0.75;
  69755. /**
  69756. * Gets or sets the FFT table size
  69757. * @ignorenaming
  69758. */
  69759. this.FFT_SIZE = 512;
  69760. /**
  69761. * Gets or sets the bar graph amplitude
  69762. * @ignorenaming
  69763. */
  69764. this.BARGRAPHAMPLITUDE = 256;
  69765. /**
  69766. * Gets or sets the position of the debug canvas
  69767. * @ignorenaming
  69768. */
  69769. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  69770. /**
  69771. * Gets or sets the debug canvas size
  69772. * @ignorenaming
  69773. */
  69774. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  69775. this._scene = scene;
  69776. this._audioEngine = BABYLON.Engine.audioEngine;
  69777. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  69778. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  69779. this._webAudioAnalyser.minDecibels = -140;
  69780. this._webAudioAnalyser.maxDecibels = 0;
  69781. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69782. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69783. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  69784. }
  69785. }
  69786. /**
  69787. * Get the number of data values you will have to play with for the visualization
  69788. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  69789. * @returns a number
  69790. */
  69791. Analyser.prototype.getFrequencyBinCount = function () {
  69792. if (this._audioEngine.canUseWebAudio) {
  69793. return this._webAudioAnalyser.frequencyBinCount;
  69794. }
  69795. else {
  69796. return 0;
  69797. }
  69798. };
  69799. /**
  69800. * Gets the current frequency data as a byte array
  69801. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69802. * @returns a Uint8Array
  69803. */
  69804. Analyser.prototype.getByteFrequencyData = function () {
  69805. if (this._audioEngine.canUseWebAudio) {
  69806. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69807. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69808. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  69809. }
  69810. return this._byteFreqs;
  69811. };
  69812. /**
  69813. * Gets the current waveform as a byte array
  69814. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  69815. * @returns a Uint8Array
  69816. */
  69817. Analyser.prototype.getByteTimeDomainData = function () {
  69818. if (this._audioEngine.canUseWebAudio) {
  69819. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69820. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69821. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  69822. }
  69823. return this._byteTime;
  69824. };
  69825. /**
  69826. * Gets the current frequency data as a float array
  69827. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69828. * @returns a Float32Array
  69829. */
  69830. Analyser.prototype.getFloatFrequencyData = function () {
  69831. if (this._audioEngine.canUseWebAudio) {
  69832. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69833. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69834. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  69835. }
  69836. return this._floatFreqs;
  69837. };
  69838. /**
  69839. * Renders the debug canvas
  69840. */
  69841. Analyser.prototype.drawDebugCanvas = function () {
  69842. var _this = this;
  69843. if (this._audioEngine.canUseWebAudio) {
  69844. if (!this._debugCanvas) {
  69845. this._debugCanvas = document.createElement("canvas");
  69846. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  69847. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  69848. this._debugCanvas.style.position = "absolute";
  69849. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  69850. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  69851. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  69852. document.body.appendChild(this._debugCanvas);
  69853. this._registerFunc = function () {
  69854. _this.drawDebugCanvas();
  69855. };
  69856. this._scene.registerBeforeRender(this._registerFunc);
  69857. }
  69858. if (this._registerFunc && this._debugCanvasContext) {
  69859. var workingArray = this.getByteFrequencyData();
  69860. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  69861. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  69862. // Draw the frequency domain chart.
  69863. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  69864. var value = workingArray[i];
  69865. var percent = value / this.BARGRAPHAMPLITUDE;
  69866. var height = this.DEBUGCANVASSIZE.height * percent;
  69867. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  69868. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  69869. var hue = i / this.getFrequencyBinCount() * 360;
  69870. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  69871. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  69872. }
  69873. }
  69874. }
  69875. };
  69876. /**
  69877. * Stops rendering the debug canvas and removes it
  69878. */
  69879. Analyser.prototype.stopDebugCanvas = function () {
  69880. if (this._debugCanvas) {
  69881. if (this._registerFunc) {
  69882. this._scene.unregisterBeforeRender(this._registerFunc);
  69883. this._registerFunc = null;
  69884. }
  69885. document.body.removeChild(this._debugCanvas);
  69886. this._debugCanvas = null;
  69887. this._debugCanvasContext = null;
  69888. }
  69889. };
  69890. /**
  69891. * Connects two audio nodes
  69892. * @param inputAudioNode defines first node to connect
  69893. * @param outputAudioNode defines second node to connect
  69894. */
  69895. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  69896. if (this._audioEngine.canUseWebAudio) {
  69897. inputAudioNode.connect(this._webAudioAnalyser);
  69898. this._webAudioAnalyser.connect(outputAudioNode);
  69899. }
  69900. };
  69901. /**
  69902. * Releases all associated resources
  69903. */
  69904. Analyser.prototype.dispose = function () {
  69905. if (this._audioEngine.canUseWebAudio) {
  69906. this._webAudioAnalyser.disconnect();
  69907. }
  69908. };
  69909. return Analyser;
  69910. }());
  69911. BABYLON.Analyser = Analyser;
  69912. })(BABYLON || (BABYLON = {}));
  69913. //# sourceMappingURL=babylon.analyser.js.map
  69914. var BABYLON;
  69915. (function (BABYLON) {
  69916. /**
  69917. * Wraps one or more Sound objects and selects one with random weight for playback.
  69918. */
  69919. var WeightedSound = /** @class */ (function () {
  69920. /**
  69921. * Creates a new WeightedSound from the list of sounds given.
  69922. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  69923. * @param sounds Array of Sounds that will be selected from.
  69924. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  69925. */
  69926. function WeightedSound(loop, sounds, weights) {
  69927. var _this = this;
  69928. /** When true a Sound will be selected and played when the current playing Sound completes. */
  69929. this.loop = false;
  69930. this._coneInnerAngle = 360;
  69931. this._coneOuterAngle = 360;
  69932. this._volume = 1;
  69933. /** A Sound is currently playing. */
  69934. this.isPlaying = false;
  69935. /** A Sound is currently paused. */
  69936. this.isPaused = false;
  69937. this._sounds = [];
  69938. this._weights = [];
  69939. if (sounds.length !== weights.length) {
  69940. throw new Error('Sounds length does not equal weights length');
  69941. }
  69942. this.loop = loop;
  69943. this._weights = weights;
  69944. // Normalize the weights
  69945. var weightSum = 0;
  69946. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  69947. var weight = weights_1[_i];
  69948. weightSum += weight;
  69949. }
  69950. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  69951. for (var i = 0; i < this._weights.length; i++) {
  69952. this._weights[i] *= invWeightSum;
  69953. }
  69954. this._sounds = sounds;
  69955. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  69956. var sound = _b[_a];
  69957. sound.onEndedObservable.add(function () { _this._onended(); });
  69958. }
  69959. }
  69960. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  69961. /**
  69962. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  69963. */
  69964. get: function () {
  69965. return this._coneInnerAngle;
  69966. },
  69967. /**
  69968. * The size of cone in degress for a directional sound in which there will be no attenuation.
  69969. */
  69970. set: function (value) {
  69971. if (value !== this._coneInnerAngle) {
  69972. if (this._coneOuterAngle < value) {
  69973. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69974. return;
  69975. }
  69976. this._coneInnerAngle = value;
  69977. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69978. var sound = _a[_i];
  69979. sound.directionalConeInnerAngle = value;
  69980. }
  69981. }
  69982. },
  69983. enumerable: true,
  69984. configurable: true
  69985. });
  69986. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  69987. /**
  69988. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69989. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69990. */
  69991. get: function () {
  69992. return this._coneOuterAngle;
  69993. },
  69994. /**
  69995. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69996. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69997. */
  69998. set: function (value) {
  69999. if (value !== this._coneOuterAngle) {
  70000. if (value < this._coneInnerAngle) {
  70001. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70002. return;
  70003. }
  70004. this._coneOuterAngle = value;
  70005. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70006. var sound = _a[_i];
  70007. sound.directionalConeOuterAngle = value;
  70008. }
  70009. }
  70010. },
  70011. enumerable: true,
  70012. configurable: true
  70013. });
  70014. Object.defineProperty(WeightedSound.prototype, "volume", {
  70015. /**
  70016. * Playback volume.
  70017. */
  70018. get: function () {
  70019. return this._volume;
  70020. },
  70021. /**
  70022. * Playback volume.
  70023. */
  70024. set: function (value) {
  70025. if (value !== this._volume) {
  70026. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70027. var sound = _a[_i];
  70028. sound.setVolume(value);
  70029. }
  70030. }
  70031. },
  70032. enumerable: true,
  70033. configurable: true
  70034. });
  70035. WeightedSound.prototype._onended = function () {
  70036. if (this._currentIndex !== undefined) {
  70037. this._sounds[this._currentIndex].autoplay = false;
  70038. }
  70039. if (this.loop && this.isPlaying) {
  70040. this.play();
  70041. }
  70042. else {
  70043. this.isPlaying = false;
  70044. }
  70045. };
  70046. /**
  70047. * Suspend playback
  70048. */
  70049. WeightedSound.prototype.pause = function () {
  70050. this.isPaused = true;
  70051. if (this._currentIndex !== undefined) {
  70052. this._sounds[this._currentIndex].pause();
  70053. }
  70054. };
  70055. /**
  70056. * Stop playback
  70057. */
  70058. WeightedSound.prototype.stop = function () {
  70059. this.isPlaying = false;
  70060. if (this._currentIndex !== undefined) {
  70061. this._sounds[this._currentIndex].stop();
  70062. }
  70063. };
  70064. /**
  70065. * Start playback.
  70066. * @param startOffset Position the clip head at a specific time in seconds.
  70067. */
  70068. WeightedSound.prototype.play = function (startOffset) {
  70069. if (!this.isPaused) {
  70070. this.stop();
  70071. var randomValue = Math.random();
  70072. var total = 0;
  70073. for (var i = 0; i < this._weights.length; i++) {
  70074. total += this._weights[i];
  70075. if (randomValue <= total) {
  70076. this._currentIndex = i;
  70077. break;
  70078. }
  70079. }
  70080. }
  70081. var sound = this._sounds[this._currentIndex];
  70082. if (sound.isReady()) {
  70083. sound.play(0, this.isPaused ? undefined : startOffset);
  70084. }
  70085. else {
  70086. sound.autoplay = true;
  70087. }
  70088. this.isPlaying = true;
  70089. this.isPaused = false;
  70090. };
  70091. return WeightedSound;
  70092. }());
  70093. BABYLON.WeightedSound = WeightedSound;
  70094. })(BABYLON || (BABYLON = {}));
  70095. //# sourceMappingURL=babylon.weightedsound.js.map
  70096. var BABYLON;
  70097. (function (BABYLON) {
  70098. // Adds the parser to the scene parsers.
  70099. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  70100. // TODO: add sound
  70101. var loadedSounds = [];
  70102. var loadedSound;
  70103. container.sounds = container.sounds || [];
  70104. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70105. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70106. var parsedSound = parsedData.sounds[index];
  70107. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70108. if (!parsedSound.url)
  70109. parsedSound.url = parsedSound.name;
  70110. if (!loadedSounds[parsedSound.url]) {
  70111. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70112. loadedSounds[parsedSound.url] = loadedSound;
  70113. container.sounds.push(loadedSound);
  70114. }
  70115. else {
  70116. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70117. }
  70118. }
  70119. else {
  70120. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70121. }
  70122. }
  70123. }
  70124. loadedSounds = [];
  70125. });
  70126. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  70127. get: function () {
  70128. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70129. if (!compo) {
  70130. compo = new AudioSceneComponent(this);
  70131. this._addComponent(compo);
  70132. }
  70133. if (!this._mainSoundTrack) {
  70134. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  70135. }
  70136. return this._mainSoundTrack;
  70137. },
  70138. enumerable: true,
  70139. configurable: true
  70140. });
  70141. BABYLON.Scene.prototype.getSoundByName = function (name) {
  70142. var index;
  70143. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  70144. if (this.mainSoundTrack.soundCollection[index].name === name) {
  70145. return this.mainSoundTrack.soundCollection[index];
  70146. }
  70147. }
  70148. if (this.soundTracks) {
  70149. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  70150. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  70151. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  70152. return this.soundTracks[sdIndex].soundCollection[index];
  70153. }
  70154. }
  70155. }
  70156. }
  70157. return null;
  70158. };
  70159. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  70160. get: function () {
  70161. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70162. if (!compo) {
  70163. compo = new AudioSceneComponent(this);
  70164. this._addComponent(compo);
  70165. }
  70166. return compo.audioEnabled;
  70167. },
  70168. set: function (value) {
  70169. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70170. if (!compo) {
  70171. compo = new AudioSceneComponent(this);
  70172. this._addComponent(compo);
  70173. }
  70174. if (value) {
  70175. compo.enableAudio();
  70176. }
  70177. else {
  70178. compo.disableAudio();
  70179. }
  70180. },
  70181. enumerable: true,
  70182. configurable: true
  70183. });
  70184. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  70185. get: function () {
  70186. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70187. if (!compo) {
  70188. compo = new AudioSceneComponent(this);
  70189. this._addComponent(compo);
  70190. }
  70191. return compo.headphone;
  70192. },
  70193. set: function (value) {
  70194. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70195. if (!compo) {
  70196. compo = new AudioSceneComponent(this);
  70197. this._addComponent(compo);
  70198. }
  70199. if (value) {
  70200. compo.switchAudioModeForHeadphones();
  70201. }
  70202. else {
  70203. compo.switchAudioModeForNormalSpeakers();
  70204. }
  70205. },
  70206. enumerable: true,
  70207. configurable: true
  70208. });
  70209. /**
  70210. * Defines the sound scene component responsible to manage any sounds
  70211. * in a given scene.
  70212. */
  70213. var AudioSceneComponent = /** @class */ (function () {
  70214. /**
  70215. * Creates a new instance of the component for the given scene
  70216. * @param scene Defines the scene to register the component in
  70217. */
  70218. function AudioSceneComponent(scene) {
  70219. /**
  70220. * The component name helpfull to identify the component in the list of scene components.
  70221. */
  70222. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  70223. this._audioEnabled = true;
  70224. this._headphone = false;
  70225. this.scene = scene;
  70226. scene.soundTracks = new Array();
  70227. scene.sounds = new Array();
  70228. }
  70229. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  70230. /**
  70231. * Gets whether audio is enabled or not.
  70232. * Please use related enable/disable method to switch state.
  70233. */
  70234. get: function () {
  70235. return this._audioEnabled;
  70236. },
  70237. enumerable: true,
  70238. configurable: true
  70239. });
  70240. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70241. /**
  70242. * Gets whether audio is outputing to headphone or not.
  70243. * Please use the according Switch methods to change output.
  70244. */
  70245. get: function () {
  70246. return this._headphone;
  70247. },
  70248. enumerable: true,
  70249. configurable: true
  70250. });
  70251. /**
  70252. * Registers the component in a given scene
  70253. */
  70254. AudioSceneComponent.prototype.register = function () {
  70255. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70256. };
  70257. /**
  70258. * Rebuilds the elements related to this component in case of
  70259. * context lost for instance.
  70260. */
  70261. AudioSceneComponent.prototype.rebuild = function () {
  70262. // Nothing to do here. (Not rendering related)
  70263. };
  70264. /**
  70265. * Serializes the component data to the specified json object
  70266. * @param serializationObject The object to serialize to
  70267. */
  70268. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  70269. serializationObject.sounds = [];
  70270. if (this.scene.soundTracks) {
  70271. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  70272. var soundtrack = this.scene.soundTracks[index];
  70273. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70274. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70275. }
  70276. }
  70277. }
  70278. };
  70279. /**
  70280. * Adds all the element from the container to the scene
  70281. * @param container the container holding the elements
  70282. */
  70283. AudioSceneComponent.prototype.addFromContainer = function (container) {
  70284. var _this = this;
  70285. if (!container.sounds) {
  70286. return;
  70287. }
  70288. container.sounds.forEach(function (sound) {
  70289. sound.play();
  70290. sound.autoplay = true;
  70291. _this.scene.mainSoundTrack.AddSound(sound);
  70292. });
  70293. };
  70294. /**
  70295. * Removes all the elements in the container from the scene
  70296. * @param container contains the elements to remove
  70297. */
  70298. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  70299. var _this = this;
  70300. if (!container.sounds) {
  70301. return;
  70302. }
  70303. container.sounds.forEach(function (sound) {
  70304. sound.stop();
  70305. sound.autoplay = false;
  70306. _this.scene.mainSoundTrack.RemoveSound(sound);
  70307. });
  70308. };
  70309. /**
  70310. * Disposes the component and the associated ressources.
  70311. */
  70312. AudioSceneComponent.prototype.dispose = function () {
  70313. var scene = this.scene;
  70314. if (scene._mainSoundTrack) {
  70315. scene.mainSoundTrack.dispose();
  70316. }
  70317. if (scene.soundTracks) {
  70318. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  70319. scene.soundTracks[scIndex].dispose();
  70320. }
  70321. }
  70322. };
  70323. /**
  70324. * Disables audio in the associated scene.
  70325. */
  70326. AudioSceneComponent.prototype.disableAudio = function () {
  70327. var scene = this.scene;
  70328. this._audioEnabled = false;
  70329. var i;
  70330. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70331. scene.mainSoundTrack.soundCollection[i].pause();
  70332. }
  70333. if (scene.soundTracks) {
  70334. for (i = 0; i < scene.soundTracks.length; i++) {
  70335. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70336. scene.soundTracks[i].soundCollection[j].pause();
  70337. }
  70338. }
  70339. }
  70340. };
  70341. /**
  70342. * Enables audio in the associated scene.
  70343. */
  70344. AudioSceneComponent.prototype.enableAudio = function () {
  70345. var scene = this.scene;
  70346. this._audioEnabled = true;
  70347. var i;
  70348. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70349. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  70350. scene.mainSoundTrack.soundCollection[i].play();
  70351. }
  70352. }
  70353. if (scene.soundTracks) {
  70354. for (i = 0; i < scene.soundTracks.length; i++) {
  70355. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70356. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  70357. scene.soundTracks[i].soundCollection[j].play();
  70358. }
  70359. }
  70360. }
  70361. }
  70362. };
  70363. /**
  70364. * Switch audio to headphone output.
  70365. */
  70366. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  70367. var scene = this.scene;
  70368. this._headphone = true;
  70369. scene.mainSoundTrack.switchPanningModelToHRTF();
  70370. if (scene.soundTracks) {
  70371. for (var i = 0; i < scene.soundTracks.length; i++) {
  70372. scene.soundTracks[i].switchPanningModelToHRTF();
  70373. }
  70374. }
  70375. };
  70376. /**
  70377. * Switch audio to normal speakers.
  70378. */
  70379. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  70380. var scene = this.scene;
  70381. this._headphone = false;
  70382. scene.mainSoundTrack.switchPanningModelToEqualPower();
  70383. if (scene.soundTracks) {
  70384. for (var i = 0; i < scene.soundTracks.length; i++) {
  70385. scene.soundTracks[i].switchPanningModelToEqualPower();
  70386. }
  70387. }
  70388. };
  70389. AudioSceneComponent.prototype._afterRender = function () {
  70390. var scene = this.scene;
  70391. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  70392. return;
  70393. }
  70394. var listeningCamera;
  70395. var audioEngine = BABYLON.Engine.audioEngine;
  70396. if (scene.activeCameras.length > 0) {
  70397. listeningCamera = scene.activeCameras[0];
  70398. }
  70399. else {
  70400. listeningCamera = scene.activeCamera;
  70401. }
  70402. if (listeningCamera && audioEngine.audioContext) {
  70403. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  70404. // for VR cameras
  70405. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  70406. listeningCamera = listeningCamera.rigCameras[0];
  70407. }
  70408. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  70409. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  70410. cameraDirection.normalize();
  70411. // To avoid some errors on GearVR
  70412. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  70413. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  70414. }
  70415. var i;
  70416. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70417. var sound = scene.mainSoundTrack.soundCollection[i];
  70418. if (sound.useCustomAttenuation) {
  70419. sound.updateDistanceFromListener();
  70420. }
  70421. }
  70422. if (scene.soundTracks) {
  70423. for (i = 0; i < scene.soundTracks.length; i++) {
  70424. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70425. sound = scene.soundTracks[i].soundCollection[j];
  70426. if (sound.useCustomAttenuation) {
  70427. sound.updateDistanceFromListener();
  70428. }
  70429. }
  70430. }
  70431. }
  70432. }
  70433. };
  70434. return AudioSceneComponent;
  70435. }());
  70436. BABYLON.AudioSceneComponent = AudioSceneComponent;
  70437. })(BABYLON || (BABYLON = {}));
  70438. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  70439. var BABYLON;
  70440. (function (BABYLON) {
  70441. /**
  70442. * This defines an action helpful to play a defined sound on a triggered action.
  70443. */
  70444. var PlaySoundAction = /** @class */ (function (_super) {
  70445. __extends(PlaySoundAction, _super);
  70446. /**
  70447. * Instantiate the action
  70448. * @param triggerOptions defines the trigger options
  70449. * @param sound defines the sound to play
  70450. * @param condition defines the trigger related conditions
  70451. */
  70452. function PlaySoundAction(triggerOptions, sound, condition) {
  70453. var _this = _super.call(this, triggerOptions, condition) || this;
  70454. _this._sound = sound;
  70455. return _this;
  70456. }
  70457. /** @hidden */
  70458. PlaySoundAction.prototype._prepare = function () {
  70459. };
  70460. /**
  70461. * Execute the action and play the sound.
  70462. */
  70463. PlaySoundAction.prototype.execute = function () {
  70464. if (this._sound !== undefined)
  70465. this._sound.play();
  70466. };
  70467. /**
  70468. * Serializes the actions and its related information.
  70469. * @param parent defines the object to serialize in
  70470. * @returns the serialized object
  70471. */
  70472. PlaySoundAction.prototype.serialize = function (parent) {
  70473. return _super.prototype._serialize.call(this, {
  70474. name: "PlaySoundAction",
  70475. properties: [{ name: "sound", value: this._sound.name }]
  70476. }, parent);
  70477. };
  70478. return PlaySoundAction;
  70479. }(BABYLON.Action));
  70480. BABYLON.PlaySoundAction = PlaySoundAction;
  70481. /**
  70482. * This defines an action helpful to stop a defined sound on a triggered action.
  70483. */
  70484. var StopSoundAction = /** @class */ (function (_super) {
  70485. __extends(StopSoundAction, _super);
  70486. /**
  70487. * Instantiate the action
  70488. * @param triggerOptions defines the trigger options
  70489. * @param sound defines the sound to stop
  70490. * @param condition defines the trigger related conditions
  70491. */
  70492. function StopSoundAction(triggerOptions, sound, condition) {
  70493. var _this = _super.call(this, triggerOptions, condition) || this;
  70494. _this._sound = sound;
  70495. return _this;
  70496. }
  70497. /** @hidden */
  70498. StopSoundAction.prototype._prepare = function () {
  70499. };
  70500. /**
  70501. * Execute the action and stop the sound.
  70502. */
  70503. StopSoundAction.prototype.execute = function () {
  70504. if (this._sound !== undefined)
  70505. this._sound.stop();
  70506. };
  70507. /**
  70508. * Serializes the actions and its related information.
  70509. * @param parent defines the object to serialize in
  70510. * @returns the serialized object
  70511. */
  70512. StopSoundAction.prototype.serialize = function (parent) {
  70513. return _super.prototype._serialize.call(this, {
  70514. name: "StopSoundAction",
  70515. properties: [{ name: "sound", value: this._sound.name }]
  70516. }, parent);
  70517. };
  70518. return StopSoundAction;
  70519. }(BABYLON.Action));
  70520. BABYLON.StopSoundAction = StopSoundAction;
  70521. })(BABYLON || (BABYLON = {}));
  70522. //# sourceMappingURL=babylon.directAudioActions.js.map
  70523. var BABYLON;
  70524. (function (BABYLON) {
  70525. /**
  70526. * Class for creating a cube texture
  70527. */
  70528. var CubeTexture = /** @class */ (function (_super) {
  70529. __extends(CubeTexture, _super);
  70530. /**
  70531. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  70532. * as prefiltered data.
  70533. * @param rootUrl defines the url of the texture or the root name of the six images
  70534. * @param scene defines the scene the texture is attached to
  70535. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  70536. * @param noMipmap defines if mipmaps should be created or not
  70537. * @param files defines the six files to load for the different faces
  70538. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  70539. * @param onError defines a callback triggered in case of error during load
  70540. * @param format defines the internal format to use for the texture once loaded
  70541. * @param prefiltered defines whether or not the texture is created from prefiltered data
  70542. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  70543. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70544. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70545. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70546. * @return the cube texture
  70547. */
  70548. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  70549. if (extensions === void 0) { extensions = null; }
  70550. if (noMipmap === void 0) { noMipmap = false; }
  70551. if (files === void 0) { files = null; }
  70552. if (onLoad === void 0) { onLoad = null; }
  70553. if (onError === void 0) { onError = null; }
  70554. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70555. if (prefiltered === void 0) { prefiltered = false; }
  70556. if (forcedExtension === void 0) { forcedExtension = null; }
  70557. if (createPolynomials === void 0) { createPolynomials = false; }
  70558. if (lodScale === void 0) { lodScale = 0.8; }
  70559. if (lodOffset === void 0) { lodOffset = 0; }
  70560. var _this = _super.call(this, scene) || this;
  70561. /**
  70562. * Gets or sets the center of the bounding box associated with the cube texture.
  70563. * It must define where the camera used to render the texture was set
  70564. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70565. */
  70566. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70567. _this._rotationY = 0;
  70568. /** @hidden */
  70569. _this._prefiltered = false;
  70570. _this.name = rootUrl;
  70571. _this.url = rootUrl;
  70572. _this._noMipmap = noMipmap;
  70573. _this.hasAlpha = false;
  70574. _this._format = format;
  70575. _this.isCube = true;
  70576. _this._textureMatrix = BABYLON.Matrix.Identity();
  70577. _this._createPolynomials = createPolynomials;
  70578. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70579. if (!rootUrl && !files) {
  70580. return _this;
  70581. }
  70582. var lastDot = rootUrl.lastIndexOf(".");
  70583. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  70584. var isDDS = (extension === ".dds");
  70585. var isEnv = (extension === ".env");
  70586. if (isEnv) {
  70587. _this.gammaSpace = false;
  70588. _this._prefiltered = false;
  70589. }
  70590. else {
  70591. _this._prefiltered = prefiltered;
  70592. if (prefiltered) {
  70593. _this.gammaSpace = false;
  70594. }
  70595. }
  70596. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  70597. if (!files) {
  70598. if (!isEnv && !isDDS && !extensions) {
  70599. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  70600. }
  70601. files = [];
  70602. if (extensions) {
  70603. for (var index = 0; index < extensions.length; index++) {
  70604. files.push(rootUrl + extensions[index]);
  70605. }
  70606. }
  70607. }
  70608. _this._files = files;
  70609. if (!_this._texture) {
  70610. if (!scene.useDelayedTextureLoading) {
  70611. if (prefiltered) {
  70612. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  70613. }
  70614. else {
  70615. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  70616. }
  70617. }
  70618. else {
  70619. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70620. }
  70621. }
  70622. else if (onLoad) {
  70623. if (_this._texture.isReady) {
  70624. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  70625. }
  70626. else {
  70627. _this._texture.onLoadedObservable.add(onLoad);
  70628. }
  70629. }
  70630. return _this;
  70631. }
  70632. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  70633. /**
  70634. * Returns the bounding box size
  70635. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70636. */
  70637. get: function () {
  70638. return this._boundingBoxSize;
  70639. },
  70640. /**
  70641. * Gets or sets the size of the bounding box associated with the cube texture
  70642. * When defined, the cubemap will switch to local mode
  70643. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70644. * @example https://www.babylonjs-playground.com/#RNASML
  70645. */
  70646. set: function (value) {
  70647. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70648. return;
  70649. }
  70650. this._boundingBoxSize = value;
  70651. var scene = this.getScene();
  70652. if (scene) {
  70653. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70654. }
  70655. },
  70656. enumerable: true,
  70657. configurable: true
  70658. });
  70659. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  70660. /**
  70661. * Gets texture matrix rotation angle around Y axis radians.
  70662. */
  70663. get: function () {
  70664. return this._rotationY;
  70665. },
  70666. /**
  70667. * Sets texture matrix rotation angle around Y axis in radians.
  70668. */
  70669. set: function (value) {
  70670. this._rotationY = value;
  70671. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  70672. },
  70673. enumerable: true,
  70674. configurable: true
  70675. });
  70676. /**
  70677. * Creates a cube texture from an array of image urls
  70678. * @param files defines an array of image urls
  70679. * @param scene defines the hosting scene
  70680. * @param noMipmap specifies if mip maps are not used
  70681. * @returns a cube texture
  70682. */
  70683. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  70684. var rootUrlKey = "";
  70685. files.forEach(function (url) { return rootUrlKey += url; });
  70686. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  70687. };
  70688. /**
  70689. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  70690. * @param url defines the url of the prefiltered texture
  70691. * @param scene defines the scene the texture is attached to
  70692. * @param forcedExtension defines the extension of the file if different from the url
  70693. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70694. * @return the prefiltered texture
  70695. */
  70696. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  70697. if (forcedExtension === void 0) { forcedExtension = null; }
  70698. if (createPolynomials === void 0) { createPolynomials = true; }
  70699. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  70700. };
  70701. /**
  70702. * Delays loading of the cube texture
  70703. */
  70704. CubeTexture.prototype.delayLoad = function () {
  70705. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  70706. return;
  70707. }
  70708. var scene = this.getScene();
  70709. if (!scene) {
  70710. return;
  70711. }
  70712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  70713. this._texture = this._getFromCache(this.url, this._noMipmap);
  70714. if (!this._texture) {
  70715. if (this._prefiltered) {
  70716. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  70717. }
  70718. else {
  70719. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  70720. }
  70721. }
  70722. };
  70723. /**
  70724. * Returns the reflection texture matrix
  70725. * @returns the reflection texture matrix
  70726. */
  70727. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  70728. return this._textureMatrix;
  70729. };
  70730. /**
  70731. * Sets the reflection texture matrix
  70732. * @param value Reflection texture matrix
  70733. */
  70734. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  70735. this._textureMatrix = value;
  70736. };
  70737. /**
  70738. * Parses text to create a cube texture
  70739. * @param parsedTexture define the serialized text to read from
  70740. * @param scene defines the hosting scene
  70741. * @param rootUrl defines the root url of the cube texture
  70742. * @returns a cube texture
  70743. */
  70744. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  70745. var texture = BABYLON.SerializationHelper.Parse(function () {
  70746. var prefiltered = false;
  70747. if (parsedTexture.prefiltered) {
  70748. prefiltered = parsedTexture.prefiltered;
  70749. }
  70750. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  70751. }, parsedTexture, scene);
  70752. // Local Cubemaps
  70753. if (parsedTexture.boundingBoxPosition) {
  70754. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  70755. }
  70756. if (parsedTexture.boundingBoxSize) {
  70757. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  70758. }
  70759. // Animations
  70760. if (parsedTexture.animations) {
  70761. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  70762. var parsedAnimation = parsedTexture.animations[animationIndex];
  70763. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70764. }
  70765. }
  70766. return texture;
  70767. };
  70768. /**
  70769. * Makes a clone, or deep copy, of the cube texture
  70770. * @returns a new cube texture
  70771. */
  70772. CubeTexture.prototype.clone = function () {
  70773. var _this = this;
  70774. return BABYLON.SerializationHelper.Clone(function () {
  70775. var scene = _this.getScene();
  70776. if (!scene) {
  70777. return _this;
  70778. }
  70779. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  70780. }, this);
  70781. };
  70782. __decorate([
  70783. BABYLON.serialize("rotationY")
  70784. ], CubeTexture.prototype, "rotationY", null);
  70785. return CubeTexture;
  70786. }(BABYLON.BaseTexture));
  70787. BABYLON.CubeTexture = CubeTexture;
  70788. })(BABYLON || (BABYLON = {}));
  70789. //# sourceMappingURL=babylon.cubeTexture.js.map
  70790. var BABYLON;
  70791. (function (BABYLON) {
  70792. /**
  70793. * Raw cube texture where the raw buffers are passed in
  70794. */
  70795. var RawCubeTexture = /** @class */ (function (_super) {
  70796. __extends(RawCubeTexture, _super);
  70797. /**
  70798. * Creates a cube texture where the raw buffers are passed in.
  70799. * @param scene defines the scene the texture is attached to
  70800. * @param data defines the array of data to use to create each face
  70801. * @param size defines the size of the textures
  70802. * @param format defines the format of the data
  70803. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  70804. * @param generateMipMaps defines if the engine should generate the mip levels
  70805. * @param invertY defines if data must be stored with Y axis inverted
  70806. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  70807. * @param compression defines the compression used (null by default)
  70808. */
  70809. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  70810. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70811. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70812. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70813. if (invertY === void 0) { invertY = false; }
  70814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70815. if (compression === void 0) { compression = null; }
  70816. var _this = _super.call(this, "", scene) || this;
  70817. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  70818. return _this;
  70819. }
  70820. /**
  70821. * Updates the raw cube texture.
  70822. * @param data defines the data to store
  70823. * @param format defines the data format
  70824. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  70825. * @param invertY defines if data must be stored with Y axis inverted
  70826. * @param compression defines the compression used (null by default)
  70827. * @param level defines which level of the texture to update
  70828. */
  70829. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  70830. if (compression === void 0) { compression = null; }
  70831. if (level === void 0) { level = 0; }
  70832. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  70833. };
  70834. /**
  70835. * Updates a raw cube texture with RGBD encoded data.
  70836. * @param data defines the array of data [mipmap][face] to use to create each face
  70837. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  70838. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70839. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70840. * @returns a promsie that resolves when the operation is complete
  70841. */
  70842. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  70843. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  70844. if (lodScale === void 0) { lodScale = 0.8; }
  70845. if (lodOffset === void 0) { lodOffset = 0; }
  70846. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  70847. };
  70848. /**
  70849. * Clones the raw cube texture.
  70850. * @return a new cube texture
  70851. */
  70852. RawCubeTexture.prototype.clone = function () {
  70853. var _this = this;
  70854. return BABYLON.SerializationHelper.Clone(function () {
  70855. var scene = _this.getScene();
  70856. var internalTexture = _this._texture;
  70857. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  70858. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  70859. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  70860. }
  70861. return texture;
  70862. }, this);
  70863. };
  70864. /** @hidden */
  70865. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  70866. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  70867. internalTexture._bufferViewArrayArray = data;
  70868. internalTexture._lodGenerationScale = lodScale;
  70869. internalTexture._lodGenerationOffset = lodOffset;
  70870. internalTexture._sphericalPolynomial = sphericalPolynomial;
  70871. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  70872. internalTexture.isReady = true;
  70873. });
  70874. };
  70875. return RawCubeTexture;
  70876. }(BABYLON.CubeTexture));
  70877. BABYLON.RawCubeTexture = RawCubeTexture;
  70878. })(BABYLON || (BABYLON = {}));
  70879. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  70880. var BABYLON;
  70881. (function (BABYLON) {
  70882. var RenderTargetTexture = /** @class */ (function (_super) {
  70883. __extends(RenderTargetTexture, _super);
  70884. /**
  70885. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  70886. * or used a shadow, depth texture...
  70887. * @param name The friendly name of the texture
  70888. * @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)
  70889. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  70890. * @param generateMipMaps True if mip maps need to be generated after render.
  70891. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  70892. * @param type The type of the buffer in the RTT (int, half float, float...)
  70893. * @param isCube True if a cube texture needs to be created
  70894. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  70895. * @param generateDepthBuffer True to generate a depth buffer
  70896. * @param generateStencilBuffer True to generate a stencil buffer
  70897. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  70898. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  70899. */
  70900. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  70901. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  70902. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70903. if (isCube === void 0) { isCube = false; }
  70904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70905. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70906. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  70907. if (isMulti === void 0) { isMulti = false; }
  70908. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70909. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70910. _this.isCube = isCube;
  70911. _this.renderParticles = true;
  70912. _this.renderSprites = false;
  70913. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  70914. _this.ignoreCameraViewport = false;
  70915. // Events
  70916. /**
  70917. * An event triggered when the texture is unbind.
  70918. */
  70919. _this.onBeforeBindObservable = new BABYLON.Observable();
  70920. /**
  70921. * An event triggered when the texture is unbind.
  70922. */
  70923. _this.onAfterUnbindObservable = new BABYLON.Observable();
  70924. /**
  70925. * An event triggered before rendering the texture
  70926. */
  70927. _this.onBeforeRenderObservable = new BABYLON.Observable();
  70928. /**
  70929. * An event triggered after rendering the texture
  70930. */
  70931. _this.onAfterRenderObservable = new BABYLON.Observable();
  70932. /**
  70933. * An event triggered after the texture clear
  70934. */
  70935. _this.onClearObservable = new BABYLON.Observable();
  70936. _this._currentRefreshId = -1;
  70937. _this._refreshRate = 1;
  70938. _this._samples = 1;
  70939. /**
  70940. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  70941. * It must define where the camera used to render the texture is set
  70942. */
  70943. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70944. scene = _this.getScene();
  70945. if (!scene) {
  70946. return _this;
  70947. }
  70948. _this.renderList = new Array();
  70949. _this._engine = scene.getEngine();
  70950. _this.name = name;
  70951. _this.isRenderTarget = true;
  70952. _this._initialSizeParameter = size;
  70953. _this._processSizeParameter(size);
  70954. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  70955. });
  70956. _this._generateMipMaps = generateMipMaps ? true : false;
  70957. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  70958. // Rendering groups
  70959. _this._renderingManager = new BABYLON.RenderingManager(scene);
  70960. _this._renderingManager._useSceneAutoClearSetup = true;
  70961. if (isMulti) {
  70962. return _this;
  70963. }
  70964. _this._renderTargetOptions = {
  70965. generateMipMaps: generateMipMaps,
  70966. type: type,
  70967. format: format,
  70968. samplingMode: samplingMode,
  70969. generateDepthBuffer: generateDepthBuffer,
  70970. generateStencilBuffer: generateStencilBuffer
  70971. };
  70972. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  70973. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70974. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70975. }
  70976. if (isCube) {
  70977. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  70978. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  70979. _this._textureMatrix = BABYLON.Matrix.Identity();
  70980. }
  70981. else {
  70982. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  70983. }
  70984. return _this;
  70985. }
  70986. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  70987. get: function () {
  70988. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  70989. },
  70990. enumerable: true,
  70991. configurable: true
  70992. });
  70993. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  70994. get: function () {
  70995. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  70996. },
  70997. enumerable: true,
  70998. configurable: true
  70999. });
  71000. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  71001. get: function () {
  71002. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  71003. },
  71004. enumerable: true,
  71005. configurable: true
  71006. });
  71007. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71008. /**
  71009. * Use this list to define the list of mesh you want to render.
  71010. */
  71011. get: function () {
  71012. return this._renderList;
  71013. },
  71014. set: function (value) {
  71015. this._renderList = value;
  71016. if (this._renderList) {
  71017. this._hookArray(this._renderList);
  71018. }
  71019. },
  71020. enumerable: true,
  71021. configurable: true
  71022. });
  71023. RenderTargetTexture.prototype._hookArray = function (array) {
  71024. var _this = this;
  71025. var oldPush = array.push;
  71026. array.push = function () {
  71027. var items = [];
  71028. for (var _i = 0; _i < arguments.length; _i++) {
  71029. items[_i] = arguments[_i];
  71030. }
  71031. var wasEmpty = array.length === 0;
  71032. var result = oldPush.apply(array, items);
  71033. if (wasEmpty) {
  71034. _this.getScene().meshes.forEach(function (mesh) {
  71035. mesh._markSubMeshesAsLightDirty();
  71036. });
  71037. }
  71038. return result;
  71039. };
  71040. var oldSplice = array.splice;
  71041. array.splice = function (index, deleteCount) {
  71042. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71043. if (array.length === 0) {
  71044. _this.getScene().meshes.forEach(function (mesh) {
  71045. mesh._markSubMeshesAsLightDirty();
  71046. });
  71047. }
  71048. return deleted;
  71049. };
  71050. };
  71051. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  71052. set: function (callback) {
  71053. if (this._onAfterUnbindObserver) {
  71054. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  71055. }
  71056. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  71057. },
  71058. enumerable: true,
  71059. configurable: true
  71060. });
  71061. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  71062. set: function (callback) {
  71063. if (this._onBeforeRenderObserver) {
  71064. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71065. }
  71066. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71067. },
  71068. enumerable: true,
  71069. configurable: true
  71070. });
  71071. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  71072. set: function (callback) {
  71073. if (this._onAfterRenderObserver) {
  71074. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71075. }
  71076. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71077. },
  71078. enumerable: true,
  71079. configurable: true
  71080. });
  71081. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  71082. set: function (callback) {
  71083. if (this._onClearObserver) {
  71084. this.onClearObservable.remove(this._onClearObserver);
  71085. }
  71086. this._onClearObserver = this.onClearObservable.add(callback);
  71087. },
  71088. enumerable: true,
  71089. configurable: true
  71090. });
  71091. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  71092. get: function () {
  71093. return this._renderTargetOptions;
  71094. },
  71095. enumerable: true,
  71096. configurable: true
  71097. });
  71098. RenderTargetTexture.prototype._onRatioRescale = function () {
  71099. if (this._sizeRatio) {
  71100. this.resize(this._initialSizeParameter);
  71101. }
  71102. };
  71103. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  71104. get: function () {
  71105. return this._boundingBoxSize;
  71106. },
  71107. /**
  71108. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  71109. * When defined, the cubemap will switch to local mode
  71110. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71111. * @example https://www.babylonjs-playground.com/#RNASML
  71112. */
  71113. set: function (value) {
  71114. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71115. return;
  71116. }
  71117. this._boundingBoxSize = value;
  71118. var scene = this.getScene();
  71119. if (scene) {
  71120. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71121. }
  71122. },
  71123. enumerable: true,
  71124. configurable: true
  71125. });
  71126. /**
  71127. * Creates a depth stencil texture.
  71128. * This is only available in WebGL 2 or with the depth texture extension available.
  71129. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  71130. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  71131. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  71132. */
  71133. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  71134. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  71135. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  71136. if (generateStencil === void 0) { generateStencil = false; }
  71137. if (!this.getScene()) {
  71138. return;
  71139. }
  71140. var engine = this.getScene().getEngine();
  71141. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  71142. bilinearFiltering: bilinearFiltering,
  71143. comparisonFunction: comparisonFunction,
  71144. generateStencil: generateStencil,
  71145. isCube: this.isCube
  71146. });
  71147. engine.setFrameBufferDepthStencilTexture(this);
  71148. };
  71149. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  71150. if (size.ratio) {
  71151. this._sizeRatio = size.ratio;
  71152. this._size = {
  71153. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  71154. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  71155. };
  71156. }
  71157. else {
  71158. this._size = size;
  71159. }
  71160. };
  71161. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  71162. get: function () {
  71163. return this._samples;
  71164. },
  71165. set: function (value) {
  71166. if (this._samples === value) {
  71167. return;
  71168. }
  71169. var scene = this.getScene();
  71170. if (!scene) {
  71171. return;
  71172. }
  71173. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  71174. },
  71175. enumerable: true,
  71176. configurable: true
  71177. });
  71178. /**
  71179. * Resets the refresh counter of the texture and start bak from scratch.
  71180. * Could be usefull to regenerate the texture if it is setup to render only once.
  71181. */
  71182. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  71183. this._currentRefreshId = -1;
  71184. };
  71185. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  71186. /**
  71187. * Define the refresh rate of the texture or the rendering frequency.
  71188. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71189. */
  71190. get: function () {
  71191. return this._refreshRate;
  71192. },
  71193. set: function (value) {
  71194. this._refreshRate = value;
  71195. this.resetRefreshCounter();
  71196. },
  71197. enumerable: true,
  71198. configurable: true
  71199. });
  71200. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  71201. if (!this._postProcessManager) {
  71202. var scene = this.getScene();
  71203. if (!scene) {
  71204. return;
  71205. }
  71206. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  71207. this._postProcesses = new Array();
  71208. }
  71209. this._postProcesses.push(postProcess);
  71210. this._postProcesses[0].autoClear = false;
  71211. };
  71212. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  71213. if (!this._postProcesses) {
  71214. return;
  71215. }
  71216. if (dispose) {
  71217. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  71218. var postProcess = _a[_i];
  71219. postProcess.dispose();
  71220. }
  71221. }
  71222. this._postProcesses = [];
  71223. };
  71224. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  71225. if (!this._postProcesses) {
  71226. return;
  71227. }
  71228. var index = this._postProcesses.indexOf(postProcess);
  71229. if (index === -1) {
  71230. return;
  71231. }
  71232. this._postProcesses.splice(index, 1);
  71233. if (this._postProcesses.length > 0) {
  71234. this._postProcesses[0].autoClear = false;
  71235. }
  71236. };
  71237. /** @hidden */
  71238. RenderTargetTexture.prototype._shouldRender = function () {
  71239. if (this._currentRefreshId === -1) { // At least render once
  71240. this._currentRefreshId = 1;
  71241. return true;
  71242. }
  71243. if (this.refreshRate === this._currentRefreshId) {
  71244. this._currentRefreshId = 1;
  71245. return true;
  71246. }
  71247. this._currentRefreshId++;
  71248. return false;
  71249. };
  71250. RenderTargetTexture.prototype.getRenderSize = function () {
  71251. if (this._size.width) {
  71252. return this._size.width;
  71253. }
  71254. return this._size;
  71255. };
  71256. RenderTargetTexture.prototype.getRenderWidth = function () {
  71257. if (this._size.width) {
  71258. return this._size.width;
  71259. }
  71260. return this._size;
  71261. };
  71262. RenderTargetTexture.prototype.getRenderHeight = function () {
  71263. if (this._size.width) {
  71264. return this._size.height;
  71265. }
  71266. return this._size;
  71267. };
  71268. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  71269. get: function () {
  71270. return true;
  71271. },
  71272. enumerable: true,
  71273. configurable: true
  71274. });
  71275. RenderTargetTexture.prototype.scale = function (ratio) {
  71276. var newSize = this.getRenderSize() * ratio;
  71277. this.resize(newSize);
  71278. };
  71279. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  71280. if (this.isCube) {
  71281. return this._textureMatrix;
  71282. }
  71283. return _super.prototype.getReflectionTextureMatrix.call(this);
  71284. };
  71285. RenderTargetTexture.prototype.resize = function (size) {
  71286. this.releaseInternalTexture();
  71287. var scene = this.getScene();
  71288. if (!scene) {
  71289. return;
  71290. }
  71291. this._processSizeParameter(size);
  71292. if (this.isCube) {
  71293. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  71294. }
  71295. else {
  71296. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  71297. }
  71298. };
  71299. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  71300. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  71301. if (dumpForDebug === void 0) { dumpForDebug = false; }
  71302. var scene = this.getScene();
  71303. if (!scene) {
  71304. return;
  71305. }
  71306. var engine = scene.getEngine();
  71307. if (this.useCameraPostProcesses !== undefined) {
  71308. useCameraPostProcess = this.useCameraPostProcesses;
  71309. }
  71310. if (this._waitingRenderList) {
  71311. this.renderList = [];
  71312. for (var index = 0; index < this._waitingRenderList.length; index++) {
  71313. var id = this._waitingRenderList[index];
  71314. var mesh_1 = scene.getMeshByID(id);
  71315. if (mesh_1) {
  71316. this.renderList.push(mesh_1);
  71317. }
  71318. }
  71319. delete this._waitingRenderList;
  71320. }
  71321. // Is predicate defined?
  71322. if (this.renderListPredicate) {
  71323. if (this.renderList) {
  71324. this.renderList.splice(0); // Clear previous renderList
  71325. }
  71326. else {
  71327. this.renderList = [];
  71328. }
  71329. var scene = this.getScene();
  71330. if (!scene) {
  71331. return;
  71332. }
  71333. var sceneMeshes = scene.meshes;
  71334. for (var index = 0; index < sceneMeshes.length; index++) {
  71335. var mesh = sceneMeshes[index];
  71336. if (this.renderListPredicate(mesh)) {
  71337. this.renderList.push(mesh);
  71338. }
  71339. }
  71340. }
  71341. this.onBeforeBindObservable.notifyObservers(this);
  71342. // Set custom projection.
  71343. // Needs to be before binding to prevent changing the aspect ratio.
  71344. var camera;
  71345. if (this.activeCamera) {
  71346. camera = this.activeCamera;
  71347. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71348. if (this.activeCamera !== scene.activeCamera) {
  71349. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  71350. }
  71351. }
  71352. else {
  71353. camera = scene.activeCamera;
  71354. if (camera) {
  71355. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71356. }
  71357. }
  71358. // Prepare renderingManager
  71359. this._renderingManager.reset();
  71360. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  71361. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  71362. var sceneRenderId = scene.getRenderId();
  71363. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  71364. var mesh = currentRenderList[meshIndex];
  71365. if (mesh) {
  71366. if (!mesh.isReady(this.refreshRate === 0)) {
  71367. this.resetRefreshCounter();
  71368. continue;
  71369. }
  71370. mesh._preActivateForIntermediateRendering(sceneRenderId);
  71371. var isMasked = void 0;
  71372. if (!this.renderList && camera) {
  71373. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  71374. }
  71375. else {
  71376. isMasked = false;
  71377. }
  71378. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  71379. mesh._activate(sceneRenderId);
  71380. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  71381. var subMesh = mesh.subMeshes[subIndex];
  71382. scene._activeIndices.addCount(subMesh.indexCount, false);
  71383. this._renderingManager.dispatch(subMesh, mesh);
  71384. }
  71385. }
  71386. }
  71387. }
  71388. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  71389. var particleSystem = scene.particleSystems[particleIndex];
  71390. var emitter = particleSystem.emitter;
  71391. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  71392. continue;
  71393. }
  71394. if (currentRenderList.indexOf(emitter) >= 0) {
  71395. this._renderingManager.dispatchParticles(particleSystem);
  71396. }
  71397. }
  71398. if (this.isCube) {
  71399. for (var face = 0; face < 6; face++) {
  71400. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71401. scene.incrementRenderId();
  71402. scene.resetCachedMaterial();
  71403. }
  71404. }
  71405. else {
  71406. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71407. }
  71408. this.onAfterUnbindObservable.notifyObservers(this);
  71409. if (scene.activeCamera) {
  71410. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  71411. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  71412. }
  71413. engine.setViewport(scene.activeCamera.viewport);
  71414. }
  71415. scene.resetCachedMaterial();
  71416. };
  71417. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  71418. var minimum = 128;
  71419. var x = renderDimension * scale;
  71420. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  71421. // Ensure we don't exceed the render dimension (while staying POT)
  71422. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  71423. };
  71424. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71425. var _this = this;
  71426. if (!this._texture) {
  71427. return;
  71428. }
  71429. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  71430. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71431. });
  71432. };
  71433. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  71434. var scene = this.getScene();
  71435. if (!scene) {
  71436. return;
  71437. }
  71438. var engine = scene.getEngine();
  71439. if (!this._texture) {
  71440. return;
  71441. }
  71442. // Bind
  71443. if (this._postProcessManager) {
  71444. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  71445. }
  71446. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  71447. if (this._texture) {
  71448. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  71449. }
  71450. }
  71451. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  71452. // Clear
  71453. if (this.onClearObservable.hasObservers()) {
  71454. this.onClearObservable.notifyObservers(engine);
  71455. }
  71456. else {
  71457. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  71458. }
  71459. if (!this._doNotChangeAspectRatio) {
  71460. scene.updateTransformMatrix(true);
  71461. }
  71462. // Render
  71463. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  71464. if (this._postProcessManager) {
  71465. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  71466. }
  71467. else if (useCameraPostProcess) {
  71468. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  71469. }
  71470. if (!this._doNotChangeAspectRatio) {
  71471. scene.updateTransformMatrix(true);
  71472. }
  71473. // Dump ?
  71474. if (dumpForDebug) {
  71475. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  71476. }
  71477. // Unbind
  71478. if (!this.isCube || faceIndex === 5) {
  71479. if (this.isCube) {
  71480. if (faceIndex === 5) {
  71481. engine.generateMipMapsForCubemap(this._texture);
  71482. }
  71483. }
  71484. this.unbindFrameBuffer(engine, faceIndex);
  71485. }
  71486. else {
  71487. this.onAfterRenderObservable.notifyObservers(faceIndex);
  71488. }
  71489. };
  71490. /**
  71491. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  71492. * This allowed control for front to back rendering or reversly depending of the special needs.
  71493. *
  71494. * @param renderingGroupId The rendering group id corresponding to its index
  71495. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  71496. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  71497. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  71498. */
  71499. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  71500. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  71501. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  71502. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  71503. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  71504. };
  71505. /**
  71506. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71507. *
  71508. * @param renderingGroupId The rendering group id corresponding to its index
  71509. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71510. */
  71511. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71512. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71513. this._renderingManager._useSceneAutoClearSetup = false;
  71514. };
  71515. RenderTargetTexture.prototype.clone = function () {
  71516. var textureSize = this.getSize();
  71517. 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);
  71518. // Base texture
  71519. newTexture.hasAlpha = this.hasAlpha;
  71520. newTexture.level = this.level;
  71521. // RenderTarget Texture
  71522. newTexture.coordinatesMode = this.coordinatesMode;
  71523. if (this.renderList) {
  71524. newTexture.renderList = this.renderList.slice(0);
  71525. }
  71526. return newTexture;
  71527. };
  71528. RenderTargetTexture.prototype.serialize = function () {
  71529. if (!this.name) {
  71530. return null;
  71531. }
  71532. var serializationObject = _super.prototype.serialize.call(this);
  71533. serializationObject.renderTargetSize = this.getRenderSize();
  71534. serializationObject.renderList = [];
  71535. if (this.renderList) {
  71536. for (var index = 0; index < this.renderList.length; index++) {
  71537. serializationObject.renderList.push(this.renderList[index].id);
  71538. }
  71539. }
  71540. return serializationObject;
  71541. };
  71542. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  71543. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  71544. var objBuffer = this.getInternalTexture();
  71545. var scene = this.getScene();
  71546. if (objBuffer && scene) {
  71547. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  71548. }
  71549. };
  71550. RenderTargetTexture.prototype.dispose = function () {
  71551. if (this._postProcessManager) {
  71552. this._postProcessManager.dispose();
  71553. this._postProcessManager = null;
  71554. }
  71555. this.clearPostProcesses(true);
  71556. if (this._resizeObserver) {
  71557. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  71558. this._resizeObserver = null;
  71559. }
  71560. this.renderList = null;
  71561. // Remove from custom render targets
  71562. var scene = this.getScene();
  71563. if (!scene) {
  71564. return;
  71565. }
  71566. var index = scene.customRenderTargets.indexOf(this);
  71567. if (index >= 0) {
  71568. scene.customRenderTargets.splice(index, 1);
  71569. }
  71570. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  71571. var camera = _a[_i];
  71572. index = camera.customRenderTargets.indexOf(this);
  71573. if (index >= 0) {
  71574. camera.customRenderTargets.splice(index, 1);
  71575. }
  71576. }
  71577. _super.prototype.dispose.call(this);
  71578. };
  71579. /** @hidden */
  71580. RenderTargetTexture.prototype._rebuild = function () {
  71581. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71582. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71583. }
  71584. if (this._postProcessManager) {
  71585. this._postProcessManager._rebuild();
  71586. }
  71587. };
  71588. /**
  71589. * Clear the info related to rendering groups preventing retention point in material dispose.
  71590. */
  71591. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  71592. if (this._renderingManager) {
  71593. this._renderingManager.freeRenderingGroups();
  71594. }
  71595. };
  71596. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  71597. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  71598. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  71599. return RenderTargetTexture;
  71600. }(BABYLON.Texture));
  71601. BABYLON.RenderTargetTexture = RenderTargetTexture;
  71602. })(BABYLON || (BABYLON = {}));
  71603. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  71604. var BABYLON;
  71605. (function (BABYLON) {
  71606. ;
  71607. /**
  71608. * A multi render target, like a render target provides the ability to render to a texture.
  71609. * Unlike the render target, it can render to several draw buffers in one draw.
  71610. * This is specially interesting in deferred rendering or for any effects requiring more than
  71611. * just one color from a single pass.
  71612. */
  71613. var MultiRenderTarget = /** @class */ (function (_super) {
  71614. __extends(MultiRenderTarget, _super);
  71615. /**
  71616. * Instantiate a new multi render target texture.
  71617. * A multi render target, like a render target provides the ability to render to a texture.
  71618. * Unlike the render target, it can render to several draw buffers in one draw.
  71619. * This is specially interesting in deferred rendering or for any effects requiring more than
  71620. * just one color from a single pass.
  71621. * @param name Define the name of the texture
  71622. * @param size Define the size of the buffers to render to
  71623. * @param count Define the number of target we are rendering into
  71624. * @param scene Define the scene the texture belongs to
  71625. * @param options Define the options used to create the multi render target
  71626. */
  71627. function MultiRenderTarget(name, size, count, scene, options) {
  71628. var _this = this;
  71629. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  71630. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  71631. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  71632. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  71633. _this._engine = scene.getEngine();
  71634. if (!_this.isSupported) {
  71635. _this.dispose();
  71636. return;
  71637. }
  71638. var types = [];
  71639. var samplingModes = [];
  71640. for (var i = 0; i < count; i++) {
  71641. if (options && options.types && options.types[i] !== undefined) {
  71642. types.push(options.types[i]);
  71643. }
  71644. else {
  71645. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71646. }
  71647. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  71648. samplingModes.push(options.samplingModes[i]);
  71649. }
  71650. else {
  71651. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71652. }
  71653. }
  71654. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  71655. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  71656. _this._size = size;
  71657. _this._multiRenderTargetOptions = {
  71658. samplingModes: samplingModes,
  71659. generateMipMaps: generateMipMaps,
  71660. generateDepthBuffer: generateDepthBuffer,
  71661. generateStencilBuffer: generateStencilBuffer,
  71662. generateDepthTexture: generateDepthTexture,
  71663. types: types,
  71664. textureCount: count
  71665. };
  71666. _this._createInternalTextures();
  71667. _this._createTextures();
  71668. return _this;
  71669. }
  71670. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  71671. /**
  71672. * Get if draw buffers are currently supported by the used hardware and browser.
  71673. */
  71674. get: function () {
  71675. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  71676. },
  71677. enumerable: true,
  71678. configurable: true
  71679. });
  71680. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  71681. /**
  71682. * Get the list of textures generated by the multi render target.
  71683. */
  71684. get: function () {
  71685. return this._textures;
  71686. },
  71687. enumerable: true,
  71688. configurable: true
  71689. });
  71690. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  71691. /**
  71692. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  71693. */
  71694. get: function () {
  71695. return this._textures[this._textures.length - 1];
  71696. },
  71697. enumerable: true,
  71698. configurable: true
  71699. });
  71700. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  71701. /**
  71702. * Set the wrapping mode on U of all the textures we are rendering to.
  71703. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  71704. */
  71705. set: function (wrap) {
  71706. if (this._textures) {
  71707. for (var i = 0; i < this._textures.length; i++) {
  71708. this._textures[i].wrapU = wrap;
  71709. }
  71710. }
  71711. },
  71712. enumerable: true,
  71713. configurable: true
  71714. });
  71715. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  71716. /**
  71717. * Set the wrapping mode on V of all the textures we are rendering to.
  71718. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  71719. */
  71720. set: function (wrap) {
  71721. if (this._textures) {
  71722. for (var i = 0; i < this._textures.length; i++) {
  71723. this._textures[i].wrapV = wrap;
  71724. }
  71725. }
  71726. },
  71727. enumerable: true,
  71728. configurable: true
  71729. });
  71730. /** @hidden */
  71731. MultiRenderTarget.prototype._rebuild = function () {
  71732. this.releaseInternalTextures();
  71733. this._createInternalTextures();
  71734. for (var i = 0; i < this._internalTextures.length; i++) {
  71735. var texture = this._textures[i];
  71736. texture._texture = this._internalTextures[i];
  71737. }
  71738. // Keeps references to frame buffer and stencil/depth buffer
  71739. this._texture = this._internalTextures[0];
  71740. };
  71741. MultiRenderTarget.prototype._createInternalTextures = function () {
  71742. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  71743. };
  71744. MultiRenderTarget.prototype._createTextures = function () {
  71745. this._textures = [];
  71746. for (var i = 0; i < this._internalTextures.length; i++) {
  71747. var texture = new BABYLON.Texture(null, this.getScene());
  71748. texture._texture = this._internalTextures[i];
  71749. this._textures.push(texture);
  71750. }
  71751. // Keeps references to frame buffer and stencil/depth buffer
  71752. this._texture = this._internalTextures[0];
  71753. };
  71754. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  71755. /**
  71756. * Define the number of samples used if MSAA is enabled.
  71757. */
  71758. get: function () {
  71759. return this._samples;
  71760. },
  71761. set: function (value) {
  71762. if (this._samples === value) {
  71763. return;
  71764. }
  71765. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  71766. },
  71767. enumerable: true,
  71768. configurable: true
  71769. });
  71770. /**
  71771. * Resize all the textures in the multi render target.
  71772. * Be carrefull as it will recreate all the data in the new texture.
  71773. * @param size Define the new size
  71774. */
  71775. MultiRenderTarget.prototype.resize = function (size) {
  71776. this.releaseInternalTextures();
  71777. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  71778. this._createInternalTextures();
  71779. };
  71780. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71781. var _this = this;
  71782. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  71783. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71784. });
  71785. };
  71786. /**
  71787. * Dispose the render targets and their associated resources
  71788. */
  71789. MultiRenderTarget.prototype.dispose = function () {
  71790. this.releaseInternalTextures();
  71791. _super.prototype.dispose.call(this);
  71792. };
  71793. /**
  71794. * Release all the underlying texture used as draw buffers.
  71795. */
  71796. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  71797. if (!this._internalTextures) {
  71798. return;
  71799. }
  71800. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  71801. if (this._internalTextures[i] !== undefined) {
  71802. this._internalTextures[i].dispose();
  71803. this._internalTextures.splice(i, 1);
  71804. }
  71805. }
  71806. };
  71807. return MultiRenderTarget;
  71808. }(BABYLON.RenderTargetTexture));
  71809. BABYLON.MultiRenderTarget = MultiRenderTarget;
  71810. })(BABYLON || (BABYLON = {}));
  71811. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  71812. var BABYLON;
  71813. (function (BABYLON) {
  71814. /**
  71815. * Mirror texture can be used to simulate the view from a mirror in a scene.
  71816. * It will dynamically be rendered every frame to adapt to the camera point of view.
  71817. * You can then easily use it as a reflectionTexture on a flat surface.
  71818. * In case the surface is not a plane, please consider relying on reflection probes.
  71819. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71820. */
  71821. var MirrorTexture = /** @class */ (function (_super) {
  71822. __extends(MirrorTexture, _super);
  71823. /**
  71824. * Instantiates a Mirror Texture.
  71825. * Mirror texture can be used to simulate the view from a mirror in a scene.
  71826. * It will dynamically be rendered every frame to adapt to the camera point of view.
  71827. * You can then easily use it as a reflectionTexture on a flat surface.
  71828. * In case the surface is not a plane, please consider relying on reflection probes.
  71829. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71830. * @param name
  71831. * @param size
  71832. * @param scene
  71833. * @param generateMipMaps
  71834. * @param type
  71835. * @param samplingMode
  71836. * @param generateDepthBuffer
  71837. */
  71838. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  71839. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71841. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71842. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  71843. _this.scene = scene;
  71844. /**
  71845. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  71846. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  71847. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71848. */
  71849. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  71850. _this._transformMatrix = BABYLON.Matrix.Zero();
  71851. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  71852. _this._adaptiveBlurKernel = 0;
  71853. _this._blurKernelX = 0;
  71854. _this._blurKernelY = 0;
  71855. _this._blurRatio = 1.0;
  71856. _this.ignoreCameraViewport = true;
  71857. _this._updateGammaSpace();
  71858. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  71859. _this._updateGammaSpace;
  71860. });
  71861. _this.onBeforeRenderObservable.add(function () {
  71862. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  71863. _this._savedViewMatrix = scene.getViewMatrix();
  71864. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  71865. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  71866. scene.clipPlane = _this.mirrorPlane;
  71867. scene.getEngine().cullBackFaces = false;
  71868. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  71869. });
  71870. _this.onAfterRenderObservable.add(function () {
  71871. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  71872. scene.getEngine().cullBackFaces = true;
  71873. scene._mirroredCameraPosition = null;
  71874. delete scene.clipPlane;
  71875. });
  71876. return _this;
  71877. }
  71878. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  71879. get: function () {
  71880. return this._blurRatio;
  71881. },
  71882. /**
  71883. * Define the blur ratio used to blur the reflection if needed.
  71884. */
  71885. set: function (value) {
  71886. if (this._blurRatio === value) {
  71887. return;
  71888. }
  71889. this._blurRatio = value;
  71890. this._preparePostProcesses();
  71891. },
  71892. enumerable: true,
  71893. configurable: true
  71894. });
  71895. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  71896. /**
  71897. * Define the adaptive blur kernel used to blur the reflection if needed.
  71898. * This will autocompute the closest best match for the `blurKernel`
  71899. */
  71900. set: function (value) {
  71901. this._adaptiveBlurKernel = value;
  71902. this._autoComputeBlurKernel();
  71903. },
  71904. enumerable: true,
  71905. configurable: true
  71906. });
  71907. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  71908. /**
  71909. * Define the blur kernel used to blur the reflection if needed.
  71910. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71911. */
  71912. set: function (value) {
  71913. this.blurKernelX = value;
  71914. this.blurKernelY = value;
  71915. },
  71916. enumerable: true,
  71917. configurable: true
  71918. });
  71919. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  71920. get: function () {
  71921. return this._blurKernelX;
  71922. },
  71923. /**
  71924. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  71925. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71926. */
  71927. set: function (value) {
  71928. if (this._blurKernelX === value) {
  71929. return;
  71930. }
  71931. this._blurKernelX = value;
  71932. this._preparePostProcesses();
  71933. },
  71934. enumerable: true,
  71935. configurable: true
  71936. });
  71937. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  71938. get: function () {
  71939. return this._blurKernelY;
  71940. },
  71941. /**
  71942. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  71943. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71944. */
  71945. set: function (value) {
  71946. if (this._blurKernelY === value) {
  71947. return;
  71948. }
  71949. this._blurKernelY = value;
  71950. this._preparePostProcesses();
  71951. },
  71952. enumerable: true,
  71953. configurable: true
  71954. });
  71955. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  71956. var engine = this.getScene().getEngine();
  71957. var dw = this.getRenderWidth() / engine.getRenderWidth();
  71958. var dh = this.getRenderHeight() / engine.getRenderHeight();
  71959. this.blurKernelX = this._adaptiveBlurKernel * dw;
  71960. this.blurKernelY = this._adaptiveBlurKernel * dh;
  71961. };
  71962. MirrorTexture.prototype._onRatioRescale = function () {
  71963. if (this._sizeRatio) {
  71964. this.resize(this._initialSizeParameter);
  71965. if (!this._adaptiveBlurKernel) {
  71966. this._preparePostProcesses();
  71967. }
  71968. }
  71969. if (this._adaptiveBlurKernel) {
  71970. this._autoComputeBlurKernel();
  71971. }
  71972. };
  71973. MirrorTexture.prototype._updateGammaSpace = function () {
  71974. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  71975. };
  71976. MirrorTexture.prototype._preparePostProcesses = function () {
  71977. this.clearPostProcesses(true);
  71978. if (this._blurKernelX && this._blurKernelY) {
  71979. var engine = this.getScene().getEngine();
  71980. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71981. 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);
  71982. this._blurX.autoClear = false;
  71983. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  71984. this._blurX.inputTexture = this._texture;
  71985. }
  71986. else {
  71987. this._blurX.alwaysForcePOT = true;
  71988. }
  71989. 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);
  71990. this._blurY.autoClear = false;
  71991. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  71992. this.addPostProcess(this._blurX);
  71993. this.addPostProcess(this._blurY);
  71994. }
  71995. else {
  71996. if (this._blurY) {
  71997. this.removePostProcess(this._blurY);
  71998. this._blurY.dispose();
  71999. this._blurY = null;
  72000. }
  72001. if (this._blurX) {
  72002. this.removePostProcess(this._blurX);
  72003. this._blurX.dispose();
  72004. this._blurX = null;
  72005. }
  72006. }
  72007. };
  72008. /**
  72009. * Clone the mirror texture.
  72010. * @returns the cloned texture
  72011. */
  72012. MirrorTexture.prototype.clone = function () {
  72013. var scene = this.getScene();
  72014. if (!scene) {
  72015. return this;
  72016. }
  72017. var textureSize = this.getSize();
  72018. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  72019. // Base texture
  72020. newTexture.hasAlpha = this.hasAlpha;
  72021. newTexture.level = this.level;
  72022. // Mirror Texture
  72023. newTexture.mirrorPlane = this.mirrorPlane.clone();
  72024. if (this.renderList) {
  72025. newTexture.renderList = this.renderList.slice(0);
  72026. }
  72027. return newTexture;
  72028. };
  72029. /**
  72030. * Serialize the texture to a JSON representation you could use in Parse later on
  72031. * @returns the serialized JSON representation
  72032. */
  72033. MirrorTexture.prototype.serialize = function () {
  72034. if (!this.name) {
  72035. return null;
  72036. }
  72037. var serializationObject = _super.prototype.serialize.call(this);
  72038. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  72039. return serializationObject;
  72040. };
  72041. /**
  72042. * Dispose the texture and release its associated resources.
  72043. */
  72044. MirrorTexture.prototype.dispose = function () {
  72045. _super.prototype.dispose.call(this);
  72046. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  72047. };
  72048. return MirrorTexture;
  72049. }(BABYLON.RenderTargetTexture));
  72050. BABYLON.MirrorTexture = MirrorTexture;
  72051. })(BABYLON || (BABYLON = {}));
  72052. //# sourceMappingURL=babylon.mirrorTexture.js.map
  72053. var BABYLON;
  72054. (function (BABYLON) {
  72055. /**
  72056. * Creates a refraction texture used by refraction channel of the standard material.
  72057. * It is like a mirror but to see through a material.
  72058. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72059. */
  72060. var RefractionTexture = /** @class */ (function (_super) {
  72061. __extends(RefractionTexture, _super);
  72062. /**
  72063. * Creates a refraction texture used by refraction channel of the standard material.
  72064. * It is like a mirror but to see through a material.
  72065. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72066. * @param name Define the texture name
  72067. * @param size Define the size of the underlying texture
  72068. * @param scene Define the scene the refraction belongs to
  72069. * @param generateMipMaps Define if we need to generate mips level for the refraction
  72070. */
  72071. function RefractionTexture(name, size, scene, generateMipMaps) {
  72072. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  72073. /**
  72074. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  72075. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  72076. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72077. */
  72078. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  72079. /**
  72080. * Define how deep under the surface we should see.
  72081. */
  72082. _this.depth = 2.0;
  72083. _this.onBeforeRenderObservable.add(function () {
  72084. scene.clipPlane = _this.refractionPlane;
  72085. });
  72086. _this.onAfterRenderObservable.add(function () {
  72087. delete scene.clipPlane;
  72088. });
  72089. return _this;
  72090. }
  72091. /**
  72092. * Clone the refraction texture.
  72093. * @returns the cloned texture
  72094. */
  72095. RefractionTexture.prototype.clone = function () {
  72096. var scene = this.getScene();
  72097. if (!scene) {
  72098. return this;
  72099. }
  72100. var textureSize = this.getSize();
  72101. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  72102. // Base texture
  72103. newTexture.hasAlpha = this.hasAlpha;
  72104. newTexture.level = this.level;
  72105. // Refraction Texture
  72106. newTexture.refractionPlane = this.refractionPlane.clone();
  72107. if (this.renderList) {
  72108. newTexture.renderList = this.renderList.slice(0);
  72109. }
  72110. newTexture.depth = this.depth;
  72111. return newTexture;
  72112. };
  72113. /**
  72114. * Serialize the texture to a JSON representation you could use in Parse later on
  72115. * @returns the serialized JSON representation
  72116. */
  72117. RefractionTexture.prototype.serialize = function () {
  72118. if (!this.name) {
  72119. return null;
  72120. }
  72121. var serializationObject = _super.prototype.serialize.call(this);
  72122. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  72123. serializationObject.depth = this.depth;
  72124. return serializationObject;
  72125. };
  72126. return RefractionTexture;
  72127. }(BABYLON.RenderTargetTexture));
  72128. BABYLON.RefractionTexture = RefractionTexture;
  72129. })(BABYLON || (BABYLON = {}));
  72130. //# sourceMappingURL=babylon.refractionTexture.js.map
  72131. var BABYLON;
  72132. (function (BABYLON) {
  72133. /**
  72134. * A class extending {BABYLON.Texture} allowing drawing on a texture
  72135. * @see http://doc.babylonjs.com/how_to/dynamictexture
  72136. */
  72137. var DynamicTexture = /** @class */ (function (_super) {
  72138. __extends(DynamicTexture, _super);
  72139. /**
  72140. * Creates a {BABYLON.DynamicTexture}
  72141. * @param name defines the name of the texture
  72142. * @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
  72143. * @param scene defines the scene where you want the texture
  72144. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  72145. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  72146. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  72147. */
  72148. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  72149. if (scene === void 0) { scene = null; }
  72150. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72151. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72152. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  72153. _this.name = name;
  72154. _this._engine = _this.getScene().getEngine();
  72155. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72156. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72157. _this._generateMipMaps = generateMipMaps;
  72158. if (options.getContext) {
  72159. _this._canvas = options;
  72160. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72161. }
  72162. else {
  72163. _this._canvas = document.createElement("canvas");
  72164. if (options.width || options.width === 0) {
  72165. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72166. }
  72167. else {
  72168. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  72169. }
  72170. }
  72171. var textureSize = _this.getSize();
  72172. _this._canvas.width = textureSize.width;
  72173. _this._canvas.height = textureSize.height;
  72174. _this._context = _this._canvas.getContext("2d");
  72175. return _this;
  72176. }
  72177. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  72178. /**
  72179. * Gets the current state of canRescale
  72180. */
  72181. get: function () {
  72182. return true;
  72183. },
  72184. enumerable: true,
  72185. configurable: true
  72186. });
  72187. DynamicTexture.prototype._recreate = function (textureSize) {
  72188. this._canvas.width = textureSize.width;
  72189. this._canvas.height = textureSize.height;
  72190. this.releaseInternalTexture();
  72191. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  72192. };
  72193. /**
  72194. * Scales the texture
  72195. * @param ratio the scale factor to apply to both width and height
  72196. */
  72197. DynamicTexture.prototype.scale = function (ratio) {
  72198. var textureSize = this.getSize();
  72199. textureSize.width *= ratio;
  72200. textureSize.height *= ratio;
  72201. this._recreate(textureSize);
  72202. };
  72203. /**
  72204. * Resizes the texture
  72205. * @param width the new width
  72206. * @param height the new height
  72207. */
  72208. DynamicTexture.prototype.scaleTo = function (width, height) {
  72209. var textureSize = this.getSize();
  72210. textureSize.width = width;
  72211. textureSize.height = height;
  72212. this._recreate(textureSize);
  72213. };
  72214. /**
  72215. * Gets the context of the canvas used by the texture
  72216. * @returns the canvas context of the dynamic texture
  72217. */
  72218. DynamicTexture.prototype.getContext = function () {
  72219. return this._context;
  72220. };
  72221. /**
  72222. * Clears the texture
  72223. */
  72224. DynamicTexture.prototype.clear = function () {
  72225. var size = this.getSize();
  72226. this._context.fillRect(0, 0, size.width, size.height);
  72227. };
  72228. /**
  72229. * Updates the texture
  72230. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  72231. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  72232. */
  72233. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  72234. if (premulAlpha === void 0) { premulAlpha = false; }
  72235. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  72236. };
  72237. /**
  72238. * Draws text onto the texture
  72239. * @param text defines the text to be drawn
  72240. * @param x defines the placement of the text from the left
  72241. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  72242. * @param font defines the font to be used with font-style, font-size, font-name
  72243. * @param color defines the color used for the text
  72244. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  72245. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  72246. * @param update defines whether texture is immediately update (default is true)
  72247. */
  72248. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  72249. if (update === void 0) { update = true; }
  72250. var size = this.getSize();
  72251. if (clearColor) {
  72252. this._context.fillStyle = clearColor;
  72253. this._context.fillRect(0, 0, size.width, size.height);
  72254. }
  72255. this._context.font = font;
  72256. if (x === null || x === undefined) {
  72257. var textSize = this._context.measureText(text);
  72258. x = (size.width - textSize.width) / 2;
  72259. }
  72260. if (y === null || y === undefined) {
  72261. var fontSize = parseInt((font.replace(/\D/g, '')));
  72262. y = (size.height / 2) + (fontSize / 3.65);
  72263. }
  72264. this._context.fillStyle = color;
  72265. this._context.fillText(text, x, y);
  72266. if (update) {
  72267. this.update(invertY);
  72268. }
  72269. };
  72270. /**
  72271. * Clones the texture
  72272. * @returns the clone of the texture.
  72273. */
  72274. DynamicTexture.prototype.clone = function () {
  72275. var scene = this.getScene();
  72276. if (!scene) {
  72277. return this;
  72278. }
  72279. var textureSize = this.getSize();
  72280. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  72281. // Base texture
  72282. newTexture.hasAlpha = this.hasAlpha;
  72283. newTexture.level = this.level;
  72284. // Dynamic Texture
  72285. newTexture.wrapU = this.wrapU;
  72286. newTexture.wrapV = this.wrapV;
  72287. return newTexture;
  72288. };
  72289. /**
  72290. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  72291. * @returns a serialized dynamic texture object
  72292. */
  72293. DynamicTexture.prototype.serialize = function () {
  72294. var scene = this.getScene();
  72295. if (scene && !scene.isReady()) {
  72296. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  72297. }
  72298. var serializationObject = _super.prototype.serialize.call(this);
  72299. serializationObject.base64String = this._canvas.toDataURL();
  72300. serializationObject.invertY = this._invertY;
  72301. serializationObject.samplingMode = this.samplingMode;
  72302. return serializationObject;
  72303. };
  72304. /** @hidden */
  72305. DynamicTexture.prototype._rebuild = function () {
  72306. this.update();
  72307. };
  72308. return DynamicTexture;
  72309. }(BABYLON.Texture));
  72310. BABYLON.DynamicTexture = DynamicTexture;
  72311. })(BABYLON || (BABYLON = {}));
  72312. //# sourceMappingURL=babylon.dynamicTexture.js.map
  72313. var BABYLON;
  72314. (function (BABYLON) {
  72315. /**
  72316. * If you want to display a video in your scene, this is the special texture for that.
  72317. * This special texture works similar to other textures, with the exception of a few parameters.
  72318. * @see https://doc.babylonjs.com/how_to/video_texture
  72319. */
  72320. var VideoTexture = /** @class */ (function (_super) {
  72321. __extends(VideoTexture, _super);
  72322. /**
  72323. * Creates a video texture.
  72324. * If you want to display a video in your scene, this is the special texture for that.
  72325. * This special texture works similar to other textures, with the exception of a few parameters.
  72326. * @see https://doc.babylonjs.com/how_to/video_texture
  72327. * @param {string | null} name optional name, will detect from video source, if not defined
  72328. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  72329. * @param {BABYLON.Scene} scene is obviously the current scene.
  72330. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  72331. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  72332. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  72333. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  72334. */
  72335. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  72336. if (generateMipMaps === void 0) { generateMipMaps = false; }
  72337. if (invertY === void 0) { invertY = false; }
  72338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72339. if (settings === void 0) { settings = {
  72340. autoPlay: true,
  72341. loop: true,
  72342. autoUpdateTexture: true,
  72343. }; }
  72344. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72345. _this._onUserActionRequestedObservable = null;
  72346. _this._stillImageCaptured = false;
  72347. _this._poster = false;
  72348. _this._createInternalTexture = function () {
  72349. if (_this._texture != null) {
  72350. if (_this._poster) {
  72351. _this._texture.dispose();
  72352. _this._poster = false;
  72353. }
  72354. else {
  72355. return;
  72356. }
  72357. }
  72358. if (!_this._engine.needPOTTextures ||
  72359. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  72360. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72361. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72362. }
  72363. else {
  72364. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72365. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72366. _this._generateMipMaps = false;
  72367. }
  72368. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  72369. if (!_this.video.autoplay) {
  72370. var oldHandler_1 = _this.video.onplaying;
  72371. var error_1 = false;
  72372. _this.video.onplaying = function () {
  72373. _this.video.onplaying = oldHandler_1;
  72374. _this._texture.isReady = true;
  72375. _this._updateInternalTexture();
  72376. if (!error_1) {
  72377. _this.video.pause();
  72378. }
  72379. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72380. _this.onLoadObservable.notifyObservers(_this);
  72381. }
  72382. };
  72383. var playing = _this.video.play();
  72384. if (playing) {
  72385. playing.then(function () {
  72386. // Everything is good.
  72387. })
  72388. .catch(function () {
  72389. error_1 = true;
  72390. // On Chrome for instance, new policies might prevent playing without user interaction.
  72391. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  72392. _this._onUserActionRequestedObservable.notifyObservers(_this);
  72393. }
  72394. });
  72395. }
  72396. else {
  72397. _this.video.onplaying = oldHandler_1;
  72398. _this._texture.isReady = true;
  72399. _this._updateInternalTexture();
  72400. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72401. _this.onLoadObservable.notifyObservers(_this);
  72402. }
  72403. }
  72404. }
  72405. else {
  72406. _this._texture.isReady = true;
  72407. _this._updateInternalTexture();
  72408. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72409. _this.onLoadObservable.notifyObservers(_this);
  72410. }
  72411. }
  72412. };
  72413. _this.reset = function () {
  72414. if (_this._texture == null) {
  72415. return;
  72416. }
  72417. if (!_this._poster) {
  72418. _this._texture.dispose();
  72419. _this._texture = null;
  72420. }
  72421. };
  72422. _this._updateInternalTexture = function (e) {
  72423. if (_this._texture == null || !_this._texture.isReady) {
  72424. return;
  72425. }
  72426. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  72427. return;
  72428. }
  72429. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  72430. };
  72431. _this._engine = _this.getScene().getEngine();
  72432. _this._generateMipMaps = generateMipMaps;
  72433. _this._samplingMode = samplingMode;
  72434. _this.autoUpdateTexture = settings.autoUpdateTexture;
  72435. _this.name = name || _this._getName(src);
  72436. _this.video = _this._getVideo(src);
  72437. if (settings.poster) {
  72438. _this.video.poster = settings.poster;
  72439. }
  72440. if (settings.autoPlay !== undefined) {
  72441. _this.video.autoplay = settings.autoPlay;
  72442. }
  72443. if (settings.loop !== undefined) {
  72444. _this.video.loop = settings.loop;
  72445. }
  72446. _this.video.setAttribute("playsinline", "");
  72447. _this.video.addEventListener("canplay", _this._createInternalTexture);
  72448. _this.video.addEventListener("paused", _this._updateInternalTexture);
  72449. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  72450. _this.video.addEventListener("emptied", _this.reset);
  72451. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  72452. _this._createInternalTexture();
  72453. }
  72454. if (settings.poster) {
  72455. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  72456. _this._poster = true;
  72457. }
  72458. return _this;
  72459. }
  72460. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  72461. /**
  72462. * Event triggerd when a dom action is required by the user to play the video.
  72463. * This happens due to recent changes in browser policies preventing video to auto start.
  72464. */
  72465. get: function () {
  72466. if (!this._onUserActionRequestedObservable) {
  72467. this._onUserActionRequestedObservable = new BABYLON.Observable();
  72468. }
  72469. return this._onUserActionRequestedObservable;
  72470. },
  72471. enumerable: true,
  72472. configurable: true
  72473. });
  72474. VideoTexture.prototype._getName = function (src) {
  72475. if (src instanceof HTMLVideoElement) {
  72476. return src.currentSrc;
  72477. }
  72478. if (typeof src === "object") {
  72479. return src.toString();
  72480. }
  72481. return src;
  72482. };
  72483. ;
  72484. VideoTexture.prototype._getVideo = function (src) {
  72485. if (src instanceof HTMLVideoElement) {
  72486. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  72487. return src;
  72488. }
  72489. var video = document.createElement("video");
  72490. if (typeof src === "string") {
  72491. BABYLON.Tools.SetCorsBehavior(src, video);
  72492. video.src = src;
  72493. }
  72494. else {
  72495. BABYLON.Tools.SetCorsBehavior(src[0], video);
  72496. src.forEach(function (url) {
  72497. var source = document.createElement("source");
  72498. source.src = url;
  72499. video.appendChild(source);
  72500. });
  72501. }
  72502. return video;
  72503. };
  72504. ;
  72505. /**
  72506. * @hidden Internal method to initiate `update`.
  72507. */
  72508. VideoTexture.prototype._rebuild = function () {
  72509. this.update();
  72510. };
  72511. /**
  72512. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  72513. */
  72514. VideoTexture.prototype.update = function () {
  72515. if (!this.autoUpdateTexture) {
  72516. // Expecting user to call `updateTexture` manually
  72517. return;
  72518. }
  72519. this.updateTexture(true);
  72520. };
  72521. /**
  72522. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  72523. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  72524. */
  72525. VideoTexture.prototype.updateTexture = function (isVisible) {
  72526. if (!isVisible) {
  72527. return;
  72528. }
  72529. if (this.video.paused && this._stillImageCaptured) {
  72530. return;
  72531. }
  72532. this._stillImageCaptured = true;
  72533. this._updateInternalTexture();
  72534. };
  72535. /**
  72536. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  72537. * @param url New url.
  72538. */
  72539. VideoTexture.prototype.updateURL = function (url) {
  72540. this.video.src = url;
  72541. };
  72542. /**
  72543. * Dispose the texture and release its associated resources.
  72544. */
  72545. VideoTexture.prototype.dispose = function () {
  72546. _super.prototype.dispose.call(this);
  72547. if (this._onUserActionRequestedObservable) {
  72548. this._onUserActionRequestedObservable.clear();
  72549. this._onUserActionRequestedObservable = null;
  72550. }
  72551. this.video.removeEventListener("canplay", this._createInternalTexture);
  72552. this.video.removeEventListener("paused", this._updateInternalTexture);
  72553. this.video.removeEventListener("seeked", this._updateInternalTexture);
  72554. this.video.removeEventListener("emptied", this.reset);
  72555. this.video.pause();
  72556. };
  72557. /**
  72558. * Creates a video texture straight from your WebCam video feed.
  72559. * @param scene Define the scene the texture should be created in
  72560. * @param onReady Define a callback to triggered once the texture will be ready
  72561. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  72562. */
  72563. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  72564. var video = document.createElement("video");
  72565. video.setAttribute('autoplay', '');
  72566. video.setAttribute('muted', '');
  72567. video.setAttribute('playsinline', '');
  72568. var constraintsDeviceId;
  72569. if (constraints && constraints.deviceId) {
  72570. constraintsDeviceId = {
  72571. exact: constraints.deviceId,
  72572. };
  72573. }
  72574. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  72575. if (navigator.mediaDevices) {
  72576. navigator.mediaDevices.getUserMedia({ video: constraints })
  72577. .then(function (stream) {
  72578. if (video.mozSrcObject !== undefined) {
  72579. // hack for Firefox < 19
  72580. video.mozSrcObject = stream;
  72581. }
  72582. else {
  72583. video.srcObject = stream;
  72584. }
  72585. var onPlaying = function () {
  72586. if (onReady) {
  72587. onReady(new VideoTexture("video", video, scene, true, true));
  72588. }
  72589. video.removeEventListener("playing", onPlaying);
  72590. };
  72591. video.addEventListener("playing", onPlaying);
  72592. video.play();
  72593. })
  72594. .catch(function (err) {
  72595. BABYLON.Tools.Error(err.name);
  72596. });
  72597. }
  72598. else {
  72599. navigator.getUserMedia =
  72600. navigator.getUserMedia ||
  72601. navigator.webkitGetUserMedia ||
  72602. navigator.mozGetUserMedia ||
  72603. navigator.msGetUserMedia;
  72604. if (navigator.getUserMedia) {
  72605. navigator.getUserMedia({
  72606. video: {
  72607. deviceId: constraintsDeviceId,
  72608. width: {
  72609. min: (constraints && constraints.minWidth) || 256,
  72610. max: (constraints && constraints.maxWidth) || 640,
  72611. },
  72612. height: {
  72613. min: (constraints && constraints.minHeight) || 256,
  72614. max: (constraints && constraints.maxHeight) || 480,
  72615. },
  72616. },
  72617. }, function (stream) {
  72618. if (video.mozSrcObject !== undefined) {
  72619. // hack for Firefox < 19
  72620. video.mozSrcObject = stream;
  72621. }
  72622. else {
  72623. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  72624. }
  72625. video.play();
  72626. if (onReady) {
  72627. onReady(new VideoTexture("video", video, scene, true, true));
  72628. }
  72629. }, function (e) {
  72630. BABYLON.Tools.Error(e.name);
  72631. });
  72632. }
  72633. }
  72634. };
  72635. return VideoTexture;
  72636. }(BABYLON.Texture));
  72637. BABYLON.VideoTexture = VideoTexture;
  72638. })(BABYLON || (BABYLON = {}));
  72639. //# sourceMappingURL=babylon.videoTexture.js.map
  72640. var BABYLON;
  72641. (function (BABYLON) {
  72642. /**
  72643. * Raw texture can help creating a texture directly from an array of data.
  72644. * This can be super useful if you either get the data from an uncompressed source or
  72645. * if you wish to create your texture pixel by pixel.
  72646. */
  72647. var RawTexture = /** @class */ (function (_super) {
  72648. __extends(RawTexture, _super);
  72649. /**
  72650. * Instantiates a new RawTexture.
  72651. * Raw texture can help creating a texture directly from an array of data.
  72652. * This can be super useful if you either get the data from an uncompressed source or
  72653. * if you wish to create your texture pixel by pixel.
  72654. * @param data define the array of data to use to create the texture
  72655. * @param width define the width of the texture
  72656. * @param height define the height of the texture
  72657. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  72658. * @param scene define the scene the texture belongs to
  72659. * @param generateMipMaps define whether mip maps should be generated or not
  72660. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72661. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72662. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  72663. */
  72664. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  72665. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72666. if (invertY === void 0) { invertY = false; }
  72667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72668. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72669. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72670. _this.format = format;
  72671. _this._engine = scene.getEngine();
  72672. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  72673. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72674. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72675. return _this;
  72676. }
  72677. /**
  72678. * Updates the texture underlying data.
  72679. * @param data Define the new data of the texture
  72680. */
  72681. RawTexture.prototype.update = function (data) {
  72682. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72683. };
  72684. /**
  72685. * Creates a luminance texture from some data.
  72686. * @param data Define the texture data
  72687. * @param width Define the width of the texture
  72688. * @param height Define the height of the texture
  72689. * @param scene Define the scene the texture belongs to
  72690. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72691. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72692. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72693. * @returns the luminance texture
  72694. */
  72695. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72696. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72697. if (invertY === void 0) { invertY = false; }
  72698. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72699. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  72700. };
  72701. /**
  72702. * Creates a luminance alpha texture from some data.
  72703. * @param data Define the texture data
  72704. * @param width Define the width of the texture
  72705. * @param height Define the height of the texture
  72706. * @param scene Define the scene the texture belongs to
  72707. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72708. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72709. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72710. * @returns the luminance alpha texture
  72711. */
  72712. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72713. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72714. if (invertY === void 0) { invertY = false; }
  72715. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72716. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72717. };
  72718. /**
  72719. * Creates an alpha texture from some data.
  72720. * @param data Define the texture data
  72721. * @param width Define the width of the texture
  72722. * @param height Define the height of the texture
  72723. * @param scene Define the scene the texture belongs to
  72724. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72725. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72726. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72727. * @returns the alpha texture
  72728. */
  72729. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72730. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72731. if (invertY === void 0) { invertY = false; }
  72732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72733. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72734. };
  72735. /**
  72736. * Creates a RGB texture from some data.
  72737. * @param data Define the texture data
  72738. * @param width Define the width of the texture
  72739. * @param height Define the height of the texture
  72740. * @param scene Define the scene the texture belongs to
  72741. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72742. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72743. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72744. * @returns the RGB alpha texture
  72745. */
  72746. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72747. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72748. if (invertY === void 0) { invertY = false; }
  72749. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72750. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72751. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  72752. };
  72753. /**
  72754. * Creates a RGBA texture from some data.
  72755. * @param data Define the texture data
  72756. * @param width Define the width of the texture
  72757. * @param height Define the height of the texture
  72758. * @param scene Define the scene the texture belongs to
  72759. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72760. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72761. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72762. * @returns the RGBA texture
  72763. */
  72764. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72765. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72766. if (invertY === void 0) { invertY = false; }
  72767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72768. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72769. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  72770. };
  72771. /**
  72772. * Creates a R texture from some data.
  72773. * @param data Define the texture data
  72774. * @param width Define the width of the texture
  72775. * @param height Define the height of the texture
  72776. * @param scene Define the scene the texture belongs to
  72777. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72778. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72779. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72780. * @returns the R texture
  72781. */
  72782. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72783. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72784. if (invertY === void 0) { invertY = false; }
  72785. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72786. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72787. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  72788. };
  72789. return RawTexture;
  72790. }(BABYLON.Texture));
  72791. BABYLON.RawTexture = RawTexture;
  72792. })(BABYLON || (BABYLON = {}));
  72793. //# sourceMappingURL=babylon.rawTexture.js.map
  72794. var BABYLON;
  72795. (function (BABYLON) {
  72796. /**
  72797. * Class used to store 3D textures containing user data
  72798. */
  72799. var RawTexture3D = /** @class */ (function (_super) {
  72800. __extends(RawTexture3D, _super);
  72801. /**
  72802. * Create a new RawTexture3D
  72803. * @param data defines the data of the texture
  72804. * @param width defines the width of the texture
  72805. * @param height defines the height of the texture
  72806. * @param depth defines the depth of the texture
  72807. * @param format defines the texture format to use
  72808. * @param scene defines the hosting scene
  72809. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  72810. * @param invertY defines if texture must be stored with Y axis inverted
  72811. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  72812. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  72813. */
  72814. function RawTexture3D(data, width, height, depth,
  72815. /** Gets or sets the texture format to use */
  72816. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  72817. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72818. if (invertY === void 0) { invertY = false; }
  72819. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72820. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72821. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72822. _this.format = format;
  72823. _this._engine = scene.getEngine();
  72824. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  72825. _this.is3D = true;
  72826. return _this;
  72827. }
  72828. /**
  72829. * Update the texture with new data
  72830. * @param data defines the data to store in the texture
  72831. */
  72832. RawTexture3D.prototype.update = function (data) {
  72833. if (!this._texture) {
  72834. return;
  72835. }
  72836. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72837. };
  72838. return RawTexture3D;
  72839. }(BABYLON.Texture));
  72840. BABYLON.RawTexture3D = RawTexture3D;
  72841. })(BABYLON || (BABYLON = {}));
  72842. //# sourceMappingURL=babylon.rawTexture3D.js.map
  72843. var BABYLON;
  72844. (function (BABYLON) {
  72845. /**
  72846. * PostProcessManager is used to manage one or more post processes or post process pipelines
  72847. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  72848. */
  72849. var PostProcessManager = /** @class */ (function () {
  72850. /**
  72851. * Creates a new instance PostProcess
  72852. * @param scene The scene that the post process is associated with.
  72853. */
  72854. function PostProcessManager(scene) {
  72855. this._vertexBuffers = {};
  72856. this._scene = scene;
  72857. }
  72858. PostProcessManager.prototype._prepareBuffers = function () {
  72859. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  72860. return;
  72861. }
  72862. // VBO
  72863. var vertices = [];
  72864. vertices.push(1, 1);
  72865. vertices.push(-1, 1);
  72866. vertices.push(-1, -1);
  72867. vertices.push(1, -1);
  72868. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72869. this._buildIndexBuffer();
  72870. };
  72871. PostProcessManager.prototype._buildIndexBuffer = function () {
  72872. // Indices
  72873. var indices = [];
  72874. indices.push(0);
  72875. indices.push(1);
  72876. indices.push(2);
  72877. indices.push(0);
  72878. indices.push(2);
  72879. indices.push(3);
  72880. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  72881. };
  72882. /**
  72883. * Rebuilds the vertex buffers of the manager.
  72884. * @hidden
  72885. */
  72886. PostProcessManager.prototype._rebuild = function () {
  72887. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72888. if (!vb) {
  72889. return;
  72890. }
  72891. vb._rebuild();
  72892. this._buildIndexBuffer();
  72893. };
  72894. // Methods
  72895. /**
  72896. * Prepares a frame to be run through a post process.
  72897. * @param sourceTexture The input texture to the post procesess. (default: null)
  72898. * @param postProcesses An array of post processes to be run. (default: null)
  72899. * @returns True if the post processes were able to be run.
  72900. * @hidden
  72901. */
  72902. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  72903. if (sourceTexture === void 0) { sourceTexture = null; }
  72904. if (postProcesses === void 0) { postProcesses = null; }
  72905. var camera = this._scene.activeCamera;
  72906. if (!camera) {
  72907. return false;
  72908. }
  72909. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72910. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72911. return false;
  72912. }
  72913. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  72914. return true;
  72915. };
  72916. /**
  72917. * Manually render a set of post processes to a texture.
  72918. * @param postProcesses An array of post processes to be run.
  72919. * @param targetTexture The target texture to render to.
  72920. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  72921. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  72922. * @param lodLevel defines which lod of the texture to render to
  72923. */
  72924. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  72925. if (targetTexture === void 0) { targetTexture = null; }
  72926. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72927. if (faceIndex === void 0) { faceIndex = 0; }
  72928. if (lodLevel === void 0) { lodLevel = 0; }
  72929. var engine = this._scene.getEngine();
  72930. for (var index = 0; index < postProcesses.length; index++) {
  72931. if (index < postProcesses.length - 1) {
  72932. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  72933. }
  72934. else {
  72935. if (targetTexture) {
  72936. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  72937. }
  72938. else {
  72939. engine.restoreDefaultFramebuffer();
  72940. }
  72941. }
  72942. var pp = postProcesses[index];
  72943. var effect = pp.apply();
  72944. if (effect) {
  72945. pp.onBeforeRenderObservable.notifyObservers(effect);
  72946. // VBOs
  72947. this._prepareBuffers();
  72948. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  72949. // Draw order
  72950. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72951. pp.onAfterRenderObservable.notifyObservers(effect);
  72952. }
  72953. }
  72954. // Restore depth buffer
  72955. engine.setDepthBuffer(true);
  72956. engine.setDepthWrite(true);
  72957. };
  72958. /**
  72959. * Finalize the result of the output of the postprocesses.
  72960. * @param doNotPresent If true the result will not be displayed to the screen.
  72961. * @param targetTexture The target texture to render to.
  72962. * @param faceIndex The index of the face to bind the target texture to.
  72963. * @param postProcesses The array of post processes to render.
  72964. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  72965. * @hidden
  72966. */
  72967. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  72968. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72969. var camera = this._scene.activeCamera;
  72970. if (!camera) {
  72971. return;
  72972. }
  72973. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72974. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72975. return;
  72976. }
  72977. var engine = this._scene.getEngine();
  72978. for (var index = 0, len = postProcesses.length; index < len; index++) {
  72979. var pp = postProcesses[index];
  72980. if (index < len - 1) {
  72981. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  72982. }
  72983. else {
  72984. if (targetTexture) {
  72985. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  72986. pp._outputTexture = targetTexture;
  72987. }
  72988. else {
  72989. engine.restoreDefaultFramebuffer();
  72990. pp._outputTexture = null;
  72991. }
  72992. }
  72993. if (doNotPresent) {
  72994. break;
  72995. }
  72996. var effect = pp.apply();
  72997. if (effect) {
  72998. pp.onBeforeRenderObservable.notifyObservers(effect);
  72999. // VBOs
  73000. this._prepareBuffers();
  73001. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73002. // Draw order
  73003. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73004. pp.onAfterRenderObservable.notifyObservers(effect);
  73005. }
  73006. }
  73007. // Restore states
  73008. engine.setDepthBuffer(true);
  73009. engine.setDepthWrite(true);
  73010. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73011. };
  73012. /**
  73013. * Disposes of the post process manager.
  73014. */
  73015. PostProcessManager.prototype.dispose = function () {
  73016. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73017. if (buffer) {
  73018. buffer.dispose();
  73019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73020. }
  73021. if (this._indexBuffer) {
  73022. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73023. this._indexBuffer = null;
  73024. }
  73025. };
  73026. return PostProcessManager;
  73027. }());
  73028. BABYLON.PostProcessManager = PostProcessManager;
  73029. })(BABYLON || (BABYLON = {}));
  73030. //# sourceMappingURL=babylon.postProcessManager.js.map
  73031. var BABYLON;
  73032. (function (BABYLON) {
  73033. /**
  73034. * PostProcess can be used to apply a shader to a texture after it has been rendered
  73035. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73036. */
  73037. var PostProcess = /** @class */ (function () {
  73038. /**
  73039. * Creates a new instance PostProcess
  73040. * @param name The name of the PostProcess.
  73041. * @param fragmentUrl The url of the fragment shader to be used.
  73042. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  73043. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  73044. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73045. * @param camera The camera to apply the render pass to.
  73046. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73047. * @param engine The engine which the post process will be applied. (default: current engine)
  73048. * @param reusable If the post process can be reused on the same frame. (default: false)
  73049. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  73050. * @param textureType Type of textures used when performing the post process. (default: 0)
  73051. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  73052. * @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
  73053. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  73054. */
  73055. function PostProcess(
  73056. /** Name of the PostProcess. */
  73057. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  73058. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  73059. if (defines === void 0) { defines = null; }
  73060. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73061. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  73062. if (blockCompilation === void 0) { blockCompilation = false; }
  73063. this.name = name;
  73064. /**
  73065. * Width of the texture to apply the post process on
  73066. */
  73067. this.width = -1;
  73068. /**
  73069. * Height of the texture to apply the post process on
  73070. */
  73071. this.height = -1;
  73072. /**
  73073. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  73074. * @hidden
  73075. */
  73076. this._outputTexture = null;
  73077. /**
  73078. * If the buffer needs to be cleared before applying the post process. (default: true)
  73079. * Should be set to false if shader will overwrite all previous pixels.
  73080. */
  73081. this.autoClear = true;
  73082. /**
  73083. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  73084. */
  73085. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  73086. /**
  73087. * Animations to be used for the post processing
  73088. */
  73089. this.animations = new Array();
  73090. /**
  73091. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  73092. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  73093. */
  73094. this.enablePixelPerfectMode = false;
  73095. /**
  73096. * Force the postprocess to be applied without taking in account viewport
  73097. */
  73098. this.forceFullscreenViewport = true;
  73099. /**
  73100. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  73101. *
  73102. * | Value | Type | Description |
  73103. * | ----- | ----------------------------------- | ----------- |
  73104. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  73105. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  73106. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  73107. *
  73108. */
  73109. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  73110. /**
  73111. * Force textures to be a power of two (default: false)
  73112. */
  73113. this.alwaysForcePOT = false;
  73114. this._samples = 1;
  73115. /**
  73116. * Modify the scale of the post process to be the same as the viewport (default: false)
  73117. */
  73118. this.adaptScaleToCurrentViewport = false;
  73119. this._reusable = false;
  73120. /**
  73121. * Smart array of input and output textures for the post process.
  73122. * @hidden
  73123. */
  73124. this._textures = new BABYLON.SmartArray(2);
  73125. /**
  73126. * The index in _textures that corresponds to the output texture.
  73127. * @hidden
  73128. */
  73129. this._currentRenderTextureInd = 0;
  73130. this._scaleRatio = new BABYLON.Vector2(1, 1);
  73131. this._texelSize = BABYLON.Vector2.Zero();
  73132. // Events
  73133. /**
  73134. * An event triggered when the postprocess is activated.
  73135. */
  73136. this.onActivateObservable = new BABYLON.Observable();
  73137. /**
  73138. * An event triggered when the postprocess changes its size.
  73139. */
  73140. this.onSizeChangedObservable = new BABYLON.Observable();
  73141. /**
  73142. * An event triggered when the postprocess applies its effect.
  73143. */
  73144. this.onApplyObservable = new BABYLON.Observable();
  73145. /**
  73146. * An event triggered before rendering the postprocess
  73147. */
  73148. this.onBeforeRenderObservable = new BABYLON.Observable();
  73149. /**
  73150. * An event triggered after rendering the postprocess
  73151. */
  73152. this.onAfterRenderObservable = new BABYLON.Observable();
  73153. if (camera != null) {
  73154. this._camera = camera;
  73155. this._scene = camera.getScene();
  73156. camera.attachPostProcess(this);
  73157. this._engine = this._scene.getEngine();
  73158. this._scene.postProcesses.push(this);
  73159. }
  73160. else if (engine) {
  73161. this._engine = engine;
  73162. this._engine.postProcesses.push(this);
  73163. }
  73164. this._options = options;
  73165. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73166. this._reusable = reusable || false;
  73167. this._textureType = textureType;
  73168. this._samplers = samplers || [];
  73169. this._samplers.push("textureSampler");
  73170. this._fragmentUrl = fragmentUrl;
  73171. this._vertexUrl = vertexUrl;
  73172. this._parameters = parameters || [];
  73173. this._parameters.push("scale");
  73174. this._indexParameters = indexParameters;
  73175. if (!blockCompilation) {
  73176. this.updateEffect(defines);
  73177. }
  73178. }
  73179. Object.defineProperty(PostProcess.prototype, "samples", {
  73180. /**
  73181. * Number of sample textures (default: 1)
  73182. */
  73183. get: function () {
  73184. return this._samples;
  73185. },
  73186. set: function (n) {
  73187. var _this = this;
  73188. this._samples = n;
  73189. this._textures.forEach(function (texture) {
  73190. if (texture.samples !== _this._samples) {
  73191. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  73192. }
  73193. });
  73194. },
  73195. enumerable: true,
  73196. configurable: true
  73197. });
  73198. Object.defineProperty(PostProcess.prototype, "onActivate", {
  73199. /**
  73200. * A function that is added to the onActivateObservable
  73201. */
  73202. set: function (callback) {
  73203. if (this._onActivateObserver) {
  73204. this.onActivateObservable.remove(this._onActivateObserver);
  73205. }
  73206. if (callback) {
  73207. this._onActivateObserver = this.onActivateObservable.add(callback);
  73208. }
  73209. },
  73210. enumerable: true,
  73211. configurable: true
  73212. });
  73213. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  73214. /**
  73215. * A function that is added to the onSizeChangedObservable
  73216. */
  73217. set: function (callback) {
  73218. if (this._onSizeChangedObserver) {
  73219. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  73220. }
  73221. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  73222. },
  73223. enumerable: true,
  73224. configurable: true
  73225. });
  73226. Object.defineProperty(PostProcess.prototype, "onApply", {
  73227. /**
  73228. * A function that is added to the onApplyObservable
  73229. */
  73230. set: function (callback) {
  73231. if (this._onApplyObserver) {
  73232. this.onApplyObservable.remove(this._onApplyObserver);
  73233. }
  73234. this._onApplyObserver = this.onApplyObservable.add(callback);
  73235. },
  73236. enumerable: true,
  73237. configurable: true
  73238. });
  73239. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  73240. /**
  73241. * A function that is added to the onBeforeRenderObservable
  73242. */
  73243. set: function (callback) {
  73244. if (this._onBeforeRenderObserver) {
  73245. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73246. }
  73247. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73248. },
  73249. enumerable: true,
  73250. configurable: true
  73251. });
  73252. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  73253. /**
  73254. * A function that is added to the onAfterRenderObservable
  73255. */
  73256. set: function (callback) {
  73257. if (this._onAfterRenderObserver) {
  73258. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73259. }
  73260. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73261. },
  73262. enumerable: true,
  73263. configurable: true
  73264. });
  73265. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  73266. /**
  73267. * 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
  73268. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  73269. */
  73270. get: function () {
  73271. return this._textures.data[this._currentRenderTextureInd];
  73272. },
  73273. set: function (value) {
  73274. this._forcedOutputTexture = value;
  73275. },
  73276. enumerable: true,
  73277. configurable: true
  73278. });
  73279. /**
  73280. * Gets the camera which post process is applied to.
  73281. * @returns The camera the post process is applied to.
  73282. */
  73283. PostProcess.prototype.getCamera = function () {
  73284. return this._camera;
  73285. };
  73286. Object.defineProperty(PostProcess.prototype, "texelSize", {
  73287. /**
  73288. * Gets the texel size of the postprocess.
  73289. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  73290. */
  73291. get: function () {
  73292. if (this._shareOutputWithPostProcess) {
  73293. return this._shareOutputWithPostProcess.texelSize;
  73294. }
  73295. if (this._forcedOutputTexture) {
  73296. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  73297. }
  73298. return this._texelSize;
  73299. },
  73300. enumerable: true,
  73301. configurable: true
  73302. });
  73303. /**
  73304. * Gets the engine which this post process belongs to.
  73305. * @returns The engine the post process was enabled with.
  73306. */
  73307. PostProcess.prototype.getEngine = function () {
  73308. return this._engine;
  73309. };
  73310. /**
  73311. * The effect that is created when initializing the post process.
  73312. * @returns The created effect corrisponding the the postprocess.
  73313. */
  73314. PostProcess.prototype.getEffect = function () {
  73315. return this._effect;
  73316. };
  73317. /**
  73318. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  73319. * @param postProcess The post process to share the output with.
  73320. * @returns This post process.
  73321. */
  73322. PostProcess.prototype.shareOutputWith = function (postProcess) {
  73323. this._disposeTextures();
  73324. this._shareOutputWithPostProcess = postProcess;
  73325. return this;
  73326. };
  73327. /**
  73328. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  73329. * This should be called if the post process that shares output with this post process is disabled/disposed.
  73330. */
  73331. PostProcess.prototype.useOwnOutput = function () {
  73332. if (this._textures.length == 0) {
  73333. this._textures = new BABYLON.SmartArray(2);
  73334. }
  73335. this._shareOutputWithPostProcess = null;
  73336. };
  73337. /**
  73338. * Updates the effect with the current post process compile time values and recompiles the shader.
  73339. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73340. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73341. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73342. * @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
  73343. * @param onCompiled Called when the shader has been compiled.
  73344. * @param onError Called if there is an error when compiling a shader.
  73345. */
  73346. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73347. if (defines === void 0) { defines = null; }
  73348. if (uniforms === void 0) { uniforms = null; }
  73349. if (samplers === void 0) { samplers = null; }
  73350. 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);
  73351. };
  73352. /**
  73353. * The post process is reusable if it can be used multiple times within one frame.
  73354. * @returns If the post process is reusable
  73355. */
  73356. PostProcess.prototype.isReusable = function () {
  73357. return this._reusable;
  73358. };
  73359. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  73360. PostProcess.prototype.markTextureDirty = function () {
  73361. this.width = -1;
  73362. };
  73363. /**
  73364. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  73365. * 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.
  73366. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  73367. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  73368. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  73369. * @returns The target texture that was bound to be written to.
  73370. */
  73371. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  73372. var _this = this;
  73373. if (sourceTexture === void 0) { sourceTexture = null; }
  73374. camera = camera || this._camera;
  73375. var scene = camera.getScene();
  73376. var engine = scene.getEngine();
  73377. var maxSize = engine.getCaps().maxTextureSize;
  73378. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  73379. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  73380. // 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
  73381. var webVRCamera = camera.parent;
  73382. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  73383. requiredWidth /= 2;
  73384. }
  73385. var desiredWidth = (this._options.width || requiredWidth);
  73386. var desiredHeight = this._options.height || requiredHeight;
  73387. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  73388. if (this.adaptScaleToCurrentViewport) {
  73389. var currentViewport = engine.currentViewport;
  73390. if (currentViewport) {
  73391. desiredWidth *= currentViewport.width;
  73392. desiredHeight *= currentViewport.height;
  73393. }
  73394. }
  73395. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  73396. if (!this._options.width) {
  73397. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  73398. }
  73399. if (!this._options.height) {
  73400. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  73401. }
  73402. }
  73403. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  73404. if (this._textures.length > 0) {
  73405. for (var i = 0; i < this._textures.length; i++) {
  73406. this._engine._releaseTexture(this._textures.data[i]);
  73407. }
  73408. this._textures.reset();
  73409. }
  73410. this.width = desiredWidth;
  73411. this.height = desiredHeight;
  73412. var textureSize = { width: this.width, height: this.height };
  73413. var textureOptions = {
  73414. generateMipMaps: false,
  73415. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  73416. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  73417. samplingMode: this.renderTargetSamplingMode,
  73418. type: this._textureType
  73419. };
  73420. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  73421. if (this._reusable) {
  73422. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  73423. }
  73424. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  73425. this.onSizeChangedObservable.notifyObservers(this);
  73426. }
  73427. this._textures.forEach(function (texture) {
  73428. if (texture.samples !== _this.samples) {
  73429. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  73430. }
  73431. });
  73432. }
  73433. var target;
  73434. if (this._shareOutputWithPostProcess) {
  73435. target = this._shareOutputWithPostProcess.inputTexture;
  73436. }
  73437. else if (this._forcedOutputTexture) {
  73438. target = this._forcedOutputTexture;
  73439. this.width = this._forcedOutputTexture.width;
  73440. this.height = this._forcedOutputTexture.height;
  73441. }
  73442. else {
  73443. target = this.inputTexture;
  73444. }
  73445. // Bind the input of this post process to be used as the output of the previous post process.
  73446. if (this.enablePixelPerfectMode) {
  73447. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  73448. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  73449. }
  73450. else {
  73451. this._scaleRatio.copyFromFloats(1, 1);
  73452. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  73453. }
  73454. this.onActivateObservable.notifyObservers(camera);
  73455. // Clear
  73456. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  73457. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  73458. }
  73459. if (this._reusable) {
  73460. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  73461. }
  73462. return target;
  73463. };
  73464. Object.defineProperty(PostProcess.prototype, "isSupported", {
  73465. /**
  73466. * If the post process is supported.
  73467. */
  73468. get: function () {
  73469. return this._effect.isSupported;
  73470. },
  73471. enumerable: true,
  73472. configurable: true
  73473. });
  73474. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  73475. /**
  73476. * The aspect ratio of the output texture.
  73477. */
  73478. get: function () {
  73479. if (this._shareOutputWithPostProcess) {
  73480. return this._shareOutputWithPostProcess.aspectRatio;
  73481. }
  73482. if (this._forcedOutputTexture) {
  73483. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  73484. }
  73485. return this.width / this.height;
  73486. },
  73487. enumerable: true,
  73488. configurable: true
  73489. });
  73490. /**
  73491. * Get a value indicating if the post-process is ready to be used
  73492. * @returns true if the post-process is ready (shader is compiled)
  73493. */
  73494. PostProcess.prototype.isReady = function () {
  73495. return this._effect && this._effect.isReady();
  73496. };
  73497. /**
  73498. * Binds all textures and uniforms to the shader, this will be run on every pass.
  73499. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  73500. */
  73501. PostProcess.prototype.apply = function () {
  73502. // Check
  73503. if (!this._effect || !this._effect.isReady())
  73504. return null;
  73505. // States
  73506. this._engine.enableEffect(this._effect);
  73507. this._engine.setState(false);
  73508. this._engine.setDepthBuffer(false);
  73509. this._engine.setDepthWrite(false);
  73510. // Alpha
  73511. this._engine.setAlphaMode(this.alphaMode);
  73512. if (this.alphaConstants) {
  73513. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  73514. }
  73515. // Bind the output texture of the preivous post process as the input to this post process.
  73516. var source;
  73517. if (this._shareOutputWithPostProcess) {
  73518. source = this._shareOutputWithPostProcess.inputTexture;
  73519. }
  73520. else if (this._forcedOutputTexture) {
  73521. source = this._forcedOutputTexture;
  73522. }
  73523. else {
  73524. source = this.inputTexture;
  73525. }
  73526. this._effect._bindTexture("textureSampler", source);
  73527. // Parameters
  73528. this._effect.setVector2("scale", this._scaleRatio);
  73529. this.onApplyObservable.notifyObservers(this._effect);
  73530. return this._effect;
  73531. };
  73532. PostProcess.prototype._disposeTextures = function () {
  73533. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  73534. return;
  73535. }
  73536. if (this._textures.length > 0) {
  73537. for (var i = 0; i < this._textures.length; i++) {
  73538. this._engine._releaseTexture(this._textures.data[i]);
  73539. }
  73540. }
  73541. this._textures.dispose();
  73542. };
  73543. /**
  73544. * Disposes the post process.
  73545. * @param camera The camera to dispose the post process on.
  73546. */
  73547. PostProcess.prototype.dispose = function (camera) {
  73548. camera = camera || this._camera;
  73549. this._disposeTextures();
  73550. if (this._scene) {
  73551. var index_1 = this._scene.postProcesses.indexOf(this);
  73552. if (index_1 !== -1) {
  73553. this._scene.postProcesses.splice(index_1, 1);
  73554. }
  73555. }
  73556. else {
  73557. var index_2 = this._engine.postProcesses.indexOf(this);
  73558. if (index_2 !== -1) {
  73559. this._engine.postProcesses.splice(index_2, 1);
  73560. }
  73561. }
  73562. if (!camera) {
  73563. return;
  73564. }
  73565. camera.detachPostProcess(this);
  73566. var index = camera._postProcesses.indexOf(this);
  73567. if (index === 0 && camera._postProcesses.length > 0) {
  73568. var firstPostProcess = this._camera._getFirstPostProcess();
  73569. if (firstPostProcess) {
  73570. firstPostProcess.markTextureDirty();
  73571. }
  73572. }
  73573. this.onActivateObservable.clear();
  73574. this.onAfterRenderObservable.clear();
  73575. this.onApplyObservable.clear();
  73576. this.onBeforeRenderObservable.clear();
  73577. this.onSizeChangedObservable.clear();
  73578. };
  73579. return PostProcess;
  73580. }());
  73581. BABYLON.PostProcess = PostProcess;
  73582. })(BABYLON || (BABYLON = {}));
  73583. //# sourceMappingURL=babylon.postProcess.js.map
  73584. var BABYLON;
  73585. (function (BABYLON) {
  73586. var PassPostProcess = /** @class */ (function (_super) {
  73587. __extends(PassPostProcess, _super);
  73588. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73589. if (camera === void 0) { camera = null; }
  73590. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73591. if (blockCompilation === void 0) { blockCompilation = false; }
  73592. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  73593. }
  73594. return PassPostProcess;
  73595. }(BABYLON.PostProcess));
  73596. BABYLON.PassPostProcess = PassPostProcess;
  73597. })(BABYLON || (BABYLON = {}));
  73598. //# sourceMappingURL=babylon.passPostProcess.js.map
  73599. var __assign = (this && this.__assign) || function () {
  73600. __assign = Object.assign || function(t) {
  73601. for (var s, i = 1, n = arguments.length; i < n; i++) {
  73602. s = arguments[i];
  73603. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  73604. t[p] = s[p];
  73605. }
  73606. return t;
  73607. };
  73608. return __assign.apply(this, arguments);
  73609. };
  73610. var BABYLON;
  73611. (function (BABYLON) {
  73612. /**
  73613. * Default implementation IShadowGenerator.
  73614. * This is the main object responsible of generating shadows in the framework.
  73615. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  73616. */
  73617. var ShadowGenerator = /** @class */ (function () {
  73618. /**
  73619. * Creates a ShadowGenerator object.
  73620. * A ShadowGenerator is the required tool to use the shadows.
  73621. * Each light casting shadows needs to use its own ShadowGenerator.
  73622. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  73623. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  73624. * @param light The light object generating the shadows.
  73625. * @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.
  73626. */
  73627. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  73628. this._bias = 0.00005;
  73629. this._normalBias = 0;
  73630. this._blurBoxOffset = 1;
  73631. this._blurScale = 2;
  73632. this._blurKernel = 1;
  73633. this._useKernelBlur = false;
  73634. this._filter = ShadowGenerator.FILTER_NONE;
  73635. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  73636. this._contactHardeningLightSizeUVRatio = 0.1;
  73637. this._darkness = 0;
  73638. this._transparencyShadow = false;
  73639. /**
  73640. * Controls the extent to which the shadows fade out at the edge of the frustum
  73641. * Used only by directionals and spots
  73642. */
  73643. this.frustumEdgeFalloff = 0;
  73644. /**
  73645. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  73646. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  73647. * It might on the other hand introduce peter panning.
  73648. */
  73649. this.forceBackFacesOnly = false;
  73650. this._lightDirection = BABYLON.Vector3.Zero();
  73651. this._viewMatrix = BABYLON.Matrix.Zero();
  73652. this._projectionMatrix = BABYLON.Matrix.Zero();
  73653. this._transformMatrix = BABYLON.Matrix.Zero();
  73654. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73655. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73656. this._currentFaceIndex = 0;
  73657. this._currentFaceIndexCache = 0;
  73658. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  73659. this._mapSize = mapSize;
  73660. this._light = light;
  73661. this._scene = light.getScene();
  73662. light._shadowGenerator = this;
  73663. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  73664. if (!component) {
  73665. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  73666. this._scene._addComponent(component);
  73667. }
  73668. // Texture type fallback from float to int if not supported.
  73669. var caps = this._scene.getEngine().getCaps();
  73670. if (!useFullFloatFirst) {
  73671. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73672. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73673. }
  73674. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73675. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73676. }
  73677. else {
  73678. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73679. }
  73680. }
  73681. else {
  73682. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73683. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73684. }
  73685. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73686. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73687. }
  73688. else {
  73689. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73690. }
  73691. }
  73692. this._initializeGenerator();
  73693. this._applyFilterValues();
  73694. }
  73695. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  73696. /**
  73697. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  73698. */
  73699. get: function () {
  73700. return this._bias;
  73701. },
  73702. /**
  73703. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  73704. */
  73705. set: function (bias) {
  73706. this._bias = bias;
  73707. },
  73708. enumerable: true,
  73709. configurable: true
  73710. });
  73711. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  73712. /**
  73713. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73714. */
  73715. get: function () {
  73716. return this._normalBias;
  73717. },
  73718. /**
  73719. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73720. */
  73721. set: function (normalBias) {
  73722. this._normalBias = normalBias;
  73723. },
  73724. enumerable: true,
  73725. configurable: true
  73726. });
  73727. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  73728. /**
  73729. * Gets the blur box offset: offset applied during the blur pass.
  73730. * Only usefull if useKernelBlur = false
  73731. */
  73732. get: function () {
  73733. return this._blurBoxOffset;
  73734. },
  73735. /**
  73736. * Sets the blur box offset: offset applied during the blur pass.
  73737. * Only usefull if useKernelBlur = false
  73738. */
  73739. set: function (value) {
  73740. if (this._blurBoxOffset === value) {
  73741. return;
  73742. }
  73743. this._blurBoxOffset = value;
  73744. this._disposeBlurPostProcesses();
  73745. },
  73746. enumerable: true,
  73747. configurable: true
  73748. });
  73749. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  73750. /**
  73751. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  73752. * 2 means half of the size.
  73753. */
  73754. get: function () {
  73755. return this._blurScale;
  73756. },
  73757. /**
  73758. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  73759. * 2 means half of the size.
  73760. */
  73761. set: function (value) {
  73762. if (this._blurScale === value) {
  73763. return;
  73764. }
  73765. this._blurScale = value;
  73766. this._disposeBlurPostProcesses();
  73767. },
  73768. enumerable: true,
  73769. configurable: true
  73770. });
  73771. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  73772. /**
  73773. * Gets the blur kernel: kernel size of the blur pass.
  73774. * Only usefull if useKernelBlur = true
  73775. */
  73776. get: function () {
  73777. return this._blurKernel;
  73778. },
  73779. /**
  73780. * Sets the blur kernel: kernel size of the blur pass.
  73781. * Only usefull if useKernelBlur = true
  73782. */
  73783. set: function (value) {
  73784. if (this._blurKernel === value) {
  73785. return;
  73786. }
  73787. this._blurKernel = value;
  73788. this._disposeBlurPostProcesses();
  73789. },
  73790. enumerable: true,
  73791. configurable: true
  73792. });
  73793. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  73794. /**
  73795. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  73796. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73797. */
  73798. get: function () {
  73799. return this._useKernelBlur;
  73800. },
  73801. /**
  73802. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  73803. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73804. */
  73805. set: function (value) {
  73806. if (this._useKernelBlur === value) {
  73807. return;
  73808. }
  73809. this._useKernelBlur = value;
  73810. this._disposeBlurPostProcesses();
  73811. },
  73812. enumerable: true,
  73813. configurable: true
  73814. });
  73815. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  73816. /**
  73817. * Gets the depth scale used in ESM mode.
  73818. */
  73819. get: function () {
  73820. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  73821. },
  73822. /**
  73823. * Sets the depth scale used in ESM mode.
  73824. * This can override the scale stored on the light.
  73825. */
  73826. set: function (value) {
  73827. this._depthScale = value;
  73828. },
  73829. enumerable: true,
  73830. configurable: true
  73831. });
  73832. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  73833. /**
  73834. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  73835. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73836. */
  73837. get: function () {
  73838. return this._filter;
  73839. },
  73840. /**
  73841. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  73842. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73843. */
  73844. set: function (value) {
  73845. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  73846. if (this._light.needCube()) {
  73847. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73848. this.useExponentialShadowMap = true;
  73849. return;
  73850. }
  73851. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73852. this.useCloseExponentialShadowMap = true;
  73853. return;
  73854. }
  73855. // PCF on cubemap would also be expensive
  73856. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73857. this.usePoissonSampling = true;
  73858. return;
  73859. }
  73860. }
  73861. // Weblg1 fallback for PCF.
  73862. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73863. if (this._scene.getEngine().webGLVersion === 1) {
  73864. this.usePoissonSampling = true;
  73865. return;
  73866. }
  73867. }
  73868. if (this._filter === value) {
  73869. return;
  73870. }
  73871. this._filter = value;
  73872. this._disposeBlurPostProcesses();
  73873. this._applyFilterValues();
  73874. this._light._markMeshesAsLightDirty();
  73875. },
  73876. enumerable: true,
  73877. configurable: true
  73878. });
  73879. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  73880. /**
  73881. * Gets if the current filter is set to Poisson Sampling.
  73882. */
  73883. get: function () {
  73884. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  73885. },
  73886. /**
  73887. * Sets the current filter to Poisson Sampling.
  73888. */
  73889. set: function (value) {
  73890. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  73891. return;
  73892. }
  73893. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  73894. },
  73895. enumerable: true,
  73896. configurable: true
  73897. });
  73898. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  73899. /**
  73900. * Gets if the current filter is set to VSM.
  73901. * DEPRECATED. Should use useExponentialShadowMap instead.
  73902. */
  73903. get: function () {
  73904. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73905. return this.useExponentialShadowMap;
  73906. },
  73907. /**
  73908. * Sets the current filter is to VSM.
  73909. * DEPRECATED. Should use useExponentialShadowMap instead.
  73910. */
  73911. set: function (value) {
  73912. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73913. this.useExponentialShadowMap = value;
  73914. },
  73915. enumerable: true,
  73916. configurable: true
  73917. });
  73918. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  73919. /**
  73920. * Gets if the current filter is set to blurred VSM.
  73921. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73922. */
  73923. get: function () {
  73924. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73925. return this.useBlurExponentialShadowMap;
  73926. },
  73927. /**
  73928. * Sets the current filter is to blurred VSM.
  73929. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73930. */
  73931. set: function (value) {
  73932. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73933. this.useBlurExponentialShadowMap = value;
  73934. },
  73935. enumerable: true,
  73936. configurable: true
  73937. });
  73938. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  73939. /**
  73940. * Gets if the current filter is set to ESM.
  73941. */
  73942. get: function () {
  73943. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  73944. },
  73945. /**
  73946. * Sets the current filter is to ESM.
  73947. */
  73948. set: function (value) {
  73949. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  73950. return;
  73951. }
  73952. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73953. },
  73954. enumerable: true,
  73955. configurable: true
  73956. });
  73957. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  73958. /**
  73959. * Gets if the current filter is set to filtered ESM.
  73960. */
  73961. get: function () {
  73962. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  73963. },
  73964. /**
  73965. * Gets if the current filter is set to filtered ESM.
  73966. */
  73967. set: function (value) {
  73968. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73969. return;
  73970. }
  73971. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73972. },
  73973. enumerable: true,
  73974. configurable: true
  73975. });
  73976. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  73977. /**
  73978. * Gets if the current filter is set to "close ESM" (using the inverse of the
  73979. * exponential to prevent steep falloff artifacts).
  73980. */
  73981. get: function () {
  73982. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  73983. },
  73984. /**
  73985. * Sets the current filter to "close ESM" (using the inverse of the
  73986. * exponential to prevent steep falloff artifacts).
  73987. */
  73988. set: function (value) {
  73989. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  73990. return;
  73991. }
  73992. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73993. },
  73994. enumerable: true,
  73995. configurable: true
  73996. });
  73997. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  73998. /**
  73999. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  74000. * exponential to prevent steep falloff artifacts).
  74001. */
  74002. get: function () {
  74003. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  74004. },
  74005. /**
  74006. * Sets the current filter to filtered "close ESM" (using the inverse of the
  74007. * exponential to prevent steep falloff artifacts).
  74008. */
  74009. set: function (value) {
  74010. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74011. return;
  74012. }
  74013. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74014. },
  74015. enumerable: true,
  74016. configurable: true
  74017. });
  74018. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  74019. /**
  74020. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  74021. */
  74022. get: function () {
  74023. return this.filter === ShadowGenerator.FILTER_PCF;
  74024. },
  74025. /**
  74026. * Sets the current filter to "PCF" (percentage closer filtering).
  74027. */
  74028. set: function (value) {
  74029. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  74030. return;
  74031. }
  74032. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  74033. },
  74034. enumerable: true,
  74035. configurable: true
  74036. });
  74037. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  74038. /**
  74039. * Gets the PCF or PCSS Quality.
  74040. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74041. */
  74042. get: function () {
  74043. return this._filteringQuality;
  74044. },
  74045. /**
  74046. * Sets the PCF or PCSS Quality.
  74047. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74048. */
  74049. set: function (filteringQuality) {
  74050. this._filteringQuality = filteringQuality;
  74051. },
  74052. enumerable: true,
  74053. configurable: true
  74054. });
  74055. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  74056. /**
  74057. * Gets if the current filter is set to "PCSS" (contact hardening).
  74058. */
  74059. get: function () {
  74060. return this.filter === ShadowGenerator.FILTER_PCSS;
  74061. },
  74062. /**
  74063. * Sets the current filter to "PCSS" (contact hardening).
  74064. */
  74065. set: function (value) {
  74066. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  74067. return;
  74068. }
  74069. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  74070. },
  74071. enumerable: true,
  74072. configurable: true
  74073. });
  74074. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  74075. /**
  74076. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74077. * Using a ratio helps keeping shape stability independently of the map size.
  74078. *
  74079. * It does not account for the light projection as it was having too much
  74080. * instability during the light setup or during light position changes.
  74081. *
  74082. * Only valid if useContactHardeningShadow is true.
  74083. */
  74084. get: function () {
  74085. return this._contactHardeningLightSizeUVRatio;
  74086. },
  74087. /**
  74088. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74089. * Using a ratio helps keeping shape stability independently of the map size.
  74090. *
  74091. * It does not account for the light projection as it was having too much
  74092. * instability during the light setup or during light position changes.
  74093. *
  74094. * Only valid if useContactHardeningShadow is true.
  74095. */
  74096. set: function (contactHardeningLightSizeUVRatio) {
  74097. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  74098. },
  74099. enumerable: true,
  74100. configurable: true
  74101. });
  74102. /**
  74103. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  74104. * 0 means strongest and 1 would means no shadow.
  74105. * @returns the darkness.
  74106. */
  74107. ShadowGenerator.prototype.getDarkness = function () {
  74108. return this._darkness;
  74109. };
  74110. /**
  74111. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  74112. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  74113. * @returns the shadow generator allowing fluent coding.
  74114. */
  74115. ShadowGenerator.prototype.setDarkness = function (darkness) {
  74116. if (darkness >= 1.0)
  74117. this._darkness = 1.0;
  74118. else if (darkness <= 0.0)
  74119. this._darkness = 0.0;
  74120. else
  74121. this._darkness = darkness;
  74122. return this;
  74123. };
  74124. /**
  74125. * Sets the ability to have transparent shadow (boolean).
  74126. * @param transparent True if transparent else False
  74127. * @returns the shadow generator allowing fluent coding
  74128. */
  74129. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  74130. this._transparencyShadow = transparent;
  74131. return this;
  74132. };
  74133. /**
  74134. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  74135. * @returns The render target texture if present otherwise, null
  74136. */
  74137. ShadowGenerator.prototype.getShadowMap = function () {
  74138. return this._shadowMap;
  74139. };
  74140. /**
  74141. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  74142. * @returns The render target texture if the shadow map is present otherwise, null
  74143. */
  74144. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  74145. if (this._shadowMap2) {
  74146. return this._shadowMap2;
  74147. }
  74148. return this._shadowMap;
  74149. };
  74150. /**
  74151. * Helper function to add a mesh and its descendants to the list of shadow casters.
  74152. * @param mesh Mesh to add
  74153. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  74154. * @returns the Shadow Generator itself
  74155. */
  74156. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  74157. if (includeDescendants === void 0) { includeDescendants = true; }
  74158. var _a;
  74159. if (!this._shadowMap) {
  74160. return this;
  74161. }
  74162. if (!this._shadowMap.renderList) {
  74163. this._shadowMap.renderList = [];
  74164. }
  74165. this._shadowMap.renderList.push(mesh);
  74166. if (includeDescendants) {
  74167. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  74168. }
  74169. return this;
  74170. };
  74171. /**
  74172. * Helper function to remove a mesh and its descendants from the list of shadow casters
  74173. * @param mesh Mesh to remove
  74174. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  74175. * @returns the Shadow Generator itself
  74176. */
  74177. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  74178. if (includeDescendants === void 0) { includeDescendants = true; }
  74179. if (!this._shadowMap || !this._shadowMap.renderList) {
  74180. return this;
  74181. }
  74182. var index = this._shadowMap.renderList.indexOf(mesh);
  74183. if (index !== -1) {
  74184. this._shadowMap.renderList.splice(index, 1);
  74185. }
  74186. if (includeDescendants) {
  74187. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  74188. var child = _a[_i];
  74189. this.removeShadowCaster(child);
  74190. }
  74191. }
  74192. return this;
  74193. };
  74194. /**
  74195. * Returns the associated light object.
  74196. * @returns the light generating the shadow
  74197. */
  74198. ShadowGenerator.prototype.getLight = function () {
  74199. return this._light;
  74200. };
  74201. ShadowGenerator.prototype._initializeGenerator = function () {
  74202. this._light._markMeshesAsLightDirty();
  74203. this._initializeShadowMap();
  74204. };
  74205. ShadowGenerator.prototype._initializeShadowMap = function () {
  74206. var _this = this;
  74207. // Render target
  74208. var engine = this._scene.getEngine();
  74209. if (engine.webGLVersion > 1) {
  74210. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  74211. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  74212. }
  74213. else {
  74214. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  74215. }
  74216. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74217. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74218. this._shadowMap.anisotropicFilteringLevel = 1;
  74219. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74220. this._shadowMap.renderParticles = false;
  74221. this._shadowMap.ignoreCameraViewport = true;
  74222. // Record Face Index before render.
  74223. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  74224. _this._currentFaceIndex = faceIndex;
  74225. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74226. engine.setColorWrite(false);
  74227. }
  74228. });
  74229. // Custom render function.
  74230. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  74231. // Blur if required afer render.
  74232. this._shadowMap.onAfterUnbindObservable.add(function () {
  74233. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74234. engine.setColorWrite(true);
  74235. }
  74236. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  74237. return;
  74238. }
  74239. var shadowMap = _this.getShadowMapForRendering();
  74240. if (shadowMap) {
  74241. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  74242. }
  74243. });
  74244. // Clear according to the chosen filter.
  74245. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  74246. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  74247. this._shadowMap.onClearObservable.add(function (engine) {
  74248. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74249. engine.clear(clearOne, false, true, false);
  74250. }
  74251. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  74252. engine.clear(clearZero, true, true, false);
  74253. }
  74254. else {
  74255. engine.clear(clearOne, true, true, false);
  74256. }
  74257. });
  74258. };
  74259. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  74260. var _this = this;
  74261. var engine = this._scene.getEngine();
  74262. var targetSize = this._mapSize / this.blurScale;
  74263. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  74264. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  74265. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74266. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74267. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74268. }
  74269. if (this.useKernelBlur) {
  74270. 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);
  74271. this._kernelBlurXPostprocess.width = targetSize;
  74272. this._kernelBlurXPostprocess.height = targetSize;
  74273. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  74274. effect.setTexture("textureSampler", _this._shadowMap);
  74275. });
  74276. 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);
  74277. this._kernelBlurXPostprocess.autoClear = false;
  74278. this._kernelBlurYPostprocess.autoClear = false;
  74279. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74280. this._kernelBlurXPostprocess.packedFloat = true;
  74281. this._kernelBlurYPostprocess.packedFloat = true;
  74282. }
  74283. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  74284. }
  74285. else {
  74286. 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);
  74287. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  74288. effect.setFloat2("screenSize", targetSize, targetSize);
  74289. effect.setTexture("textureSampler", _this._shadowMap);
  74290. });
  74291. this._boxBlurPostprocess.autoClear = false;
  74292. this._blurPostProcesses = [this._boxBlurPostprocess];
  74293. }
  74294. };
  74295. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74296. var index;
  74297. var engine = this._scene.getEngine();
  74298. if (depthOnlySubMeshes.length) {
  74299. engine.setColorWrite(false);
  74300. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74301. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  74302. }
  74303. engine.setColorWrite(true);
  74304. }
  74305. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74306. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  74307. }
  74308. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74309. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  74310. }
  74311. if (this._transparencyShadow) {
  74312. for (index = 0; index < transparentSubMeshes.length; index++) {
  74313. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  74314. }
  74315. }
  74316. };
  74317. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  74318. var _this = this;
  74319. var mesh = subMesh.getRenderingMesh();
  74320. var scene = this._scene;
  74321. var engine = scene.getEngine();
  74322. var material = subMesh.getMaterial();
  74323. if (!material) {
  74324. return;
  74325. }
  74326. // Culling
  74327. engine.setState(material.backFaceCulling);
  74328. // Managing instances
  74329. var batch = mesh._getInstancesRenderList(subMesh._id);
  74330. if (batch.mustReturn) {
  74331. return;
  74332. }
  74333. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74334. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  74335. engine.enableEffect(this._effect);
  74336. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  74337. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  74338. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  74339. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74340. this._effect.setVector3("lightData", this._cachedDirection);
  74341. }
  74342. else {
  74343. this._effect.setVector3("lightData", this._cachedPosition);
  74344. }
  74345. if (scene.activeCamera) {
  74346. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  74347. }
  74348. // Alpha test
  74349. if (material && material.needAlphaTesting()) {
  74350. var alphaTexture = material.getAlphaTestTexture();
  74351. if (alphaTexture) {
  74352. this._effect.setTexture("diffuseSampler", alphaTexture);
  74353. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  74354. }
  74355. }
  74356. // Bones
  74357. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74358. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  74359. }
  74360. // Morph targets
  74361. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  74362. if (this.forceBackFacesOnly) {
  74363. engine.setState(true, 0, false, true);
  74364. }
  74365. // Draw
  74366. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74367. if (this.forceBackFacesOnly) {
  74368. engine.setState(true, 0, false, false);
  74369. }
  74370. }
  74371. else {
  74372. // Need to reset refresh rate of the shadowMap
  74373. if (this._shadowMap) {
  74374. this._shadowMap.resetRefreshCounter();
  74375. }
  74376. }
  74377. };
  74378. ShadowGenerator.prototype._applyFilterValues = function () {
  74379. if (!this._shadowMap) {
  74380. return;
  74381. }
  74382. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  74383. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  74384. }
  74385. else {
  74386. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74387. }
  74388. };
  74389. /**
  74390. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  74391. * @param onCompiled Callback triggered at the and of the effects compilation
  74392. * @param options Sets of optional options forcing the compilation with different modes
  74393. */
  74394. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  74395. var _this = this;
  74396. var localOptions = __assign({ useInstances: false }, options);
  74397. var shadowMap = this.getShadowMap();
  74398. if (!shadowMap) {
  74399. if (onCompiled) {
  74400. onCompiled(this);
  74401. }
  74402. return;
  74403. }
  74404. var renderList = shadowMap.renderList;
  74405. if (!renderList) {
  74406. if (onCompiled) {
  74407. onCompiled(this);
  74408. }
  74409. return;
  74410. }
  74411. var subMeshes = new Array();
  74412. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  74413. var mesh = renderList_1[_i];
  74414. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  74415. }
  74416. if (subMeshes.length === 0) {
  74417. if (onCompiled) {
  74418. onCompiled(this);
  74419. }
  74420. return;
  74421. }
  74422. var currentIndex = 0;
  74423. var checkReady = function () {
  74424. if (!_this._scene || !_this._scene.getEngine()) {
  74425. return;
  74426. }
  74427. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  74428. currentIndex++;
  74429. if (currentIndex >= subMeshes.length) {
  74430. if (onCompiled) {
  74431. onCompiled(_this);
  74432. }
  74433. return;
  74434. }
  74435. }
  74436. setTimeout(checkReady, 16);
  74437. };
  74438. checkReady();
  74439. };
  74440. /**
  74441. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  74442. * @param options Sets of optional options forcing the compilation with different modes
  74443. * @returns A promise that resolves when the compilation completes
  74444. */
  74445. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  74446. var _this = this;
  74447. return new Promise(function (resolve) {
  74448. _this.forceCompilation(function () {
  74449. resolve();
  74450. }, options);
  74451. });
  74452. };
  74453. /**
  74454. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  74455. * @param subMesh The submesh we want to render in the shadow map
  74456. * @param useInstances Defines wether will draw in the map using instances
  74457. * @returns true if ready otherwise, false
  74458. */
  74459. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  74460. var defines = [];
  74461. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74462. defines.push("#define FLOAT");
  74463. }
  74464. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74465. defines.push("#define ESM");
  74466. }
  74467. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  74468. defines.push("#define DEPTHTEXTURE");
  74469. }
  74470. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74471. var mesh = subMesh.getMesh();
  74472. var material = subMesh.getMaterial();
  74473. // Normal bias.
  74474. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74475. attribs.push(BABYLON.VertexBuffer.NormalKind);
  74476. defines.push("#define NORMAL");
  74477. if (mesh.nonUniformScaling) {
  74478. defines.push("#define NONUNIFORMSCALING");
  74479. }
  74480. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74481. defines.push("#define DIRECTIONINLIGHTDATA");
  74482. }
  74483. }
  74484. // Alpha test
  74485. if (material && material.needAlphaTesting()) {
  74486. var alphaTexture = material.getAlphaTestTexture();
  74487. if (alphaTexture) {
  74488. defines.push("#define ALPHATEST");
  74489. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74490. attribs.push(BABYLON.VertexBuffer.UVKind);
  74491. defines.push("#define UV1");
  74492. }
  74493. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74494. if (alphaTexture.coordinatesIndex === 1) {
  74495. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74496. defines.push("#define UV2");
  74497. }
  74498. }
  74499. }
  74500. }
  74501. // Bones
  74502. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74503. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74504. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74505. if (mesh.numBoneInfluencers > 4) {
  74506. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74507. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74508. }
  74509. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74510. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  74511. }
  74512. else {
  74513. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74514. }
  74515. // Morph targets
  74516. var manager = mesh.morphTargetManager;
  74517. var morphInfluencers = 0;
  74518. if (manager) {
  74519. if (manager.numInfluencers > 0) {
  74520. defines.push("#define MORPHTARGETS");
  74521. morphInfluencers = manager.numInfluencers;
  74522. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  74523. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  74524. }
  74525. }
  74526. // Instances
  74527. if (useInstances) {
  74528. defines.push("#define INSTANCES");
  74529. attribs.push("world0");
  74530. attribs.push("world1");
  74531. attribs.push("world2");
  74532. attribs.push("world3");
  74533. }
  74534. // Get correct effect
  74535. var join = defines.join("\n");
  74536. if (this._cachedDefines !== join) {
  74537. this._cachedDefines = join;
  74538. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  74539. }
  74540. if (!this._effect.isReady()) {
  74541. return false;
  74542. }
  74543. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74544. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  74545. this._initializeBlurRTTAndPostProcesses();
  74546. }
  74547. }
  74548. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  74549. return false;
  74550. }
  74551. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  74552. return false;
  74553. }
  74554. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  74555. return false;
  74556. }
  74557. return true;
  74558. };
  74559. /**
  74560. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  74561. * @param defines Defines of the material we want to update
  74562. * @param lightIndex Index of the light in the enabled light list of the material
  74563. */
  74564. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  74565. var scene = this._scene;
  74566. var light = this._light;
  74567. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74568. return;
  74569. }
  74570. defines["SHADOW" + lightIndex] = true;
  74571. if (this.useContactHardeningShadow) {
  74572. defines["SHADOWPCSS" + lightIndex] = true;
  74573. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74574. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74575. }
  74576. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74577. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74578. }
  74579. // else default to high.
  74580. }
  74581. if (this.usePercentageCloserFiltering) {
  74582. defines["SHADOWPCF" + lightIndex] = true;
  74583. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74584. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74585. }
  74586. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74587. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74588. }
  74589. // else default to high.
  74590. }
  74591. else if (this.usePoissonSampling) {
  74592. defines["SHADOWPOISSON" + lightIndex] = true;
  74593. }
  74594. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74595. defines["SHADOWESM" + lightIndex] = true;
  74596. }
  74597. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74598. defines["SHADOWCLOSEESM" + lightIndex] = true;
  74599. }
  74600. if (light.needCube()) {
  74601. defines["SHADOWCUBE" + lightIndex] = true;
  74602. }
  74603. };
  74604. /**
  74605. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  74606. * defined in the generator but impacting the effect).
  74607. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  74608. * @param effect The effect we are binfing the information for
  74609. */
  74610. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  74611. var light = this._light;
  74612. var scene = this._scene;
  74613. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74614. return;
  74615. }
  74616. var camera = scene.activeCamera;
  74617. if (!camera) {
  74618. return;
  74619. }
  74620. var shadowMap = this.getShadowMap();
  74621. if (!shadowMap) {
  74622. return;
  74623. }
  74624. if (!light.needCube()) {
  74625. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  74626. }
  74627. // Only PCF uses depth stencil texture.
  74628. if (this._filter === ShadowGenerator.FILTER_PCF) {
  74629. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74630. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74631. }
  74632. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  74633. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74634. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  74635. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74636. }
  74637. else {
  74638. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74639. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  74640. }
  74641. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  74642. };
  74643. /**
  74644. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  74645. * (eq to shadow prjection matrix * light transform matrix)
  74646. * @returns The transform matrix used to create the shadow map
  74647. */
  74648. ShadowGenerator.prototype.getTransformMatrix = function () {
  74649. var scene = this._scene;
  74650. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  74651. return this._transformMatrix;
  74652. }
  74653. this._currentRenderID = scene.getRenderId();
  74654. this._currentFaceIndexCache = this._currentFaceIndex;
  74655. var lightPosition = this._light.position;
  74656. if (this._light.computeTransformedInformation()) {
  74657. lightPosition = this._light.transformedPosition;
  74658. }
  74659. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  74660. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  74661. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  74662. }
  74663. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  74664. this._cachedPosition.copyFrom(lightPosition);
  74665. this._cachedDirection.copyFrom(this._lightDirection);
  74666. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  74667. var shadowMap = this.getShadowMap();
  74668. if (shadowMap) {
  74669. var renderList = shadowMap.renderList;
  74670. if (renderList) {
  74671. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  74672. }
  74673. }
  74674. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  74675. }
  74676. return this._transformMatrix;
  74677. };
  74678. /**
  74679. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  74680. * Cube and 2D textures for instance.
  74681. */
  74682. ShadowGenerator.prototype.recreateShadowMap = function () {
  74683. var shadowMap = this._shadowMap;
  74684. if (!shadowMap) {
  74685. return;
  74686. }
  74687. // Track render list.
  74688. var renderList = shadowMap.renderList;
  74689. // Clean up existing data.
  74690. this._disposeRTTandPostProcesses();
  74691. // Reinitializes.
  74692. this._initializeGenerator();
  74693. // Reaffect the filter to ensure a correct fallback if necessary.
  74694. this.filter = this.filter;
  74695. // Reaffect the filter.
  74696. this._applyFilterValues();
  74697. // Reaffect Render List.
  74698. this._shadowMap.renderList = renderList;
  74699. };
  74700. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  74701. if (this._shadowMap2) {
  74702. this._shadowMap2.dispose();
  74703. this._shadowMap2 = null;
  74704. }
  74705. if (this._boxBlurPostprocess) {
  74706. this._boxBlurPostprocess.dispose();
  74707. this._boxBlurPostprocess = null;
  74708. }
  74709. if (this._kernelBlurXPostprocess) {
  74710. this._kernelBlurXPostprocess.dispose();
  74711. this._kernelBlurXPostprocess = null;
  74712. }
  74713. if (this._kernelBlurYPostprocess) {
  74714. this._kernelBlurYPostprocess.dispose();
  74715. this._kernelBlurYPostprocess = null;
  74716. }
  74717. this._blurPostProcesses = [];
  74718. };
  74719. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  74720. if (this._shadowMap) {
  74721. this._shadowMap.dispose();
  74722. this._shadowMap = null;
  74723. }
  74724. this._disposeBlurPostProcesses();
  74725. };
  74726. /**
  74727. * Disposes the ShadowGenerator.
  74728. * Returns nothing.
  74729. */
  74730. ShadowGenerator.prototype.dispose = function () {
  74731. this._disposeRTTandPostProcesses();
  74732. if (this._light) {
  74733. this._light._shadowGenerator = null;
  74734. this._light._markMeshesAsLightDirty();
  74735. }
  74736. };
  74737. /**
  74738. * Serializes the shadow generator setup to a json object.
  74739. * @returns The serialized JSON object
  74740. */
  74741. ShadowGenerator.prototype.serialize = function () {
  74742. var serializationObject = {};
  74743. var shadowMap = this.getShadowMap();
  74744. if (!shadowMap) {
  74745. return serializationObject;
  74746. }
  74747. serializationObject.lightId = this._light.id;
  74748. serializationObject.mapSize = shadowMap.getRenderSize();
  74749. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  74750. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  74751. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74752. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74753. serializationObject.usePoissonSampling = this.usePoissonSampling;
  74754. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  74755. serializationObject.depthScale = this.depthScale;
  74756. serializationObject.darkness = this.getDarkness();
  74757. serializationObject.blurBoxOffset = this.blurBoxOffset;
  74758. serializationObject.blurKernel = this.blurKernel;
  74759. serializationObject.blurScale = this.blurScale;
  74760. serializationObject.useKernelBlur = this.useKernelBlur;
  74761. serializationObject.transparencyShadow = this._transparencyShadow;
  74762. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  74763. serializationObject.bias = this.bias;
  74764. serializationObject.normalBias = this.normalBias;
  74765. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  74766. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  74767. serializationObject.filteringQuality = this.filteringQuality;
  74768. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  74769. serializationObject.renderList = [];
  74770. if (shadowMap.renderList) {
  74771. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  74772. var mesh = shadowMap.renderList[meshIndex];
  74773. serializationObject.renderList.push(mesh.id);
  74774. }
  74775. }
  74776. return serializationObject;
  74777. };
  74778. /**
  74779. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  74780. * @param parsedShadowGenerator The JSON object to parse
  74781. * @param scene The scene to create the shadow map for
  74782. * @returns The parsed shadow generator
  74783. */
  74784. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  74785. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  74786. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  74787. var shadowMap = shadowGenerator.getShadowMap();
  74788. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  74789. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  74790. meshes.forEach(function (mesh) {
  74791. if (!shadowMap) {
  74792. return;
  74793. }
  74794. if (!shadowMap.renderList) {
  74795. shadowMap.renderList = [];
  74796. }
  74797. shadowMap.renderList.push(mesh);
  74798. });
  74799. }
  74800. if (parsedShadowGenerator.usePoissonSampling) {
  74801. shadowGenerator.usePoissonSampling = true;
  74802. }
  74803. else if (parsedShadowGenerator.useExponentialShadowMap) {
  74804. shadowGenerator.useExponentialShadowMap = true;
  74805. }
  74806. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  74807. shadowGenerator.useBlurExponentialShadowMap = true;
  74808. }
  74809. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  74810. shadowGenerator.useCloseExponentialShadowMap = true;
  74811. }
  74812. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  74813. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  74814. }
  74815. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  74816. shadowGenerator.usePercentageCloserFiltering = true;
  74817. }
  74818. else if (parsedShadowGenerator.useContactHardeningShadow) {
  74819. shadowGenerator.useContactHardeningShadow = true;
  74820. }
  74821. if (parsedShadowGenerator.filteringQuality) {
  74822. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  74823. }
  74824. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  74825. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  74826. }
  74827. // Backward compat
  74828. else if (parsedShadowGenerator.useVarianceShadowMap) {
  74829. shadowGenerator.useExponentialShadowMap = true;
  74830. }
  74831. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  74832. shadowGenerator.useBlurExponentialShadowMap = true;
  74833. }
  74834. if (parsedShadowGenerator.depthScale) {
  74835. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  74836. }
  74837. if (parsedShadowGenerator.blurScale) {
  74838. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  74839. }
  74840. if (parsedShadowGenerator.blurBoxOffset) {
  74841. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  74842. }
  74843. if (parsedShadowGenerator.useKernelBlur) {
  74844. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  74845. }
  74846. if (parsedShadowGenerator.blurKernel) {
  74847. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  74848. }
  74849. if (parsedShadowGenerator.bias !== undefined) {
  74850. shadowGenerator.bias = parsedShadowGenerator.bias;
  74851. }
  74852. if (parsedShadowGenerator.normalBias !== undefined) {
  74853. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  74854. }
  74855. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  74856. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  74857. }
  74858. if (parsedShadowGenerator.darkness) {
  74859. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  74860. }
  74861. if (parsedShadowGenerator.transparencyShadow) {
  74862. shadowGenerator.setTransparencyShadow(true);
  74863. }
  74864. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  74865. return shadowGenerator;
  74866. };
  74867. /**
  74868. * Shadow generator mode None: no filtering applied.
  74869. */
  74870. ShadowGenerator.FILTER_NONE = 0;
  74871. /**
  74872. * Shadow generator mode ESM: Exponential Shadow Mapping.
  74873. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74874. */
  74875. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  74876. /**
  74877. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  74878. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  74879. */
  74880. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  74881. /**
  74882. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  74883. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74884. */
  74885. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  74886. /**
  74887. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  74888. * edge artifacts on steep falloff.
  74889. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74890. */
  74891. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  74892. /**
  74893. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  74894. * edge artifacts on steep falloff.
  74895. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74896. */
  74897. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  74898. /**
  74899. * Shadow generator mode PCF: Percentage Closer Filtering
  74900. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74901. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  74902. */
  74903. ShadowGenerator.FILTER_PCF = 6;
  74904. /**
  74905. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  74906. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74907. * Contact Hardening
  74908. */
  74909. ShadowGenerator.FILTER_PCSS = 7;
  74910. /**
  74911. * Reserved for PCF and PCSS
  74912. * Highest Quality.
  74913. *
  74914. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  74915. *
  74916. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  74917. */
  74918. ShadowGenerator.QUALITY_HIGH = 0;
  74919. /**
  74920. * Reserved for PCF and PCSS
  74921. * Good tradeoff for quality/perf cross devices
  74922. *
  74923. * Execute PCF on a 3*3 kernel.
  74924. *
  74925. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  74926. */
  74927. ShadowGenerator.QUALITY_MEDIUM = 1;
  74928. /**
  74929. * Reserved for PCF and PCSS
  74930. * The lowest quality but the fastest.
  74931. *
  74932. * Execute PCF on a 1*1 kernel.
  74933. *
  74934. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  74935. */
  74936. ShadowGenerator.QUALITY_LOW = 2;
  74937. return ShadowGenerator;
  74938. }());
  74939. BABYLON.ShadowGenerator = ShadowGenerator;
  74940. })(BABYLON || (BABYLON = {}));
  74941. //# sourceMappingURL=babylon.shadowGenerator.js.map
  74942. var BABYLON;
  74943. (function (BABYLON) {
  74944. // Adds the parser to the scene parsers.
  74945. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  74946. // Shadows
  74947. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  74948. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  74949. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  74950. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  74951. // SG would be available on their associated lights
  74952. }
  74953. }
  74954. });
  74955. /**
  74956. * Defines the shadow generator component responsible to manage any shadow generators
  74957. * in a given scene.
  74958. */
  74959. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  74960. /**
  74961. * Creates a new instance of the component for the given scene
  74962. * @param scene Defines the scene to register the component in
  74963. */
  74964. function ShadowGeneratorSceneComponent(scene) {
  74965. /**
  74966. * The component name helpfull to identify the component in the list of scene components.
  74967. */
  74968. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  74969. this.scene = scene;
  74970. }
  74971. /**
  74972. * Registers the component in a given scene
  74973. */
  74974. ShadowGeneratorSceneComponent.prototype.register = function () {
  74975. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  74976. };
  74977. /**
  74978. * Rebuilds the elements related to this component in case of
  74979. * context lost for instance.
  74980. */
  74981. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  74982. // Nothing To Do Here.
  74983. };
  74984. /**
  74985. * Serializes the component data to the specified json object
  74986. * @param serializationObject The object to serialize to
  74987. */
  74988. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  74989. // Shadows
  74990. serializationObject.shadowGenerators = [];
  74991. var lights = this.scene.lights;
  74992. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  74993. var light = lights_1[_i];
  74994. var shadowGenerator = light.getShadowGenerator();
  74995. if (shadowGenerator) {
  74996. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  74997. }
  74998. }
  74999. };
  75000. /**
  75001. * Adds all the element from the container to the scene
  75002. * @param container the container holding the elements
  75003. */
  75004. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  75005. // Nothing To Do Here. (directly attached to a light)
  75006. };
  75007. /**
  75008. * Removes all the elements in the container from the scene
  75009. * @param container contains the elements to remove
  75010. */
  75011. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  75012. // Nothing To Do Here. (directly attached to a light)
  75013. };
  75014. /**
  75015. * Rebuilds the elements related to this component in case of
  75016. * context lost for instance.
  75017. */
  75018. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  75019. // Nothing To Do Here.
  75020. };
  75021. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  75022. // Shadows
  75023. var scene = this.scene;
  75024. if (this.scene.shadowsEnabled) {
  75025. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  75026. var light = scene.lights[lightIndex];
  75027. var shadowGenerator = light.getShadowGenerator();
  75028. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  75029. var shadowMap = (shadowGenerator.getShadowMap());
  75030. if (scene.textures.indexOf(shadowMap) !== -1) {
  75031. renderTargets.push(shadowMap);
  75032. }
  75033. }
  75034. }
  75035. }
  75036. };
  75037. return ShadowGeneratorSceneComponent;
  75038. }());
  75039. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  75040. })(BABYLON || (BABYLON = {}));
  75041. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  75042. var BABYLON;
  75043. (function (BABYLON) {
  75044. var DefaultLoadingScreen = /** @class */ (function () {
  75045. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  75046. if (_loadingText === void 0) { _loadingText = ""; }
  75047. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  75048. var _this = this;
  75049. this._renderingCanvas = _renderingCanvas;
  75050. this._loadingText = _loadingText;
  75051. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  75052. // Resize
  75053. this._resizeLoadingUI = function () {
  75054. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  75055. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  75056. if (!_this._loadingDiv) {
  75057. return;
  75058. }
  75059. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  75060. _this._loadingDiv.style.left = canvasRect.left + "px";
  75061. _this._loadingDiv.style.top = canvasRect.top + "px";
  75062. _this._loadingDiv.style.width = canvasRect.width + "px";
  75063. _this._loadingDiv.style.height = canvasRect.height + "px";
  75064. };
  75065. }
  75066. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  75067. if (this._loadingDiv) {
  75068. // Do not add a loading screen if there is already one
  75069. return;
  75070. }
  75071. this._loadingDiv = document.createElement("div");
  75072. this._loadingDiv.id = "babylonjsLoadingDiv";
  75073. this._loadingDiv.style.opacity = "0";
  75074. this._loadingDiv.style.transition = "opacity 1.5s ease";
  75075. this._loadingDiv.style.pointerEvents = "none";
  75076. // Loading text
  75077. this._loadingTextDiv = document.createElement("div");
  75078. this._loadingTextDiv.style.position = "absolute";
  75079. this._loadingTextDiv.style.left = "0";
  75080. this._loadingTextDiv.style.top = "50%";
  75081. this._loadingTextDiv.style.marginTop = "80px";
  75082. this._loadingTextDiv.style.width = "100%";
  75083. this._loadingTextDiv.style.height = "20px";
  75084. this._loadingTextDiv.style.fontFamily = "Arial";
  75085. this._loadingTextDiv.style.fontSize = "14px";
  75086. this._loadingTextDiv.style.color = "white";
  75087. this._loadingTextDiv.style.textAlign = "center";
  75088. this._loadingTextDiv.innerHTML = "Loading";
  75089. this._loadingDiv.appendChild(this._loadingTextDiv);
  75090. //set the predefined text
  75091. this._loadingTextDiv.innerHTML = this._loadingText;
  75092. // Generating keyframes
  75093. var style = document.createElement('style');
  75094. style.type = 'text/css';
  75095. 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 }";
  75096. style.innerHTML = keyFrames;
  75097. document.getElementsByTagName('head')[0].appendChild(style);
  75098. // Loading img
  75099. var imgBack = new Image();
  75100. 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";
  75101. imgBack.style.position = "absolute";
  75102. imgBack.style.left = "50%";
  75103. imgBack.style.top = "50%";
  75104. imgBack.style.marginLeft = "-60px";
  75105. imgBack.style.marginTop = "-60px";
  75106. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  75107. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  75108. imgBack.style.transformOrigin = "50% 50%";
  75109. imgBack.style.webkitTransformOrigin = "50% 50%";
  75110. this._loadingDiv.appendChild(imgBack);
  75111. this._resizeLoadingUI();
  75112. window.addEventListener("resize", this._resizeLoadingUI);
  75113. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75114. document.body.appendChild(this._loadingDiv);
  75115. this._loadingDiv.style.opacity = "1";
  75116. };
  75117. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  75118. var _this = this;
  75119. if (!this._loadingDiv) {
  75120. return;
  75121. }
  75122. var onTransitionEnd = function () {
  75123. if (!_this._loadingDiv) {
  75124. return;
  75125. }
  75126. document.body.removeChild(_this._loadingDiv);
  75127. window.removeEventListener("resize", _this._resizeLoadingUI);
  75128. _this._loadingDiv = null;
  75129. };
  75130. this._loadingDiv.style.opacity = "0";
  75131. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  75132. };
  75133. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  75134. set: function (text) {
  75135. this._loadingText = text;
  75136. if (this._loadingTextDiv) {
  75137. this._loadingTextDiv.innerHTML = this._loadingText;
  75138. }
  75139. },
  75140. enumerable: true,
  75141. configurable: true
  75142. });
  75143. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  75144. get: function () {
  75145. return this._loadingDivBackgroundColor;
  75146. },
  75147. set: function (color) {
  75148. this._loadingDivBackgroundColor = color;
  75149. if (!this._loadingDiv) {
  75150. return;
  75151. }
  75152. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75153. },
  75154. enumerable: true,
  75155. configurable: true
  75156. });
  75157. return DefaultLoadingScreen;
  75158. }());
  75159. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  75160. })(BABYLON || (BABYLON = {}));
  75161. //# sourceMappingURL=babylon.loadingScreen.js.map
  75162. var BABYLON;
  75163. (function (BABYLON) {
  75164. var SceneLoaderProgressEvent = /** @class */ (function () {
  75165. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  75166. this.lengthComputable = lengthComputable;
  75167. this.loaded = loaded;
  75168. this.total = total;
  75169. }
  75170. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  75171. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  75172. };
  75173. return SceneLoaderProgressEvent;
  75174. }());
  75175. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  75176. var SceneLoader = /** @class */ (function () {
  75177. function SceneLoader() {
  75178. }
  75179. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  75180. get: function () {
  75181. return 0;
  75182. },
  75183. enumerable: true,
  75184. configurable: true
  75185. });
  75186. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  75187. get: function () {
  75188. return 1;
  75189. },
  75190. enumerable: true,
  75191. configurable: true
  75192. });
  75193. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  75194. get: function () {
  75195. return 2;
  75196. },
  75197. enumerable: true,
  75198. configurable: true
  75199. });
  75200. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  75201. get: function () {
  75202. return 3;
  75203. },
  75204. enumerable: true,
  75205. configurable: true
  75206. });
  75207. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  75208. get: function () {
  75209. return SceneLoader._ForceFullSceneLoadingForIncremental;
  75210. },
  75211. set: function (value) {
  75212. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  75213. },
  75214. enumerable: true,
  75215. configurable: true
  75216. });
  75217. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  75218. get: function () {
  75219. return SceneLoader._ShowLoadingScreen;
  75220. },
  75221. set: function (value) {
  75222. SceneLoader._ShowLoadingScreen = value;
  75223. },
  75224. enumerable: true,
  75225. configurable: true
  75226. });
  75227. Object.defineProperty(SceneLoader, "loggingLevel", {
  75228. get: function () {
  75229. return SceneLoader._loggingLevel;
  75230. },
  75231. set: function (value) {
  75232. SceneLoader._loggingLevel = value;
  75233. },
  75234. enumerable: true,
  75235. configurable: true
  75236. });
  75237. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  75238. get: function () {
  75239. return SceneLoader._CleanBoneMatrixWeights;
  75240. },
  75241. set: function (value) {
  75242. SceneLoader._CleanBoneMatrixWeights = value;
  75243. },
  75244. enumerable: true,
  75245. configurable: true
  75246. });
  75247. SceneLoader._getDefaultPlugin = function () {
  75248. return SceneLoader._registeredPlugins[".babylon"];
  75249. };
  75250. SceneLoader._getPluginForExtension = function (extension) {
  75251. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  75252. if (registeredPlugin) {
  75253. return registeredPlugin;
  75254. }
  75255. 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");
  75256. return SceneLoader._getDefaultPlugin();
  75257. };
  75258. SceneLoader._getPluginForDirectLoad = function (data) {
  75259. for (var extension in SceneLoader._registeredPlugins) {
  75260. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  75261. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  75262. return SceneLoader._registeredPlugins[extension];
  75263. }
  75264. }
  75265. return SceneLoader._getDefaultPlugin();
  75266. };
  75267. SceneLoader._getPluginForFilename = function (sceneFilename) {
  75268. var queryStringPosition = sceneFilename.indexOf("?");
  75269. if (queryStringPosition !== -1) {
  75270. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  75271. }
  75272. var dotPosition = sceneFilename.lastIndexOf(".");
  75273. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  75274. return SceneLoader._getPluginForExtension(extension);
  75275. };
  75276. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  75277. SceneLoader._getDirectLoad = function (sceneFilename) {
  75278. if (sceneFilename.substr(0, 5) === "data:") {
  75279. return sceneFilename.substr(5);
  75280. }
  75281. return null;
  75282. };
  75283. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  75284. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  75285. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  75286. var plugin;
  75287. if (registeredPlugin.plugin.createPlugin) {
  75288. plugin = registeredPlugin.plugin.createPlugin();
  75289. }
  75290. else {
  75291. plugin = registeredPlugin.plugin;
  75292. }
  75293. var useArrayBuffer = registeredPlugin.isBinary;
  75294. var database;
  75295. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  75296. var dataCallback = function (data, responseURL) {
  75297. if (scene.isDisposed) {
  75298. onError("Scene has been disposed");
  75299. return;
  75300. }
  75301. scene.database = database;
  75302. onSuccess(plugin, data, responseURL);
  75303. };
  75304. var request = null;
  75305. var pluginDisposed = false;
  75306. var onDisposeObservable = plugin.onDisposeObservable;
  75307. if (onDisposeObservable) {
  75308. onDisposeObservable.add(function () {
  75309. pluginDisposed = true;
  75310. if (request) {
  75311. request.abort();
  75312. request = null;
  75313. }
  75314. onDispose();
  75315. });
  75316. }
  75317. var manifestChecked = function () {
  75318. if (pluginDisposed) {
  75319. return;
  75320. }
  75321. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  75322. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  75323. } : undefined, database, useArrayBuffer, function (request, exception) {
  75324. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  75325. });
  75326. };
  75327. if (directLoad) {
  75328. dataCallback(directLoad);
  75329. return plugin;
  75330. }
  75331. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  75332. var engine = scene.getEngine();
  75333. var canUseOfflineSupport = engine.enableOfflineSupport;
  75334. if (canUseOfflineSupport) {
  75335. // Also check for exceptions
  75336. var exceptionFound = false;
  75337. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  75338. var regex = _a[_i];
  75339. if (regex.test(fileInfo.url)) {
  75340. exceptionFound = true;
  75341. break;
  75342. }
  75343. }
  75344. canUseOfflineSupport = !exceptionFound;
  75345. }
  75346. if (canUseOfflineSupport) {
  75347. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  75348. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  75349. }
  75350. else {
  75351. manifestChecked();
  75352. }
  75353. }
  75354. // Loading file from disk via input file or drag'n'drop
  75355. else {
  75356. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  75357. if (file) {
  75358. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  75359. }
  75360. else {
  75361. onError("Unable to find file named " + fileInfo.name);
  75362. }
  75363. }
  75364. return plugin;
  75365. };
  75366. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  75367. var url;
  75368. var name;
  75369. if (!sceneFilename) {
  75370. url = rootUrl;
  75371. name = BABYLON.Tools.GetFilename(rootUrl);
  75372. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  75373. }
  75374. else {
  75375. if (sceneFilename.substr(0, 1) === "/") {
  75376. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  75377. return null;
  75378. }
  75379. url = rootUrl + sceneFilename;
  75380. name = sceneFilename;
  75381. }
  75382. ;
  75383. return {
  75384. url: url,
  75385. rootUrl: rootUrl,
  75386. name: name
  75387. };
  75388. };
  75389. // Public functions
  75390. SceneLoader.GetPluginForExtension = function (extension) {
  75391. return SceneLoader._getPluginForExtension(extension).plugin;
  75392. };
  75393. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  75394. return !!SceneLoader._registeredPlugins[extension];
  75395. };
  75396. SceneLoader.RegisterPlugin = function (plugin) {
  75397. if (typeof plugin.extensions === "string") {
  75398. var extension = plugin.extensions;
  75399. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  75400. plugin: plugin,
  75401. isBinary: false
  75402. };
  75403. }
  75404. else {
  75405. var extensions = plugin.extensions;
  75406. Object.keys(extensions).forEach(function (extension) {
  75407. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  75408. plugin: plugin,
  75409. isBinary: extensions[extension].isBinary
  75410. };
  75411. });
  75412. }
  75413. };
  75414. /**
  75415. * Import meshes into a scene
  75416. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75417. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75418. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75419. * @param scene the instance of BABYLON.Scene to append to
  75420. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  75421. * @param onProgress a callback with a progress event for each file being loaded
  75422. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75423. * @param pluginExtension the extension used to determine the plugin
  75424. * @returns The loaded plugin
  75425. */
  75426. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75427. if (sceneFilename === void 0) { sceneFilename = ""; }
  75428. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75429. if (onSuccess === void 0) { onSuccess = null; }
  75430. if (onProgress === void 0) { onProgress = null; }
  75431. if (onError === void 0) { onError = null; }
  75432. if (pluginExtension === void 0) { pluginExtension = null; }
  75433. if (!scene) {
  75434. BABYLON.Tools.Error("No scene available to import mesh to");
  75435. return null;
  75436. }
  75437. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75438. if (!fileInfo) {
  75439. return null;
  75440. }
  75441. var loadingToken = {};
  75442. scene._addPendingData(loadingToken);
  75443. var disposeHandler = function () {
  75444. scene._removePendingData(loadingToken);
  75445. };
  75446. var errorHandler = function (message, exception) {
  75447. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  75448. if (onError) {
  75449. onError(scene, errorMessage, exception);
  75450. }
  75451. else {
  75452. BABYLON.Tools.Error(errorMessage);
  75453. // should the exception be thrown?
  75454. }
  75455. disposeHandler();
  75456. };
  75457. var progressHandler = onProgress ? function (event) {
  75458. try {
  75459. onProgress(event);
  75460. }
  75461. catch (e) {
  75462. errorHandler("Error in onProgress callback", e);
  75463. }
  75464. } : undefined;
  75465. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  75466. scene.importedMeshesFiles.push(fileInfo.url);
  75467. if (onSuccess) {
  75468. try {
  75469. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  75470. }
  75471. catch (e) {
  75472. errorHandler("Error in onSuccess callback", e);
  75473. }
  75474. }
  75475. scene._removePendingData(loadingToken);
  75476. };
  75477. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75478. if (plugin.rewriteRootURL) {
  75479. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  75480. }
  75481. if (plugin.importMesh) {
  75482. var syncedPlugin = plugin;
  75483. var meshes = new Array();
  75484. var particleSystems = new Array();
  75485. var skeletons = new Array();
  75486. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  75487. return;
  75488. }
  75489. scene.loadingPluginName = plugin.name;
  75490. successHandler(meshes, particleSystems, skeletons, []);
  75491. }
  75492. else {
  75493. var asyncedPlugin = plugin;
  75494. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  75495. scene.loadingPluginName = plugin.name;
  75496. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  75497. }).catch(function (error) {
  75498. errorHandler(error.message, error);
  75499. });
  75500. }
  75501. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75502. };
  75503. /**
  75504. * Import meshes into a scene
  75505. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75506. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75507. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75508. * @param scene the instance of BABYLON.Scene to append to
  75509. * @param onProgress a callback with a progress event for each file being loaded
  75510. * @param pluginExtension the extension used to determine the plugin
  75511. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  75512. */
  75513. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75514. if (sceneFilename === void 0) { sceneFilename = ""; }
  75515. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75516. if (onProgress === void 0) { onProgress = null; }
  75517. if (pluginExtension === void 0) { pluginExtension = null; }
  75518. return new Promise(function (resolve, reject) {
  75519. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  75520. resolve({
  75521. meshes: meshes,
  75522. particleSystems: particleSystems,
  75523. skeletons: skeletons,
  75524. animationGroups: animationGroups
  75525. });
  75526. }, onProgress, function (scene, message, exception) {
  75527. reject(exception || new Error(message));
  75528. }, pluginExtension);
  75529. });
  75530. };
  75531. /**
  75532. * Load a scene
  75533. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75534. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75535. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75536. * @param onSuccess a callback with the scene when import succeeds
  75537. * @param onProgress a callback with a progress event for each file being loaded
  75538. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75539. * @param pluginExtension the extension used to determine the plugin
  75540. * @returns The loaded plugin
  75541. */
  75542. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  75543. if (onSuccess === void 0) { onSuccess = null; }
  75544. if (onProgress === void 0) { onProgress = null; }
  75545. if (onError === void 0) { onError = null; }
  75546. if (pluginExtension === void 0) { pluginExtension = null; }
  75547. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  75548. };
  75549. /**
  75550. * Load a scene
  75551. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75552. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75553. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75554. * @param onProgress a callback with a progress event for each file being loaded
  75555. * @param pluginExtension the extension used to determine the plugin
  75556. * @returns The loaded scene
  75557. */
  75558. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  75559. if (onProgress === void 0) { onProgress = null; }
  75560. if (pluginExtension === void 0) { pluginExtension = null; }
  75561. return new Promise(function (resolve, reject) {
  75562. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  75563. resolve(scene);
  75564. }, onProgress, function (scene, message, exception) {
  75565. reject(exception || new Error(message));
  75566. }, pluginExtension);
  75567. });
  75568. };
  75569. /**
  75570. * Append a scene
  75571. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75572. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75573. * @param scene is the instance of BABYLON.Scene to append to
  75574. * @param onSuccess a callback with the scene when import succeeds
  75575. * @param onProgress a callback with a progress event for each file being loaded
  75576. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75577. * @param pluginExtension the extension used to determine the plugin
  75578. * @returns The loaded plugin
  75579. */
  75580. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75581. if (sceneFilename === void 0) { sceneFilename = ""; }
  75582. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75583. if (onSuccess === void 0) { onSuccess = null; }
  75584. if (onProgress === void 0) { onProgress = null; }
  75585. if (onError === void 0) { onError = null; }
  75586. if (pluginExtension === void 0) { pluginExtension = null; }
  75587. if (!scene) {
  75588. BABYLON.Tools.Error("No scene available to append to");
  75589. return null;
  75590. }
  75591. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75592. if (!fileInfo) {
  75593. return null;
  75594. }
  75595. if (SceneLoader.ShowLoadingScreen) {
  75596. scene.getEngine().displayLoadingUI();
  75597. }
  75598. var loadingToken = {};
  75599. scene._addPendingData(loadingToken);
  75600. var disposeHandler = function () {
  75601. scene._removePendingData(loadingToken);
  75602. scene.getEngine().hideLoadingUI();
  75603. };
  75604. var errorHandler = function (message, exception) {
  75605. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  75606. if (onError) {
  75607. onError(scene, errorMessage, exception);
  75608. }
  75609. else {
  75610. BABYLON.Tools.Error(errorMessage);
  75611. // should the exception be thrown?
  75612. }
  75613. disposeHandler();
  75614. };
  75615. var progressHandler = onProgress ? function (event) {
  75616. try {
  75617. onProgress(event);
  75618. }
  75619. catch (e) {
  75620. errorHandler("Error in onProgress callback", e);
  75621. }
  75622. } : undefined;
  75623. var successHandler = function () {
  75624. if (onSuccess) {
  75625. try {
  75626. onSuccess(scene);
  75627. }
  75628. catch (e) {
  75629. errorHandler("Error in onSuccess callback", e);
  75630. }
  75631. }
  75632. scene._removePendingData(loadingToken);
  75633. };
  75634. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75635. if (plugin.load) {
  75636. var syncedPlugin = plugin;
  75637. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  75638. return;
  75639. }
  75640. scene.loadingPluginName = plugin.name;
  75641. successHandler();
  75642. }
  75643. else {
  75644. var asyncedPlugin = plugin;
  75645. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  75646. scene.loadingPluginName = plugin.name;
  75647. successHandler();
  75648. }).catch(function (error) {
  75649. errorHandler(error.message, error);
  75650. });
  75651. }
  75652. if (SceneLoader.ShowLoadingScreen) {
  75653. scene.executeWhenReady(function () {
  75654. scene.getEngine().hideLoadingUI();
  75655. });
  75656. }
  75657. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75658. };
  75659. /**
  75660. * Append a scene
  75661. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75662. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75663. * @param scene is the instance of BABYLON.Scene to append to
  75664. * @param onProgress a callback with a progress event for each file being loaded
  75665. * @param pluginExtension the extension used to determine the plugin
  75666. * @returns The given scene
  75667. */
  75668. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75669. if (sceneFilename === void 0) { sceneFilename = ""; }
  75670. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75671. if (onProgress === void 0) { onProgress = null; }
  75672. if (pluginExtension === void 0) { pluginExtension = null; }
  75673. return new Promise(function (resolve, reject) {
  75674. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  75675. resolve(scene);
  75676. }, onProgress, function (scene, message, exception) {
  75677. reject(exception || new Error(message));
  75678. }, pluginExtension);
  75679. });
  75680. };
  75681. /**
  75682. * Load a scene into an asset container
  75683. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75684. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75685. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  75686. * @param onSuccess a callback with the scene when import succeeds
  75687. * @param onProgress a callback with a progress event for each file being loaded
  75688. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75689. * @param pluginExtension the extension used to determine the plugin
  75690. * @returns The loaded plugin
  75691. */
  75692. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75693. if (sceneFilename === void 0) { sceneFilename = ""; }
  75694. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75695. if (onSuccess === void 0) { onSuccess = null; }
  75696. if (onProgress === void 0) { onProgress = null; }
  75697. if (onError === void 0) { onError = null; }
  75698. if (pluginExtension === void 0) { pluginExtension = null; }
  75699. if (!scene) {
  75700. BABYLON.Tools.Error("No scene available to load asset container to");
  75701. return null;
  75702. }
  75703. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75704. if (!fileInfo) {
  75705. return null;
  75706. }
  75707. var loadingToken = {};
  75708. scene._addPendingData(loadingToken);
  75709. var disposeHandler = function () {
  75710. scene._removePendingData(loadingToken);
  75711. };
  75712. var errorHandler = function (message, exception) {
  75713. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  75714. if (onError) {
  75715. onError(scene, errorMessage, exception);
  75716. }
  75717. else {
  75718. BABYLON.Tools.Error(errorMessage);
  75719. // should the exception be thrown?
  75720. }
  75721. disposeHandler();
  75722. };
  75723. var progressHandler = onProgress ? function (event) {
  75724. try {
  75725. onProgress(event);
  75726. }
  75727. catch (e) {
  75728. errorHandler("Error in onProgress callback", e);
  75729. }
  75730. } : undefined;
  75731. var successHandler = function (assets) {
  75732. if (onSuccess) {
  75733. try {
  75734. onSuccess(assets);
  75735. }
  75736. catch (e) {
  75737. errorHandler("Error in onSuccess callback", e);
  75738. }
  75739. }
  75740. scene._removePendingData(loadingToken);
  75741. };
  75742. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75743. if (plugin.loadAssetContainer) {
  75744. var syncedPlugin = plugin;
  75745. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  75746. if (!assetContainer) {
  75747. return;
  75748. }
  75749. scene.loadingPluginName = plugin.name;
  75750. successHandler(assetContainer);
  75751. }
  75752. else if (plugin.loadAssetContainerAsync) {
  75753. var asyncedPlugin = plugin;
  75754. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  75755. scene.loadingPluginName = plugin.name;
  75756. successHandler(assetContainer);
  75757. }).catch(function (error) {
  75758. errorHandler(error.message, error);
  75759. });
  75760. }
  75761. else {
  75762. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  75763. }
  75764. if (SceneLoader.ShowLoadingScreen) {
  75765. scene.executeWhenReady(function () {
  75766. scene.getEngine().hideLoadingUI();
  75767. });
  75768. }
  75769. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75770. };
  75771. /**
  75772. * Load a scene into an asset container
  75773. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75774. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75775. * @param scene is the instance of BABYLON.Scene to append to
  75776. * @param onProgress a callback with a progress event for each file being loaded
  75777. * @param pluginExtension the extension used to determine the plugin
  75778. * @returns The loaded asset container
  75779. */
  75780. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75781. if (sceneFilename === void 0) { sceneFilename = ""; }
  75782. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75783. if (onProgress === void 0) { onProgress = null; }
  75784. if (pluginExtension === void 0) { pluginExtension = null; }
  75785. return new Promise(function (resolve, reject) {
  75786. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  75787. resolve(assetContainer);
  75788. }, onProgress, function (scene, message, exception) {
  75789. reject(exception || new Error(message));
  75790. }, pluginExtension);
  75791. });
  75792. };
  75793. // Flags
  75794. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  75795. SceneLoader._ShowLoadingScreen = true;
  75796. SceneLoader._CleanBoneMatrixWeights = false;
  75797. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  75798. // Members
  75799. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  75800. SceneLoader._registeredPlugins = {};
  75801. return SceneLoader;
  75802. }());
  75803. BABYLON.SceneLoader = SceneLoader;
  75804. ;
  75805. })(BABYLON || (BABYLON = {}));
  75806. //# sourceMappingURL=babylon.sceneLoader.js.map
  75807. var BABYLON;
  75808. (function (BABYLON) {
  75809. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  75810. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75811. var parsedMaterial = parsedData.materials[index];
  75812. if (parsedMaterial.id === id) {
  75813. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75814. }
  75815. }
  75816. return null;
  75817. };
  75818. var isDescendantOf = function (mesh, names, hierarchyIds) {
  75819. for (var i in names) {
  75820. if (mesh.name === names[i]) {
  75821. hierarchyIds.push(mesh.id);
  75822. return true;
  75823. }
  75824. }
  75825. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  75826. hierarchyIds.push(mesh.id);
  75827. return true;
  75828. }
  75829. return false;
  75830. };
  75831. var logOperation = function (operation, producer) {
  75832. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  75833. };
  75834. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  75835. if (addToScene === void 0) { addToScene = false; }
  75836. var container = new BABYLON.AssetContainer(scene);
  75837. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75838. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75839. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75840. // and avoid problems with multiple concurrent .babylon loads.
  75841. var log = "importScene has failed JSON parse";
  75842. try {
  75843. var parsedData = JSON.parse(data);
  75844. log = "";
  75845. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  75846. var index;
  75847. var cache;
  75848. // Lights
  75849. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  75850. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  75851. var parsedLight = parsedData.lights[index];
  75852. var light = BABYLON.Light.Parse(parsedLight, scene);
  75853. if (light) {
  75854. container.lights.push(light);
  75855. log += (index === 0 ? "\n\tLights:" : "");
  75856. log += "\n\t\t" + light.toString(fullDetails);
  75857. }
  75858. }
  75859. }
  75860. // Animations
  75861. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  75862. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  75863. var parsedAnimation = parsedData.animations[index];
  75864. var animation = BABYLON.Animation.Parse(parsedAnimation);
  75865. scene.animations.push(animation);
  75866. container.animations.push(animation);
  75867. log += (index === 0 ? "\n\tAnimations:" : "");
  75868. log += "\n\t\t" + animation.toString(fullDetails);
  75869. }
  75870. }
  75871. // Materials
  75872. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  75873. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75874. var parsedMaterial = parsedData.materials[index];
  75875. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75876. container.materials.push(mat);
  75877. log += (index === 0 ? "\n\tMaterials:" : "");
  75878. log += "\n\t\t" + mat.toString(fullDetails);
  75879. }
  75880. }
  75881. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75882. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  75883. var parsedMultiMaterial = parsedData.multiMaterials[index];
  75884. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75885. container.multiMaterials.push(mmat);
  75886. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  75887. log += "\n\t\t" + mmat.toString(fullDetails);
  75888. }
  75889. }
  75890. // Morph targets
  75891. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75892. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75893. var managerData = _a[_i];
  75894. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  75895. }
  75896. }
  75897. // Skeletons
  75898. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75899. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  75900. var parsedSkeleton = parsedData.skeletons[index];
  75901. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75902. container.skeletons.push(skeleton);
  75903. log += (index === 0 ? "\n\tSkeletons:" : "");
  75904. log += "\n\t\t" + skeleton.toString(fullDetails);
  75905. }
  75906. }
  75907. // Geometries
  75908. var geometries = parsedData.geometries;
  75909. if (geometries !== undefined && geometries !== null) {
  75910. var addedGeometry = new Array();
  75911. // Boxes
  75912. var boxes = geometries.boxes;
  75913. if (boxes !== undefined && boxes !== null) {
  75914. for (index = 0, cache = boxes.length; index < cache; index++) {
  75915. var parsedBox = boxes[index];
  75916. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  75917. }
  75918. }
  75919. // Spheres
  75920. var spheres = geometries.spheres;
  75921. if (spheres !== undefined && spheres !== null) {
  75922. for (index = 0, cache = spheres.length; index < cache; index++) {
  75923. var parsedSphere = spheres[index];
  75924. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  75925. }
  75926. }
  75927. // Cylinders
  75928. var cylinders = geometries.cylinders;
  75929. if (cylinders !== undefined && cylinders !== null) {
  75930. for (index = 0, cache = cylinders.length; index < cache; index++) {
  75931. var parsedCylinder = cylinders[index];
  75932. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  75933. }
  75934. }
  75935. // Toruses
  75936. var toruses = geometries.toruses;
  75937. if (toruses !== undefined && toruses !== null) {
  75938. for (index = 0, cache = toruses.length; index < cache; index++) {
  75939. var parsedTorus = toruses[index];
  75940. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  75941. }
  75942. }
  75943. // Grounds
  75944. var grounds = geometries.grounds;
  75945. if (grounds !== undefined && grounds !== null) {
  75946. for (index = 0, cache = grounds.length; index < cache; index++) {
  75947. var parsedGround = grounds[index];
  75948. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  75949. }
  75950. }
  75951. // Planes
  75952. var planes = geometries.planes;
  75953. if (planes !== undefined && planes !== null) {
  75954. for (index = 0, cache = planes.length; index < cache; index++) {
  75955. var parsedPlane = planes[index];
  75956. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  75957. }
  75958. }
  75959. // TorusKnots
  75960. var torusKnots = geometries.torusKnots;
  75961. if (torusKnots !== undefined && torusKnots !== null) {
  75962. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  75963. var parsedTorusKnot = torusKnots[index];
  75964. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  75965. }
  75966. }
  75967. // VertexData
  75968. var vertexData = geometries.vertexData;
  75969. if (vertexData !== undefined && vertexData !== null) {
  75970. for (index = 0, cache = vertexData.length; index < cache; index++) {
  75971. var parsedVertexData = vertexData[index];
  75972. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  75973. }
  75974. }
  75975. addedGeometry.forEach(function (g) {
  75976. if (g) {
  75977. container.geometries.push(g);
  75978. }
  75979. });
  75980. }
  75981. // Transform nodes
  75982. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  75983. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  75984. var parsedTransformNode = parsedData.transformNodes[index];
  75985. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  75986. container.transformNodes.push(node);
  75987. }
  75988. }
  75989. // Meshes
  75990. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  75991. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  75992. var parsedMesh = parsedData.meshes[index];
  75993. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  75994. container.meshes.push(mesh);
  75995. log += (index === 0 ? "\n\tMeshes:" : "");
  75996. log += "\n\t\t" + mesh.toString(fullDetails);
  75997. }
  75998. }
  75999. // Cameras
  76000. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  76001. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  76002. var parsedCamera = parsedData.cameras[index];
  76003. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  76004. container.cameras.push(camera);
  76005. log += (index === 0 ? "\n\tCameras:" : "");
  76006. log += "\n\t\t" + camera.toString(fullDetails);
  76007. }
  76008. }
  76009. // Animation Groups
  76010. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  76011. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  76012. var parsedAnimationGroup = parsedData.animationGroups[index];
  76013. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  76014. container.animationGroups.push(animationGroup);
  76015. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  76016. log += "\n\t\t" + animationGroup.toString(fullDetails);
  76017. }
  76018. }
  76019. // Browsing all the graph to connect the dots
  76020. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  76021. var camera = scene.cameras[index];
  76022. if (camera._waitingParentId) {
  76023. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  76024. camera._waitingParentId = null;
  76025. }
  76026. }
  76027. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76028. var light_1 = scene.lights[index];
  76029. if (light_1 && light_1._waitingParentId) {
  76030. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  76031. light_1._waitingParentId = null;
  76032. }
  76033. }
  76034. // Connect parents & children and parse actions
  76035. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  76036. var transformNode = scene.transformNodes[index];
  76037. if (transformNode._waitingParentId) {
  76038. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  76039. transformNode._waitingParentId = null;
  76040. }
  76041. }
  76042. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76043. var mesh = scene.meshes[index];
  76044. if (mesh._waitingParentId) {
  76045. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  76046. mesh._waitingParentId = null;
  76047. }
  76048. }
  76049. // freeze world matrix application
  76050. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76051. var currentMesh = scene.meshes[index];
  76052. if (currentMesh._waitingFreezeWorldMatrix) {
  76053. currentMesh.freezeWorldMatrix();
  76054. currentMesh._waitingFreezeWorldMatrix = null;
  76055. }
  76056. else {
  76057. currentMesh.computeWorldMatrix(true);
  76058. }
  76059. }
  76060. // Lights exclusions / inclusions
  76061. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76062. var light_2 = scene.lights[index];
  76063. // Excluded check
  76064. if (light_2._excludedMeshesIds.length > 0) {
  76065. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  76066. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  76067. if (excludedMesh) {
  76068. light_2.excludedMeshes.push(excludedMesh);
  76069. }
  76070. }
  76071. light_2._excludedMeshesIds = [];
  76072. }
  76073. // Included check
  76074. if (light_2._includedOnlyMeshesIds.length > 0) {
  76075. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  76076. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  76077. if (includedOnlyMesh) {
  76078. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  76079. }
  76080. }
  76081. light_2._includedOnlyMeshesIds = [];
  76082. }
  76083. }
  76084. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  76085. // Actions (scene) Done last as it can access other objects.
  76086. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76087. var mesh = scene.meshes[index];
  76088. if (mesh._waitingActions) {
  76089. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  76090. mesh._waitingActions = null;
  76091. }
  76092. }
  76093. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  76094. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  76095. }
  76096. if (!addToScene) {
  76097. container.removeAllFromScene();
  76098. }
  76099. }
  76100. catch (err) {
  76101. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  76102. if (onError) {
  76103. onError(msg, err);
  76104. }
  76105. else {
  76106. BABYLON.Tools.Log(msg);
  76107. throw err;
  76108. }
  76109. }
  76110. finally {
  76111. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76112. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76113. }
  76114. }
  76115. return container;
  76116. };
  76117. BABYLON.SceneLoader.RegisterPlugin({
  76118. name: "babylon.js",
  76119. extensions: ".babylon",
  76120. canDirectLoad: function (data) {
  76121. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  76122. return true;
  76123. }
  76124. return false;
  76125. },
  76126. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  76127. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76128. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76129. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76130. // and avoid problems with multiple concurrent .babylon loads.
  76131. var log = "importMesh has failed JSON parse";
  76132. try {
  76133. var parsedData = JSON.parse(data);
  76134. log = "";
  76135. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  76136. if (!meshesNames) {
  76137. meshesNames = null;
  76138. }
  76139. else if (!Array.isArray(meshesNames)) {
  76140. meshesNames = [meshesNames];
  76141. }
  76142. var hierarchyIds = new Array();
  76143. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76144. var loadedSkeletonsIds = [];
  76145. var loadedMaterialsIds = [];
  76146. var index;
  76147. var cache;
  76148. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76149. var parsedMesh = parsedData.meshes[index];
  76150. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  76151. if (meshesNames !== null) {
  76152. // Remove found mesh name from list.
  76153. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  76154. }
  76155. //Geometry?
  76156. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  76157. //does the file contain geometries?
  76158. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  76159. //find the correct geometry and add it to the scene
  76160. var found = false;
  76161. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  76162. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  76163. return;
  76164. }
  76165. else {
  76166. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  76167. if (parsedGeometryData.id === parsedMesh.geometryId) {
  76168. switch (geometryType) {
  76169. case "boxes":
  76170. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  76171. break;
  76172. case "spheres":
  76173. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  76174. break;
  76175. case "cylinders":
  76176. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  76177. break;
  76178. case "toruses":
  76179. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  76180. break;
  76181. case "grounds":
  76182. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  76183. break;
  76184. case "planes":
  76185. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  76186. break;
  76187. case "torusKnots":
  76188. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  76189. break;
  76190. case "vertexData":
  76191. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  76192. break;
  76193. }
  76194. found = true;
  76195. }
  76196. });
  76197. }
  76198. });
  76199. if (found === false) {
  76200. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  76201. }
  76202. }
  76203. }
  76204. // Material ?
  76205. if (parsedMesh.materialId) {
  76206. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  76207. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  76208. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  76209. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  76210. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  76211. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  76212. var subMatId = parsedMultiMaterial.materials[matIndex];
  76213. loadedMaterialsIds.push(subMatId);
  76214. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  76215. if (mat) {
  76216. log += "\n\tMaterial " + mat.toString(fullDetails);
  76217. }
  76218. }
  76219. loadedMaterialsIds.push(parsedMultiMaterial.id);
  76220. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  76221. if (mmat) {
  76222. materialFound = true;
  76223. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  76224. }
  76225. break;
  76226. }
  76227. }
  76228. }
  76229. if (materialFound === false) {
  76230. loadedMaterialsIds.push(parsedMesh.materialId);
  76231. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  76232. if (!mat) {
  76233. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  76234. }
  76235. else {
  76236. log += "\n\tMaterial " + mat.toString(fullDetails);
  76237. }
  76238. }
  76239. }
  76240. // Skeleton ?
  76241. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  76242. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  76243. if (skeletonAlreadyLoaded === false) {
  76244. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  76245. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  76246. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  76247. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  76248. skeletons.push(skeleton);
  76249. loadedSkeletonsIds.push(parsedSkeleton.id);
  76250. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  76251. }
  76252. }
  76253. }
  76254. }
  76255. // Morph targets ?
  76256. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  76257. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  76258. var managerData = _a[_i];
  76259. BABYLON.MorphTargetManager.Parse(managerData, scene);
  76260. }
  76261. }
  76262. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76263. meshes.push(mesh);
  76264. log += "\n\tMesh " + mesh.toString(fullDetails);
  76265. }
  76266. }
  76267. // Connecting parents
  76268. var currentMesh;
  76269. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76270. currentMesh = scene.meshes[index];
  76271. if (currentMesh._waitingParentId) {
  76272. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  76273. currentMesh._waitingParentId = null;
  76274. }
  76275. }
  76276. // freeze and compute world matrix application
  76277. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76278. currentMesh = scene.meshes[index];
  76279. if (currentMesh._waitingFreezeWorldMatrix) {
  76280. currentMesh.freezeWorldMatrix();
  76281. currentMesh._waitingFreezeWorldMatrix = null;
  76282. }
  76283. else {
  76284. currentMesh.computeWorldMatrix(true);
  76285. }
  76286. }
  76287. }
  76288. // Particles
  76289. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  76290. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  76291. if (parser) {
  76292. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  76293. var parsedParticleSystem = parsedData.particleSystems[index];
  76294. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  76295. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  76296. }
  76297. }
  76298. }
  76299. }
  76300. return true;
  76301. }
  76302. catch (err) {
  76303. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  76304. if (onError) {
  76305. onError(msg, err);
  76306. }
  76307. else {
  76308. BABYLON.Tools.Log(msg);
  76309. throw err;
  76310. }
  76311. }
  76312. finally {
  76313. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76314. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76315. }
  76316. }
  76317. return false;
  76318. },
  76319. load: function (scene, data, rootUrl, onError) {
  76320. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76321. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76322. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76323. // and avoid problems with multiple concurrent .babylon loads.
  76324. var log = "importScene has failed JSON parse";
  76325. try {
  76326. var parsedData = JSON.parse(data);
  76327. log = "";
  76328. // Scene
  76329. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  76330. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  76331. }
  76332. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  76333. scene.autoClear = parsedData.autoClear;
  76334. }
  76335. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  76336. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  76337. }
  76338. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  76339. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  76340. }
  76341. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  76342. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  76343. }
  76344. // Fog
  76345. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  76346. scene.fogMode = parsedData.fogMode;
  76347. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  76348. scene.fogStart = parsedData.fogStart;
  76349. scene.fogEnd = parsedData.fogEnd;
  76350. scene.fogDensity = parsedData.fogDensity;
  76351. log += "\tFog mode for scene: ";
  76352. switch (scene.fogMode) {
  76353. // getters not compiling, so using hardcoded
  76354. case 1:
  76355. log += "exp\n";
  76356. break;
  76357. case 2:
  76358. log += "exp2\n";
  76359. break;
  76360. case 3:
  76361. log += "linear\n";
  76362. break;
  76363. }
  76364. }
  76365. //Physics
  76366. if (parsedData.physicsEnabled) {
  76367. var physicsPlugin;
  76368. if (parsedData.physicsEngine === "cannon") {
  76369. physicsPlugin = new BABYLON.CannonJSPlugin();
  76370. }
  76371. else if (parsedData.physicsEngine === "oimo") {
  76372. physicsPlugin = new BABYLON.OimoJSPlugin();
  76373. }
  76374. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  76375. //else - default engine, which is currently oimo
  76376. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  76377. scene.enablePhysics(physicsGravity, physicsPlugin);
  76378. }
  76379. // Metadata
  76380. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  76381. scene.metadata = parsedData.metadata;
  76382. }
  76383. //collisions, if defined. otherwise, default is true
  76384. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  76385. scene.collisionsEnabled = parsedData.collisionsEnabled;
  76386. }
  76387. scene.workerCollisions = !!parsedData.workerCollisions;
  76388. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  76389. if (!container) {
  76390. return false;
  76391. }
  76392. if (parsedData.autoAnimate) {
  76393. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  76394. }
  76395. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  76396. scene.setActiveCameraByID(parsedData.activeCameraID);
  76397. }
  76398. // Environment texture
  76399. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  76400. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  76401. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  76402. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  76403. if (parsedData.environmentTextureRotationY) {
  76404. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  76405. }
  76406. scene.environmentTexture = hdrTexture;
  76407. }
  76408. else {
  76409. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  76410. if (parsedData.environmentTextureRotationY) {
  76411. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  76412. }
  76413. scene.environmentTexture = cubeTexture;
  76414. }
  76415. if (parsedData.createDefaultSkybox === true) {
  76416. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  76417. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  76418. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  76419. }
  76420. }
  76421. // Finish
  76422. return true;
  76423. }
  76424. catch (err) {
  76425. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  76426. if (onError) {
  76427. onError(msg, err);
  76428. }
  76429. else {
  76430. BABYLON.Tools.Log(msg);
  76431. throw err;
  76432. }
  76433. }
  76434. finally {
  76435. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76436. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76437. }
  76438. }
  76439. return false;
  76440. },
  76441. loadAssetContainer: function (scene, data, rootUrl, onError) {
  76442. var container = loadAssetContainer(scene, data, rootUrl, onError);
  76443. return container;
  76444. }
  76445. });
  76446. })(BABYLON || (BABYLON = {}));
  76447. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  76448. var BABYLON;
  76449. (function (BABYLON) {
  76450. /**
  76451. * Class used to help managing file picking and drag'n'drop
  76452. */
  76453. var FilesInput = /** @class */ (function () {
  76454. /**
  76455. * Creates a new FilesInput
  76456. * @param engine defines the rendering engine
  76457. * @param scene defines the hosting scene
  76458. * @param sceneLoadedCallback callback called when scene is loaded
  76459. * @param progressCallback callback called to track progress
  76460. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  76461. * @param textureLoadingCallback callback called when a texture is loading
  76462. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  76463. * @param onReloadCallback callback called when a reload is requested
  76464. * @param errorCallback callback call if an error occurs
  76465. */
  76466. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  76467. /**
  76468. * Callback called when a file is processed
  76469. */
  76470. this.onProcessFileCallback = function () { return true; };
  76471. this._engine = engine;
  76472. this._currentScene = scene;
  76473. this._sceneLoadedCallback = sceneLoadedCallback;
  76474. this._progressCallback = progressCallback;
  76475. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  76476. this._textureLoadingCallback = textureLoadingCallback;
  76477. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  76478. this._onReloadCallback = onReloadCallback;
  76479. this._errorCallback = errorCallback;
  76480. }
  76481. /**
  76482. * Calls this function to listen to drag'n'drop events on a specific DOM element
  76483. * @param elementToMonitor defines the DOM element to track
  76484. */
  76485. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  76486. var _this = this;
  76487. if (elementToMonitor) {
  76488. this._elementToMonitor = elementToMonitor;
  76489. this._dragEnterHandler = function (e) { _this.drag(e); };
  76490. this._dragOverHandler = function (e) { _this.drag(e); };
  76491. this._dropHandler = function (e) { _this.drop(e); };
  76492. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  76493. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  76494. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  76495. }
  76496. };
  76497. /**
  76498. * Release all associated resources
  76499. */
  76500. FilesInput.prototype.dispose = function () {
  76501. if (!this._elementToMonitor) {
  76502. return;
  76503. }
  76504. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  76505. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  76506. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  76507. };
  76508. FilesInput.prototype.renderFunction = function () {
  76509. if (this._additionalRenderLoopLogicCallback) {
  76510. this._additionalRenderLoopLogicCallback();
  76511. }
  76512. if (this._currentScene) {
  76513. if (this._textureLoadingCallback) {
  76514. var remaining = this._currentScene.getWaitingItemsCount();
  76515. if (remaining > 0) {
  76516. this._textureLoadingCallback(remaining);
  76517. }
  76518. }
  76519. this._currentScene.render();
  76520. }
  76521. };
  76522. FilesInput.prototype.drag = function (e) {
  76523. e.stopPropagation();
  76524. e.preventDefault();
  76525. };
  76526. FilesInput.prototype.drop = function (eventDrop) {
  76527. eventDrop.stopPropagation();
  76528. eventDrop.preventDefault();
  76529. this.loadFiles(eventDrop);
  76530. };
  76531. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  76532. var _this = this;
  76533. var reader = folder.createReader();
  76534. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  76535. reader.readEntries(function (entries) {
  76536. remaining.count += entries.length;
  76537. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  76538. var entry = entries_1[_i];
  76539. if (entry.isFile) {
  76540. entry.file(function (file) {
  76541. file.correctName = relativePath + file.name;
  76542. files.push(file);
  76543. if (--remaining.count === 0) {
  76544. callback();
  76545. }
  76546. });
  76547. }
  76548. else if (entry.isDirectory) {
  76549. _this._traverseFolder(entry, files, remaining, callback);
  76550. }
  76551. }
  76552. if (--remaining.count) {
  76553. callback();
  76554. }
  76555. });
  76556. };
  76557. FilesInput.prototype._processFiles = function (files) {
  76558. for (var i = 0; i < files.length; i++) {
  76559. var name = files[i].correctName.toLowerCase();
  76560. var extension = name.split('.').pop();
  76561. if (!this.onProcessFileCallback(files[i], name, extension)) {
  76562. continue;
  76563. }
  76564. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  76565. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  76566. this._sceneFileToLoad = files[i];
  76567. }
  76568. FilesInput.FilesToLoad[name] = files[i];
  76569. }
  76570. };
  76571. /**
  76572. * Load files from a drop event
  76573. * @param event defines the drop event to use as source
  76574. */
  76575. FilesInput.prototype.loadFiles = function (event) {
  76576. var _this = this;
  76577. // Handling data transfer via drag'n'drop
  76578. if (event && event.dataTransfer && event.dataTransfer.files) {
  76579. this._filesToLoad = event.dataTransfer.files;
  76580. }
  76581. // Handling files from input files
  76582. if (event && event.target && event.target.files) {
  76583. this._filesToLoad = event.target.files;
  76584. }
  76585. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  76586. return;
  76587. }
  76588. if (this._startingProcessingFilesCallback) {
  76589. this._startingProcessingFilesCallback(this._filesToLoad);
  76590. }
  76591. if (this._filesToLoad && this._filesToLoad.length > 0) {
  76592. var files_1 = new Array();
  76593. var folders = [];
  76594. var items = event.dataTransfer ? event.dataTransfer.items : null;
  76595. for (var i = 0; i < this._filesToLoad.length; i++) {
  76596. var fileToLoad = this._filesToLoad[i];
  76597. var name_1 = fileToLoad.name.toLowerCase();
  76598. var entry = void 0;
  76599. fileToLoad.correctName = name_1;
  76600. if (items) {
  76601. var item = items[i];
  76602. if (item.getAsEntry) {
  76603. entry = item.getAsEntry();
  76604. }
  76605. else if (item.webkitGetAsEntry) {
  76606. entry = item.webkitGetAsEntry();
  76607. }
  76608. }
  76609. if (!entry) {
  76610. files_1.push(fileToLoad);
  76611. }
  76612. else {
  76613. if (entry.isDirectory) {
  76614. folders.push(entry);
  76615. }
  76616. else {
  76617. files_1.push(fileToLoad);
  76618. }
  76619. }
  76620. }
  76621. if (folders.length === 0) {
  76622. this._processFiles(files_1);
  76623. this._processReload();
  76624. }
  76625. else {
  76626. var remaining = { count: folders.length };
  76627. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  76628. var folder = folders_1[_i];
  76629. this._traverseFolder(folder, files_1, remaining, function () {
  76630. _this._processFiles(files_1);
  76631. if (remaining.count === 0) {
  76632. _this._processReload();
  76633. }
  76634. });
  76635. }
  76636. }
  76637. }
  76638. };
  76639. FilesInput.prototype._processReload = function () {
  76640. if (this._onReloadCallback) {
  76641. this._onReloadCallback(this._sceneFileToLoad);
  76642. }
  76643. else {
  76644. this.reload();
  76645. }
  76646. };
  76647. /**
  76648. * Reload the current scene from the loaded files
  76649. */
  76650. FilesInput.prototype.reload = function () {
  76651. var _this = this;
  76652. // If a scene file has been provided
  76653. if (this._sceneFileToLoad) {
  76654. if (this._currentScene) {
  76655. if (BABYLON.Tools.errorsCount > 0) {
  76656. BABYLON.Tools.ClearLogCache();
  76657. }
  76658. this._engine.stopRenderLoop();
  76659. }
  76660. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  76661. if (_this._progressCallback) {
  76662. _this._progressCallback(progress);
  76663. }
  76664. }).then(function (scene) {
  76665. if (_this._currentScene) {
  76666. _this._currentScene.dispose();
  76667. }
  76668. _this._currentScene = scene;
  76669. if (_this._sceneLoadedCallback) {
  76670. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  76671. }
  76672. // Wait for textures and shaders to be ready
  76673. _this._currentScene.executeWhenReady(function () {
  76674. _this._engine.runRenderLoop(function () {
  76675. _this.renderFunction();
  76676. });
  76677. });
  76678. }).catch(function (error) {
  76679. if (_this._errorCallback) {
  76680. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  76681. }
  76682. });
  76683. }
  76684. else {
  76685. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  76686. }
  76687. };
  76688. /**
  76689. * List of files ready to be loaded
  76690. */
  76691. FilesInput.FilesToLoad = {};
  76692. return FilesInput;
  76693. }());
  76694. BABYLON.FilesInput = FilesInput;
  76695. })(BABYLON || (BABYLON = {}));
  76696. //# sourceMappingURL=babylon.filesInput.js.map
  76697. var BABYLON;
  76698. (function (BABYLON) {
  76699. /**
  76700. * Class used to store custom tags
  76701. */
  76702. var Tags = /** @class */ (function () {
  76703. function Tags() {
  76704. }
  76705. /**
  76706. * Adds support for tags on the given object
  76707. * @param obj defines the object to use
  76708. */
  76709. Tags.EnableFor = function (obj) {
  76710. obj._tags = obj._tags || {};
  76711. obj.hasTags = function () {
  76712. return Tags.HasTags(obj);
  76713. };
  76714. obj.addTags = function (tagsString) {
  76715. return Tags.AddTagsTo(obj, tagsString);
  76716. };
  76717. obj.removeTags = function (tagsString) {
  76718. return Tags.RemoveTagsFrom(obj, tagsString);
  76719. };
  76720. obj.matchesTagsQuery = function (tagsQuery) {
  76721. return Tags.MatchesQuery(obj, tagsQuery);
  76722. };
  76723. };
  76724. /**
  76725. * Removes tags support
  76726. * @param obj defines the object to use
  76727. */
  76728. Tags.DisableFor = function (obj) {
  76729. delete obj._tags;
  76730. delete obj.hasTags;
  76731. delete obj.addTags;
  76732. delete obj.removeTags;
  76733. delete obj.matchesTagsQuery;
  76734. };
  76735. /**
  76736. * Gets a boolean indicating if the given object has tags
  76737. * @param obj defines the object to use
  76738. * @returns a boolean
  76739. */
  76740. Tags.HasTags = function (obj) {
  76741. if (!obj._tags) {
  76742. return false;
  76743. }
  76744. return !BABYLON.Tools.IsEmpty(obj._tags);
  76745. };
  76746. /**
  76747. * Gets the tags available on a given object
  76748. * @param obj defines the object to use
  76749. * @param asString defines if the tags must be returned as a string instead of an array of strings
  76750. * @returns the tags
  76751. */
  76752. Tags.GetTags = function (obj, asString) {
  76753. if (asString === void 0) { asString = true; }
  76754. if (!obj._tags) {
  76755. return null;
  76756. }
  76757. if (asString) {
  76758. var tagsArray = [];
  76759. for (var tag in obj._tags) {
  76760. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  76761. tagsArray.push(tag);
  76762. }
  76763. }
  76764. return tagsArray.join(" ");
  76765. }
  76766. else {
  76767. return obj._tags;
  76768. }
  76769. };
  76770. /**
  76771. * Adds tags to an object
  76772. * @param obj defines the object to use
  76773. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  76774. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  76775. */
  76776. Tags.AddTagsTo = function (obj, tagsString) {
  76777. if (!tagsString) {
  76778. return;
  76779. }
  76780. if (typeof tagsString !== "string") {
  76781. return;
  76782. }
  76783. var tags = tagsString.split(" ");
  76784. tags.forEach(function (tag, index, array) {
  76785. Tags._AddTagTo(obj, tag);
  76786. });
  76787. };
  76788. /**
  76789. * @hidden
  76790. */
  76791. Tags._AddTagTo = function (obj, tag) {
  76792. tag = tag.trim();
  76793. if (tag === "" || tag === "true" || tag === "false") {
  76794. return;
  76795. }
  76796. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  76797. return;
  76798. }
  76799. Tags.EnableFor(obj);
  76800. obj._tags[tag] = true;
  76801. };
  76802. /**
  76803. * Removes specific tags from a specific object
  76804. * @param obj defines the object to use
  76805. * @param tagsString defines the tags to remove
  76806. */
  76807. Tags.RemoveTagsFrom = function (obj, tagsString) {
  76808. if (!Tags.HasTags(obj)) {
  76809. return;
  76810. }
  76811. var tags = tagsString.split(" ");
  76812. for (var t in tags) {
  76813. Tags._RemoveTagFrom(obj, tags[t]);
  76814. }
  76815. };
  76816. /**
  76817. * @hidden
  76818. */
  76819. Tags._RemoveTagFrom = function (obj, tag) {
  76820. delete obj._tags[tag];
  76821. };
  76822. /**
  76823. * Defines if tags hosted on an object match a given query
  76824. * @param obj defines the object to use
  76825. * @param tagsQuery defines the tag query
  76826. * @returns a boolean
  76827. */
  76828. Tags.MatchesQuery = function (obj, tagsQuery) {
  76829. if (tagsQuery === undefined) {
  76830. return true;
  76831. }
  76832. if (tagsQuery === "") {
  76833. return Tags.HasTags(obj);
  76834. }
  76835. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  76836. };
  76837. return Tags;
  76838. }());
  76839. BABYLON.Tags = Tags;
  76840. })(BABYLON || (BABYLON = {}));
  76841. //# sourceMappingURL=babylon.tags.js.map
  76842. var BABYLON;
  76843. (function (BABYLON) {
  76844. /**
  76845. * Class used to evalaute queries containing `and` and `or` operators
  76846. */
  76847. var AndOrNotEvaluator = /** @class */ (function () {
  76848. function AndOrNotEvaluator() {
  76849. }
  76850. /**
  76851. * Evaluate a query
  76852. * @param query defines the query to evaluate
  76853. * @param evaluateCallback defines the callback used to filter result
  76854. * @returns true if the query matches
  76855. */
  76856. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  76857. if (!query.match(/\([^\(\)]*\)/g)) {
  76858. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  76859. }
  76860. else {
  76861. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  76862. // remove parenthesis
  76863. r = r.slice(1, r.length - 1);
  76864. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  76865. });
  76866. }
  76867. if (query === "true") {
  76868. return true;
  76869. }
  76870. if (query === "false") {
  76871. return false;
  76872. }
  76873. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  76874. };
  76875. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  76876. evaluateCallback = evaluateCallback || (function (r) {
  76877. return r === "true" ? true : false;
  76878. });
  76879. var result;
  76880. var or = parenthesisContent.split("||");
  76881. for (var i in or) {
  76882. if (or.hasOwnProperty(i)) {
  76883. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  76884. var and = ori.split("&&");
  76885. if (and.length > 1) {
  76886. for (var j = 0; j < and.length; ++j) {
  76887. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  76888. if (andj !== "true" && andj !== "false") {
  76889. if (andj[0] === "!") {
  76890. result = !evaluateCallback(andj.substring(1));
  76891. }
  76892. else {
  76893. result = evaluateCallback(andj);
  76894. }
  76895. }
  76896. else {
  76897. result = andj === "true" ? true : false;
  76898. }
  76899. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  76900. ori = "false";
  76901. break;
  76902. }
  76903. }
  76904. }
  76905. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  76906. result = true;
  76907. break;
  76908. }
  76909. // result equals false (or undefined)
  76910. if (ori !== "true" && ori !== "false") {
  76911. if (ori[0] === "!") {
  76912. result = !evaluateCallback(ori.substring(1));
  76913. }
  76914. else {
  76915. result = evaluateCallback(ori);
  76916. }
  76917. }
  76918. else {
  76919. result = ori === "true" ? true : false;
  76920. }
  76921. }
  76922. }
  76923. // the whole parenthesis scope is replaced by 'true' or 'false'
  76924. return result ? "true" : "false";
  76925. };
  76926. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  76927. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  76928. // remove whitespaces
  76929. r = r.replace(/[\s]/g, function () { return ""; });
  76930. return r.length % 2 ? "!" : "";
  76931. });
  76932. booleanString = booleanString.trim();
  76933. if (booleanString === "!true") {
  76934. booleanString = "false";
  76935. }
  76936. else if (booleanString === "!false") {
  76937. booleanString = "true";
  76938. }
  76939. return booleanString;
  76940. };
  76941. return AndOrNotEvaluator;
  76942. }());
  76943. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  76944. })(BABYLON || (BABYLON = {}));
  76945. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  76946. var BABYLON;
  76947. (function (BABYLON) {
  76948. /**
  76949. * Class used to enable access to IndexedDB
  76950. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  76951. */
  76952. var Database = /** @class */ (function () {
  76953. /**
  76954. * Creates a new Database
  76955. * @param urlToScene defines the url to load the scene
  76956. * @param callbackManifestChecked defines the callback to use when manifest is checked
  76957. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  76958. */
  76959. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  76960. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  76961. var _this = this;
  76962. // Handling various flavors of prefixed version of IndexedDB
  76963. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  76964. this.callbackManifestChecked = callbackManifestChecked;
  76965. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  76966. this.db = null;
  76967. this._enableSceneOffline = false;
  76968. this._enableTexturesOffline = false;
  76969. this.manifestVersionFound = 0;
  76970. this.mustUpdateRessources = false;
  76971. this.hasReachedQuota = false;
  76972. if (!Database.IDBStorageEnabled) {
  76973. this.callbackManifestChecked(true);
  76974. }
  76975. else {
  76976. if (disableManifestCheck) {
  76977. this._enableSceneOffline = true;
  76978. this._enableTexturesOffline = true;
  76979. this.manifestVersionFound = 1;
  76980. BABYLON.Tools.SetImmediate(function () {
  76981. _this.callbackManifestChecked(true);
  76982. });
  76983. }
  76984. else {
  76985. this._checkManifestFile();
  76986. }
  76987. }
  76988. }
  76989. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  76990. /**
  76991. * Gets a boolean indicating if scene must be saved in the database
  76992. */
  76993. get: function () {
  76994. return this._enableSceneOffline;
  76995. },
  76996. enumerable: true,
  76997. configurable: true
  76998. });
  76999. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  77000. /**
  77001. * Gets a boolean indicating if textures must be saved in the database
  77002. */
  77003. get: function () {
  77004. return this._enableTexturesOffline;
  77005. },
  77006. enumerable: true,
  77007. configurable: true
  77008. });
  77009. Database.prototype._checkManifestFile = function () {
  77010. var _this = this;
  77011. var noManifestFile = function () {
  77012. _this._enableSceneOffline = false;
  77013. _this._enableTexturesOffline = false;
  77014. _this.callbackManifestChecked(false);
  77015. };
  77016. var timeStampUsed = false;
  77017. var manifestURL = this.currentSceneUrl + ".manifest";
  77018. var xhr = new XMLHttpRequest();
  77019. if (navigator.onLine) {
  77020. // Adding a timestamp to by-pass browsers' cache
  77021. timeStampUsed = true;
  77022. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  77023. }
  77024. xhr.open("GET", manifestURL, true);
  77025. xhr.addEventListener("load", function () {
  77026. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77027. try {
  77028. var manifestFile = JSON.parse(xhr.response);
  77029. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  77030. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  77031. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  77032. _this.manifestVersionFound = manifestFile.version;
  77033. }
  77034. if (_this.callbackManifestChecked) {
  77035. _this.callbackManifestChecked(true);
  77036. }
  77037. }
  77038. catch (ex) {
  77039. noManifestFile();
  77040. }
  77041. }
  77042. else {
  77043. noManifestFile();
  77044. }
  77045. }, false);
  77046. xhr.addEventListener("error", function (event) {
  77047. if (timeStampUsed) {
  77048. timeStampUsed = false;
  77049. // Let's retry without the timeStamp
  77050. // It could fail when coupled with HTML5 Offline API
  77051. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  77052. xhr.open("GET", retryManifestURL, true);
  77053. xhr.send();
  77054. }
  77055. else {
  77056. noManifestFile();
  77057. }
  77058. }, false);
  77059. try {
  77060. xhr.send();
  77061. }
  77062. catch (ex) {
  77063. BABYLON.Tools.Error("Error on XHR send request.");
  77064. this.callbackManifestChecked(false);
  77065. }
  77066. };
  77067. /**
  77068. * Open the database and make it available
  77069. * @param successCallback defines the callback to call on success
  77070. * @param errorCallback defines the callback to call on error
  77071. */
  77072. Database.prototype.openAsync = function (successCallback, errorCallback) {
  77073. var _this = this;
  77074. var handleError = function () {
  77075. _this.isSupported = false;
  77076. if (errorCallback)
  77077. errorCallback();
  77078. };
  77079. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  77080. // Your browser doesn't support IndexedDB
  77081. this.isSupported = false;
  77082. if (errorCallback)
  77083. errorCallback();
  77084. }
  77085. else {
  77086. // If the DB hasn't been opened or created yet
  77087. if (!this.db) {
  77088. this.hasReachedQuota = false;
  77089. this.isSupported = true;
  77090. var request = this.idbFactory.open("babylonjs", 1);
  77091. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  77092. request.onerror = function (event) {
  77093. handleError();
  77094. };
  77095. // executes when a version change transaction cannot complete due to other active transactions
  77096. request.onblocked = function (event) {
  77097. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  77098. handleError();
  77099. };
  77100. // DB has been opened successfully
  77101. request.onsuccess = function (event) {
  77102. _this.db = request.result;
  77103. successCallback();
  77104. };
  77105. // Initialization of the DB. Creating Scenes & Textures stores
  77106. request.onupgradeneeded = function (event) {
  77107. _this.db = (event.target).result;
  77108. if (_this.db) {
  77109. try {
  77110. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  77111. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  77112. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  77113. }
  77114. catch (ex) {
  77115. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  77116. handleError();
  77117. }
  77118. }
  77119. };
  77120. }
  77121. // DB has already been created and opened
  77122. else {
  77123. if (successCallback)
  77124. successCallback();
  77125. }
  77126. }
  77127. };
  77128. /**
  77129. * Loads an image from the database
  77130. * @param url defines the url to load from
  77131. * @param image defines the target DOM image
  77132. */
  77133. Database.prototype.loadImageFromDB = function (url, image) {
  77134. var _this = this;
  77135. var completeURL = Database._ReturnFullUrlLocation(url);
  77136. var saveAndLoadImage = function () {
  77137. if (!_this.hasReachedQuota && _this.db !== null) {
  77138. // the texture is not yet in the DB, let's try to save it
  77139. _this._saveImageIntoDBAsync(completeURL, image);
  77140. }
  77141. // If the texture is not in the DB and we've reached the DB quota limit
  77142. // let's load it directly from the web
  77143. else {
  77144. image.src = url;
  77145. }
  77146. };
  77147. if (!this.mustUpdateRessources) {
  77148. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  77149. }
  77150. // First time we're download the images or update requested in the manifest file by a version change
  77151. else {
  77152. saveAndLoadImage();
  77153. }
  77154. };
  77155. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  77156. if (this.isSupported && this.db !== null) {
  77157. var texture;
  77158. var transaction = this.db.transaction(["textures"]);
  77159. transaction.onabort = function (event) {
  77160. image.src = url;
  77161. };
  77162. transaction.oncomplete = function (event) {
  77163. var blobTextureURL;
  77164. if (texture) {
  77165. var URL = window.URL || window.webkitURL;
  77166. blobTextureURL = URL.createObjectURL(texture.data);
  77167. image.onerror = function () {
  77168. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  77169. image.src = url;
  77170. };
  77171. image.src = blobTextureURL;
  77172. }
  77173. else {
  77174. notInDBCallback();
  77175. }
  77176. };
  77177. var getRequest = transaction.objectStore("textures").get(url);
  77178. getRequest.onsuccess = function (event) {
  77179. texture = (event.target).result;
  77180. };
  77181. getRequest.onerror = function (event) {
  77182. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  77183. image.src = url;
  77184. };
  77185. }
  77186. else {
  77187. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77188. image.src = url;
  77189. }
  77190. };
  77191. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  77192. var _this = this;
  77193. if (this.isSupported) {
  77194. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  77195. var generateBlobUrl = function () {
  77196. var blobTextureURL;
  77197. if (blob) {
  77198. var URL = window.URL || window.webkitURL;
  77199. try {
  77200. blobTextureURL = URL.createObjectURL(blob);
  77201. }
  77202. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  77203. catch (ex) {
  77204. blobTextureURL = URL.createObjectURL(blob);
  77205. }
  77206. }
  77207. if (blobTextureURL) {
  77208. image.src = blobTextureURL;
  77209. }
  77210. };
  77211. if (Database.IsUASupportingBlobStorage) { // Create XHR
  77212. var xhr = new XMLHttpRequest(), blob;
  77213. xhr.open("GET", url, true);
  77214. xhr.responseType = "blob";
  77215. xhr.addEventListener("load", function () {
  77216. if (xhr.status === 200 && _this.db) {
  77217. // Blob as response (XHR2)
  77218. blob = xhr.response;
  77219. var transaction = _this.db.transaction(["textures"], "readwrite");
  77220. // the transaction could abort because of a QuotaExceededError error
  77221. transaction.onabort = function (event) {
  77222. try {
  77223. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77224. var srcElement = (event.srcElement || event.target);
  77225. var error = srcElement.error;
  77226. if (error && error.name === "QuotaExceededError") {
  77227. _this.hasReachedQuota = true;
  77228. }
  77229. }
  77230. catch (ex) { }
  77231. generateBlobUrl();
  77232. };
  77233. transaction.oncomplete = function (event) {
  77234. generateBlobUrl();
  77235. };
  77236. var newTexture = { textureUrl: url, data: blob };
  77237. try {
  77238. // Put the blob into the dabase
  77239. var addRequest = transaction.objectStore("textures").put(newTexture);
  77240. addRequest.onsuccess = function (event) {
  77241. };
  77242. addRequest.onerror = function (event) {
  77243. generateBlobUrl();
  77244. };
  77245. }
  77246. catch (ex) {
  77247. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  77248. if (ex.code === 25) {
  77249. Database.IsUASupportingBlobStorage = false;
  77250. }
  77251. image.src = url;
  77252. }
  77253. }
  77254. else {
  77255. image.src = url;
  77256. }
  77257. }, false);
  77258. xhr.addEventListener("error", function (event) {
  77259. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  77260. image.src = url;
  77261. }, false);
  77262. xhr.send();
  77263. }
  77264. else {
  77265. image.src = url;
  77266. }
  77267. }
  77268. else {
  77269. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77270. image.src = url;
  77271. }
  77272. };
  77273. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  77274. var _this = this;
  77275. var updateVersion = function () {
  77276. // the version is not yet in the DB or we need to update it
  77277. _this._saveVersionIntoDBAsync(url, versionLoaded);
  77278. };
  77279. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  77280. };
  77281. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  77282. var _this = this;
  77283. if (this.isSupported && this.db) {
  77284. var version;
  77285. try {
  77286. var transaction = this.db.transaction(["versions"]);
  77287. transaction.oncomplete = function (event) {
  77288. if (version) {
  77289. // If the version in the JSON file is different from the version in DB
  77290. if (_this.manifestVersionFound !== version.data) {
  77291. _this.mustUpdateRessources = true;
  77292. updateInDBCallback();
  77293. }
  77294. else {
  77295. callback(version.data);
  77296. }
  77297. }
  77298. // version was not found in DB
  77299. else {
  77300. _this.mustUpdateRessources = true;
  77301. updateInDBCallback();
  77302. }
  77303. };
  77304. transaction.onabort = function (event) {
  77305. callback(-1);
  77306. };
  77307. var getRequest = transaction.objectStore("versions").get(url);
  77308. getRequest.onsuccess = function (event) {
  77309. version = (event.target).result;
  77310. };
  77311. getRequest.onerror = function (event) {
  77312. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  77313. callback(-1);
  77314. };
  77315. }
  77316. catch (ex) {
  77317. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  77318. callback(-1);
  77319. }
  77320. }
  77321. else {
  77322. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77323. callback(-1);
  77324. }
  77325. };
  77326. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  77327. var _this = this;
  77328. if (this.isSupported && !this.hasReachedQuota && this.db) {
  77329. try {
  77330. // Open a transaction to the database
  77331. var transaction = this.db.transaction(["versions"], "readwrite");
  77332. // the transaction could abort because of a QuotaExceededError error
  77333. transaction.onabort = function (event) {
  77334. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77335. var error = event.srcElement['error'];
  77336. if (error && error.name === "QuotaExceededError") {
  77337. _this.hasReachedQuota = true;
  77338. }
  77339. }
  77340. catch (ex) { }
  77341. callback(-1);
  77342. };
  77343. transaction.oncomplete = function (event) {
  77344. callback(_this.manifestVersionFound);
  77345. };
  77346. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  77347. // Put the scene into the database
  77348. var addRequest = transaction.objectStore("versions").put(newVersion);
  77349. addRequest.onsuccess = function (event) {
  77350. };
  77351. addRequest.onerror = function (event) {
  77352. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  77353. };
  77354. }
  77355. catch (ex) {
  77356. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  77357. callback(-1);
  77358. }
  77359. }
  77360. else {
  77361. callback(-1);
  77362. }
  77363. };
  77364. /**
  77365. * Loads a file from database
  77366. * @param url defines the URL to load from
  77367. * @param sceneLoaded defines a callback to call on success
  77368. * @param progressCallBack defines a callback to call when progress changed
  77369. * @param errorCallback defines a callback to call on error
  77370. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  77371. */
  77372. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  77373. var _this = this;
  77374. var completeUrl = Database._ReturnFullUrlLocation(url);
  77375. var saveAndLoadFile = function () {
  77376. // the scene is not yet in the DB, let's try to save it
  77377. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  77378. };
  77379. this._checkVersionFromDB(completeUrl, function (version) {
  77380. if (version !== -1) {
  77381. if (!_this.mustUpdateRessources) {
  77382. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  77383. }
  77384. else {
  77385. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  77386. }
  77387. }
  77388. else {
  77389. if (errorCallback) {
  77390. errorCallback();
  77391. }
  77392. }
  77393. });
  77394. };
  77395. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  77396. if (this.isSupported && this.db) {
  77397. var targetStore;
  77398. if (url.indexOf(".babylon") !== -1) {
  77399. targetStore = "scenes";
  77400. }
  77401. else {
  77402. targetStore = "textures";
  77403. }
  77404. var file;
  77405. var transaction = this.db.transaction([targetStore]);
  77406. transaction.oncomplete = function (event) {
  77407. if (file) {
  77408. callback(file.data);
  77409. }
  77410. // file was not found in DB
  77411. else {
  77412. notInDBCallback();
  77413. }
  77414. };
  77415. transaction.onabort = function (event) {
  77416. notInDBCallback();
  77417. };
  77418. var getRequest = transaction.objectStore(targetStore).get(url);
  77419. getRequest.onsuccess = function (event) {
  77420. file = (event.target).result;
  77421. };
  77422. getRequest.onerror = function (event) {
  77423. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  77424. notInDBCallback();
  77425. };
  77426. }
  77427. else {
  77428. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77429. callback();
  77430. }
  77431. };
  77432. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  77433. var _this = this;
  77434. if (this.isSupported) {
  77435. var targetStore;
  77436. if (url.indexOf(".babylon") !== -1) {
  77437. targetStore = "scenes";
  77438. }
  77439. else {
  77440. targetStore = "textures";
  77441. }
  77442. // Create XHR
  77443. var xhr = new XMLHttpRequest();
  77444. var fileData;
  77445. xhr.open("GET", url + "?" + Date.now(), true);
  77446. if (useArrayBuffer) {
  77447. xhr.responseType = "arraybuffer";
  77448. }
  77449. if (progressCallback) {
  77450. xhr.onprogress = progressCallback;
  77451. }
  77452. xhr.addEventListener("load", function () {
  77453. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  77454. // Blob as response (XHR2)
  77455. //fileData = xhr.responseText;
  77456. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  77457. if (!_this.hasReachedQuota && _this.db) {
  77458. // Open a transaction to the database
  77459. var transaction = _this.db.transaction([targetStore], "readwrite");
  77460. // the transaction could abort because of a QuotaExceededError error
  77461. transaction.onabort = function (event) {
  77462. try {
  77463. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77464. var error = event.srcElement['error'];
  77465. if (error && error.name === "QuotaExceededError") {
  77466. _this.hasReachedQuota = true;
  77467. }
  77468. }
  77469. catch (ex) { }
  77470. callback(fileData);
  77471. };
  77472. transaction.oncomplete = function (event) {
  77473. callback(fileData);
  77474. };
  77475. var newFile;
  77476. if (targetStore === "scenes") {
  77477. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  77478. }
  77479. else {
  77480. newFile = { textureUrl: url, data: fileData };
  77481. }
  77482. try {
  77483. // Put the scene into the database
  77484. var addRequest = transaction.objectStore(targetStore).put(newFile);
  77485. addRequest.onsuccess = function (event) {
  77486. };
  77487. addRequest.onerror = function (event) {
  77488. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  77489. };
  77490. }
  77491. catch (ex) {
  77492. callback(fileData);
  77493. }
  77494. }
  77495. else {
  77496. callback(fileData);
  77497. }
  77498. }
  77499. else {
  77500. if (xhr.status >= 400 && errorCallback) {
  77501. errorCallback(xhr);
  77502. }
  77503. else {
  77504. callback();
  77505. }
  77506. }
  77507. }, false);
  77508. xhr.addEventListener("error", function (event) {
  77509. BABYLON.Tools.Error("error on XHR request.");
  77510. callback();
  77511. }, false);
  77512. xhr.send();
  77513. }
  77514. else {
  77515. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77516. callback();
  77517. }
  77518. };
  77519. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  77520. Database.IsUASupportingBlobStorage = true;
  77521. /** Gets a boolean indicating if Database storate is enabled */
  77522. Database.IDBStorageEnabled = true;
  77523. Database._ParseURL = function (url) {
  77524. var a = document.createElement('a');
  77525. a.href = url;
  77526. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  77527. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  77528. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  77529. return absLocation;
  77530. };
  77531. Database._ReturnFullUrlLocation = function (url) {
  77532. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  77533. return (Database._ParseURL(window.location.href) + url);
  77534. }
  77535. else {
  77536. return url;
  77537. }
  77538. };
  77539. return Database;
  77540. }());
  77541. BABYLON.Database = Database;
  77542. })(BABYLON || (BABYLON = {}));
  77543. //# sourceMappingURL=babylon.database.js.map
  77544. var BABYLON;
  77545. (function (BABYLON) {
  77546. /**
  77547. * This represents all the required information to add a fresnel effect on a material:
  77548. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  77549. */
  77550. var FresnelParameters = /** @class */ (function () {
  77551. function FresnelParameters() {
  77552. this._isEnabled = true;
  77553. /**
  77554. * Define the color used on edges (grazing angle)
  77555. */
  77556. this.leftColor = BABYLON.Color3.White();
  77557. /**
  77558. * Define the color used on center
  77559. */
  77560. this.rightColor = BABYLON.Color3.Black();
  77561. /**
  77562. * Define bias applied to computed fresnel term
  77563. */
  77564. this.bias = 0;
  77565. /**
  77566. * Defined the power exponent applied to fresnel term
  77567. */
  77568. this.power = 1;
  77569. }
  77570. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  77571. /**
  77572. * Define if the fresnel effect is enable or not.
  77573. */
  77574. get: function () {
  77575. return this._isEnabled;
  77576. },
  77577. set: function (value) {
  77578. if (this._isEnabled === value) {
  77579. return;
  77580. }
  77581. this._isEnabled = value;
  77582. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  77583. },
  77584. enumerable: true,
  77585. configurable: true
  77586. });
  77587. /**
  77588. * Clones the current fresnel and its valuues
  77589. * @returns a clone fresnel configuration
  77590. */
  77591. FresnelParameters.prototype.clone = function () {
  77592. var newFresnelParameters = new FresnelParameters();
  77593. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  77594. return newFresnelParameters;
  77595. };
  77596. /**
  77597. * Serializes the current fresnel parameters to a JSON representation.
  77598. * @return the JSON serialization
  77599. */
  77600. FresnelParameters.prototype.serialize = function () {
  77601. var serializationObject = {};
  77602. serializationObject.isEnabled = this.isEnabled;
  77603. serializationObject.leftColor = this.leftColor.asArray();
  77604. serializationObject.rightColor = this.rightColor.asArray();
  77605. serializationObject.bias = this.bias;
  77606. serializationObject.power = this.power;
  77607. return serializationObject;
  77608. };
  77609. /**
  77610. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  77611. * @param parsedFresnelParameters Define the JSON representation
  77612. * @returns the parsed parameters
  77613. */
  77614. FresnelParameters.Parse = function (parsedFresnelParameters) {
  77615. var fresnelParameters = new FresnelParameters();
  77616. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  77617. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  77618. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  77619. fresnelParameters.bias = parsedFresnelParameters.bias;
  77620. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  77621. return fresnelParameters;
  77622. };
  77623. return FresnelParameters;
  77624. }());
  77625. BABYLON.FresnelParameters = FresnelParameters;
  77626. })(BABYLON || (BABYLON = {}));
  77627. //# sourceMappingURL=babylon.fresnelParameters.js.map
  77628. var BABYLON;
  77629. (function (BABYLON) {
  77630. /**
  77631. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77632. * separate meshes. This can be use to improve performances.
  77633. * @see http://doc.babylonjs.com/how_to/multi_materials
  77634. */
  77635. var MultiMaterial = /** @class */ (function (_super) {
  77636. __extends(MultiMaterial, _super);
  77637. /**
  77638. * Instantiates a new Multi Material
  77639. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77640. * separate meshes. This can be use to improve performances.
  77641. * @see http://doc.babylonjs.com/how_to/multi_materials
  77642. * @param name Define the name in the scene
  77643. * @param scene Define the scene the material belongs to
  77644. */
  77645. function MultiMaterial(name, scene) {
  77646. var _this = _super.call(this, name, scene, true) || this;
  77647. scene.multiMaterials.push(_this);
  77648. _this.subMaterials = new Array();
  77649. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  77650. return _this;
  77651. }
  77652. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  77653. /**
  77654. * Gets or Sets the list of Materials used within the multi material.
  77655. * They need to be ordered according to the submeshes order in the associated mesh
  77656. */
  77657. get: function () {
  77658. return this._subMaterials;
  77659. },
  77660. set: function (value) {
  77661. this._subMaterials = value;
  77662. this._hookArray(value);
  77663. },
  77664. enumerable: true,
  77665. configurable: true
  77666. });
  77667. MultiMaterial.prototype._hookArray = function (array) {
  77668. var _this = this;
  77669. var oldPush = array.push;
  77670. array.push = function () {
  77671. var items = [];
  77672. for (var _i = 0; _i < arguments.length; _i++) {
  77673. items[_i] = arguments[_i];
  77674. }
  77675. var result = oldPush.apply(array, items);
  77676. _this._markAllSubMeshesAsTexturesDirty();
  77677. return result;
  77678. };
  77679. var oldSplice = array.splice;
  77680. array.splice = function (index, deleteCount) {
  77681. var deleted = oldSplice.apply(array, [index, deleteCount]);
  77682. _this._markAllSubMeshesAsTexturesDirty();
  77683. return deleted;
  77684. };
  77685. };
  77686. /**
  77687. * Get one of the submaterial by its index in the submaterials array
  77688. * @param index The index to look the sub material at
  77689. * @returns The Material if the index has been defined
  77690. */
  77691. MultiMaterial.prototype.getSubMaterial = function (index) {
  77692. if (index < 0 || index >= this.subMaterials.length) {
  77693. return this.getScene().defaultMaterial;
  77694. }
  77695. return this.subMaterials[index];
  77696. };
  77697. /**
  77698. * Get the list of active textures for the whole sub materials list.
  77699. * @returns All the textures that will be used during the rendering
  77700. */
  77701. MultiMaterial.prototype.getActiveTextures = function () {
  77702. var _a;
  77703. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  77704. if (subMaterial) {
  77705. return subMaterial.getActiveTextures();
  77706. }
  77707. else {
  77708. return [];
  77709. }
  77710. }));
  77711. };
  77712. /**
  77713. * Gets the current class name of the material e.g. "MultiMaterial"
  77714. * Mainly use in serialization.
  77715. * @returns the class name
  77716. */
  77717. MultiMaterial.prototype.getClassName = function () {
  77718. return "MultiMaterial";
  77719. };
  77720. /**
  77721. * Checks if the material is ready to render the requested sub mesh
  77722. * @param mesh Define the mesh the submesh belongs to
  77723. * @param subMesh Define the sub mesh to look readyness for
  77724. * @param useInstances Define whether or not the material is used with instances
  77725. * @returns true if ready, otherwise false
  77726. */
  77727. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77728. for (var index = 0; index < this.subMaterials.length; index++) {
  77729. var subMaterial = this.subMaterials[index];
  77730. if (subMaterial) {
  77731. if (subMaterial.storeEffectOnSubMeshes) {
  77732. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  77733. return false;
  77734. }
  77735. continue;
  77736. }
  77737. if (!subMaterial.isReady(mesh)) {
  77738. return false;
  77739. }
  77740. }
  77741. }
  77742. return true;
  77743. };
  77744. /**
  77745. * Clones the current material and its related sub materials
  77746. * @param name Define the name of the newly cloned material
  77747. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  77748. * @returns the cloned material
  77749. */
  77750. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  77751. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  77752. for (var index = 0; index < this.subMaterials.length; index++) {
  77753. var subMaterial = null;
  77754. var current = this.subMaterials[index];
  77755. if (cloneChildren && current) {
  77756. subMaterial = current.clone(name + "-" + current.name);
  77757. }
  77758. else {
  77759. subMaterial = this.subMaterials[index];
  77760. }
  77761. newMultiMaterial.subMaterials.push(subMaterial);
  77762. }
  77763. return newMultiMaterial;
  77764. };
  77765. /**
  77766. * Serializes the materials into a JSON representation.
  77767. * @returns the JSON representation
  77768. */
  77769. MultiMaterial.prototype.serialize = function () {
  77770. var serializationObject = {};
  77771. serializationObject.name = this.name;
  77772. serializationObject.id = this.id;
  77773. if (BABYLON.Tags) {
  77774. serializationObject.tags = BABYLON.Tags.GetTags(this);
  77775. }
  77776. serializationObject.materials = [];
  77777. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  77778. var subMat = this.subMaterials[matIndex];
  77779. if (subMat) {
  77780. serializationObject.materials.push(subMat.id);
  77781. }
  77782. else {
  77783. serializationObject.materials.push(null);
  77784. }
  77785. }
  77786. return serializationObject;
  77787. };
  77788. /**
  77789. * Dispose the material and release its associated resources
  77790. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  77791. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  77792. */
  77793. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  77794. var scene = this.getScene();
  77795. if (!scene) {
  77796. return;
  77797. }
  77798. var index = scene.multiMaterials.indexOf(this);
  77799. if (index >= 0) {
  77800. scene.multiMaterials.splice(index, 1);
  77801. }
  77802. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  77803. };
  77804. return MultiMaterial;
  77805. }(BABYLON.Material));
  77806. BABYLON.MultiMaterial = MultiMaterial;
  77807. })(BABYLON || (BABYLON = {}));
  77808. //# sourceMappingURL=babylon.multiMaterial.js.map
  77809. var BABYLON;
  77810. (function (BABYLON) {
  77811. /**
  77812. * Manage the touch inputs to control the movement of a free camera.
  77813. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77814. */
  77815. var FreeCameraTouchInput = /** @class */ (function () {
  77816. function FreeCameraTouchInput() {
  77817. /**
  77818. * Defines the touch sensibility for rotation.
  77819. * The higher the faster.
  77820. */
  77821. this.touchAngularSensibility = 200000.0;
  77822. /**
  77823. * Defines the touch sensibility for move.
  77824. * The higher the faster.
  77825. */
  77826. this.touchMoveSensibility = 250.0;
  77827. this._offsetX = null;
  77828. this._offsetY = null;
  77829. this._pointerPressed = new Array();
  77830. }
  77831. /**
  77832. * Attach the input controls to a specific dom element to get the input from.
  77833. * @param element Defines the element the controls should be listened from
  77834. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77835. */
  77836. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  77837. var _this = this;
  77838. var previousPosition = null;
  77839. if (this._pointerInput === undefined) {
  77840. this._onLostFocus = function (evt) {
  77841. _this._offsetX = null;
  77842. _this._offsetY = null;
  77843. };
  77844. this._pointerInput = function (p, s) {
  77845. var evt = p.event;
  77846. if (evt.pointerType === "mouse") {
  77847. return;
  77848. }
  77849. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77850. if (!noPreventDefault) {
  77851. evt.preventDefault();
  77852. }
  77853. _this._pointerPressed.push(evt.pointerId);
  77854. if (_this._pointerPressed.length !== 1) {
  77855. return;
  77856. }
  77857. previousPosition = {
  77858. x: evt.clientX,
  77859. y: evt.clientY
  77860. };
  77861. }
  77862. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  77863. if (!noPreventDefault) {
  77864. evt.preventDefault();
  77865. }
  77866. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77867. if (index === -1) {
  77868. return;
  77869. }
  77870. _this._pointerPressed.splice(index, 1);
  77871. if (index != 0) {
  77872. return;
  77873. }
  77874. previousPosition = null;
  77875. _this._offsetX = null;
  77876. _this._offsetY = null;
  77877. }
  77878. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  77879. if (!noPreventDefault) {
  77880. evt.preventDefault();
  77881. }
  77882. if (!previousPosition) {
  77883. return;
  77884. }
  77885. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77886. if (index != 0) {
  77887. return;
  77888. }
  77889. _this._offsetX = evt.clientX - previousPosition.x;
  77890. _this._offsetY = -(evt.clientY - previousPosition.y);
  77891. }
  77892. };
  77893. }
  77894. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  77895. if (this._onLostFocus) {
  77896. element.addEventListener("blur", this._onLostFocus);
  77897. }
  77898. };
  77899. /**
  77900. * Detach the current controls from the specified dom element.
  77901. * @param element Defines the element to stop listening the inputs from
  77902. */
  77903. FreeCameraTouchInput.prototype.detachControl = function (element) {
  77904. if (this._pointerInput && element) {
  77905. if (this._observer) {
  77906. this.camera.getScene().onPointerObservable.remove(this._observer);
  77907. this._observer = null;
  77908. }
  77909. if (this._onLostFocus) {
  77910. element.removeEventListener("blur", this._onLostFocus);
  77911. this._onLostFocus = null;
  77912. }
  77913. this._pointerPressed = [];
  77914. this._offsetX = null;
  77915. this._offsetY = null;
  77916. }
  77917. };
  77918. /**
  77919. * Update the current camera state depending on the inputs that have been used this frame.
  77920. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77921. */
  77922. FreeCameraTouchInput.prototype.checkInputs = function () {
  77923. if (this._offsetX && this._offsetY) {
  77924. var camera = this.camera;
  77925. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  77926. if (this._pointerPressed.length > 1) {
  77927. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  77928. }
  77929. else {
  77930. var speed = camera._computeLocalCameraSpeed();
  77931. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  77932. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  77933. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  77934. }
  77935. }
  77936. };
  77937. /**
  77938. * Gets the class name of the current intput.
  77939. * @returns the class name
  77940. */
  77941. FreeCameraTouchInput.prototype.getClassName = function () {
  77942. return "FreeCameraTouchInput";
  77943. };
  77944. /**
  77945. * Get the friendly name associated with the input class.
  77946. * @returns the input friendly name
  77947. */
  77948. FreeCameraTouchInput.prototype.getSimpleName = function () {
  77949. return "touch";
  77950. };
  77951. __decorate([
  77952. BABYLON.serialize()
  77953. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  77954. __decorate([
  77955. BABYLON.serialize()
  77956. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  77957. return FreeCameraTouchInput;
  77958. }());
  77959. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  77960. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  77961. })(BABYLON || (BABYLON = {}));
  77962. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  77963. var BABYLON;
  77964. (function (BABYLON) {
  77965. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  77966. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  77967. });
  77968. /**
  77969. * This represents a FPS type of camera controlled by touch.
  77970. * This is like a universal camera minus the Gamepad controls.
  77971. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77972. */
  77973. var TouchCamera = /** @class */ (function (_super) {
  77974. __extends(TouchCamera, _super);
  77975. /**
  77976. * Instantiates a new touch camera.
  77977. * This represents a FPS type of camera controlled by touch.
  77978. * This is like a universal camera minus the Gamepad controls.
  77979. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77980. * @param name Define the name of the camera in the scene
  77981. * @param position Define the start position of the camera in the scene
  77982. * @param scene Define the scene the camera belongs to
  77983. */
  77984. function TouchCamera(name, position, scene) {
  77985. var _this = _super.call(this, name, position, scene) || this;
  77986. _this.inputs.addTouch();
  77987. _this._setupInputs();
  77988. return _this;
  77989. }
  77990. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  77991. /**
  77992. * Defines the touch sensibility for rotation.
  77993. * The higher the faster.
  77994. */
  77995. get: function () {
  77996. var touch = this.inputs.attached["touch"];
  77997. if (touch)
  77998. return touch.touchAngularSensibility;
  77999. return 0;
  78000. },
  78001. set: function (value) {
  78002. var touch = this.inputs.attached["touch"];
  78003. if (touch)
  78004. touch.touchAngularSensibility = value;
  78005. },
  78006. enumerable: true,
  78007. configurable: true
  78008. });
  78009. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  78010. /**
  78011. * Defines the touch sensibility for move.
  78012. * The higher the faster.
  78013. */
  78014. get: function () {
  78015. var touch = this.inputs.attached["touch"];
  78016. if (touch)
  78017. return touch.touchMoveSensibility;
  78018. return 0;
  78019. },
  78020. set: function (value) {
  78021. var touch = this.inputs.attached["touch"];
  78022. if (touch)
  78023. touch.touchMoveSensibility = value;
  78024. },
  78025. enumerable: true,
  78026. configurable: true
  78027. });
  78028. /**
  78029. * Gets the current object class name.
  78030. * @return the class name
  78031. */
  78032. TouchCamera.prototype.getClassName = function () {
  78033. return "TouchCamera";
  78034. };
  78035. /** @hidden */
  78036. TouchCamera.prototype._setupInputs = function () {
  78037. var mouse = this.inputs.attached["mouse"];
  78038. if (mouse) {
  78039. mouse.touchEnabled = false;
  78040. }
  78041. };
  78042. return TouchCamera;
  78043. }(BABYLON.FreeCamera));
  78044. BABYLON.TouchCamera = TouchCamera;
  78045. })(BABYLON || (BABYLON = {}));
  78046. //# sourceMappingURL=babylon.touchCamera.js.map
  78047. var BABYLON;
  78048. (function (BABYLON) {
  78049. /**
  78050. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78051. * This is the base class of any Procedural texture and contains most of the shareable code.
  78052. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78053. */
  78054. var ProceduralTexture = /** @class */ (function (_super) {
  78055. __extends(ProceduralTexture, _super);
  78056. /**
  78057. * Instantiates a new procedural texture.
  78058. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78059. * This is the base class of any Procedural texture and contains most of the shareable code.
  78060. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78061. * @param name Define the name of the texture
  78062. * @param size Define the size of the texture to create
  78063. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  78064. * @param scene Define the scene the texture belongs to
  78065. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78066. * @param generateMipMaps Define if the texture should creates mip maps or not
  78067. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  78068. */
  78069. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  78070. if (fallbackTexture === void 0) { fallbackTexture = null; }
  78071. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78072. if (isCube === void 0) { isCube = false; }
  78073. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  78074. _this.isCube = isCube;
  78075. /**
  78076. * Define if the texture is enabled or not (disabled texture will not render)
  78077. */
  78078. _this.isEnabled = true;
  78079. /**
  78080. * Event raised when the texture is generated
  78081. */
  78082. _this.onGeneratedObservable = new BABYLON.Observable();
  78083. /** @hidden */
  78084. _this._textures = {};
  78085. _this._currentRefreshId = -1;
  78086. _this._refreshRate = 1;
  78087. _this._vertexBuffers = {};
  78088. _this._uniforms = new Array();
  78089. _this._samplers = new Array();
  78090. _this._floats = {};
  78091. _this._ints = {};
  78092. _this._floatsArrays = {};
  78093. _this._colors3 = {};
  78094. _this._colors4 = {};
  78095. _this._vectors2 = {};
  78096. _this._vectors3 = {};
  78097. _this._matrices = {};
  78098. _this._fallbackTextureUsed = false;
  78099. _this._cachedDefines = "";
  78100. _this._contentUpdateId = -1;
  78101. scene = _this.getScene();
  78102. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  78103. if (!component) {
  78104. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  78105. scene._addComponent(component);
  78106. }
  78107. scene.proceduralTextures.push(_this);
  78108. _this._engine = scene.getEngine();
  78109. _this.name = name;
  78110. _this.isRenderTarget = true;
  78111. _this._size = size;
  78112. _this._generateMipMaps = generateMipMaps;
  78113. _this.setFragment(fragment);
  78114. _this._fallbackTexture = fallbackTexture;
  78115. if (isCube) {
  78116. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  78117. _this.setFloat("face", 0);
  78118. }
  78119. else {
  78120. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  78121. }
  78122. // VBO
  78123. var vertices = [];
  78124. vertices.push(1, 1);
  78125. vertices.push(-1, 1);
  78126. vertices.push(-1, -1);
  78127. vertices.push(1, -1);
  78128. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78129. _this._createIndexBuffer();
  78130. return _this;
  78131. }
  78132. /**
  78133. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  78134. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  78135. */
  78136. ProceduralTexture.prototype.getContent = function () {
  78137. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  78138. return this._contentData;
  78139. }
  78140. this._contentData = this.readPixels(0, 0, this._contentData);
  78141. this._contentUpdateId = this._currentRefreshId;
  78142. return this._contentData;
  78143. };
  78144. ProceduralTexture.prototype._createIndexBuffer = function () {
  78145. var engine = this._engine;
  78146. // Indices
  78147. var indices = [];
  78148. indices.push(0);
  78149. indices.push(1);
  78150. indices.push(2);
  78151. indices.push(0);
  78152. indices.push(2);
  78153. indices.push(3);
  78154. this._indexBuffer = engine.createIndexBuffer(indices);
  78155. };
  78156. /** @hidden */
  78157. ProceduralTexture.prototype._rebuild = function () {
  78158. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78159. if (vb) {
  78160. vb._rebuild();
  78161. }
  78162. this._createIndexBuffer();
  78163. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  78164. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  78165. }
  78166. };
  78167. /**
  78168. * Resets the texture in order to recreate its associated resources.
  78169. * This can be called in case of context loss
  78170. */
  78171. ProceduralTexture.prototype.reset = function () {
  78172. if (this._effect === undefined) {
  78173. return;
  78174. }
  78175. var engine = this._engine;
  78176. engine._releaseEffect(this._effect);
  78177. };
  78178. ProceduralTexture.prototype._getDefines = function () {
  78179. return "";
  78180. };
  78181. /**
  78182. * Is the texture ready to be used ? (rendered at least once)
  78183. * @returns true if ready, otherwise, false.
  78184. */
  78185. ProceduralTexture.prototype.isReady = function () {
  78186. var _this = this;
  78187. var engine = this._engine;
  78188. var shaders;
  78189. if (!this._fragment) {
  78190. return false;
  78191. }
  78192. if (this._fallbackTextureUsed) {
  78193. return true;
  78194. }
  78195. var defines = this._getDefines();
  78196. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  78197. return true;
  78198. }
  78199. if (this._fragment.fragmentElement !== undefined) {
  78200. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  78201. }
  78202. else {
  78203. shaders = { vertex: "procedural", fragment: this._fragment };
  78204. }
  78205. this._cachedDefines = defines;
  78206. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  78207. _this.releaseInternalTexture();
  78208. if (_this._fallbackTexture) {
  78209. _this._texture = _this._fallbackTexture._texture;
  78210. if (_this._texture) {
  78211. _this._texture.incrementReferences();
  78212. }
  78213. }
  78214. _this._fallbackTextureUsed = true;
  78215. });
  78216. return this._effect.isReady();
  78217. };
  78218. /**
  78219. * Resets the refresh counter of the texture and start bak from scratch.
  78220. * Could be usefull to regenerate the texture if it is setup to render only once.
  78221. */
  78222. ProceduralTexture.prototype.resetRefreshCounter = function () {
  78223. this._currentRefreshId = -1;
  78224. };
  78225. /**
  78226. * Set the fragment shader to use in order to render the texture.
  78227. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  78228. */
  78229. ProceduralTexture.prototype.setFragment = function (fragment) {
  78230. this._fragment = fragment;
  78231. };
  78232. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  78233. /**
  78234. * Define the refresh rate of the texture or the rendering frequency.
  78235. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  78236. */
  78237. get: function () {
  78238. return this._refreshRate;
  78239. },
  78240. set: function (value) {
  78241. this._refreshRate = value;
  78242. this.resetRefreshCounter();
  78243. },
  78244. enumerable: true,
  78245. configurable: true
  78246. });
  78247. /** @hidden */
  78248. ProceduralTexture.prototype._shouldRender = function () {
  78249. if (!this.isEnabled || !this.isReady() || !this._texture) {
  78250. if (this._texture) {
  78251. this._texture.isReady = false;
  78252. }
  78253. return false;
  78254. }
  78255. if (this._fallbackTextureUsed) {
  78256. return false;
  78257. }
  78258. if (this._currentRefreshId === -1) { // At least render once
  78259. this._currentRefreshId = 1;
  78260. return true;
  78261. }
  78262. if (this.refreshRate === this._currentRefreshId) {
  78263. this._currentRefreshId = 1;
  78264. return true;
  78265. }
  78266. this._currentRefreshId++;
  78267. return false;
  78268. };
  78269. /**
  78270. * Get the size the texture is rendering at.
  78271. * @returns the size (texture is always squared)
  78272. */
  78273. ProceduralTexture.prototype.getRenderSize = function () {
  78274. return this._size;
  78275. };
  78276. /**
  78277. * Resize the texture to new value.
  78278. * @param size Define the new size the texture should have
  78279. * @param generateMipMaps Define whether the new texture should create mip maps
  78280. */
  78281. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  78282. if (this._fallbackTextureUsed) {
  78283. return;
  78284. }
  78285. this.releaseInternalTexture();
  78286. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  78287. // Update properties
  78288. this._size = size;
  78289. this._generateMipMaps = generateMipMaps;
  78290. };
  78291. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  78292. if (this._uniforms.indexOf(uniformName) === -1) {
  78293. this._uniforms.push(uniformName);
  78294. }
  78295. };
  78296. /**
  78297. * Set a texture in the shader program used to render.
  78298. * @param name Define the name of the uniform samplers as defined in the shader
  78299. * @param texture Define the texture to bind to this sampler
  78300. * @return the texture itself allowing "fluent" like uniform updates
  78301. */
  78302. ProceduralTexture.prototype.setTexture = function (name, texture) {
  78303. if (this._samplers.indexOf(name) === -1) {
  78304. this._samplers.push(name);
  78305. }
  78306. this._textures[name] = texture;
  78307. return this;
  78308. };
  78309. /**
  78310. * Set a float in the shader.
  78311. * @param name Define the name of the uniform as defined in the shader
  78312. * @param value Define the value to give to the uniform
  78313. * @return the texture itself allowing "fluent" like uniform updates
  78314. */
  78315. ProceduralTexture.prototype.setFloat = function (name, value) {
  78316. this._checkUniform(name);
  78317. this._floats[name] = value;
  78318. return this;
  78319. };
  78320. /**
  78321. * Set a int in the shader.
  78322. * @param name Define the name of the uniform as defined in the shader
  78323. * @param value Define the value to give to the uniform
  78324. * @return the texture itself allowing "fluent" like uniform updates
  78325. */
  78326. ProceduralTexture.prototype.setInt = function (name, value) {
  78327. this._checkUniform(name);
  78328. this._ints[name] = value;
  78329. return this;
  78330. };
  78331. /**
  78332. * Set an array of floats in the shader.
  78333. * @param name Define the name of the uniform as defined in the shader
  78334. * @param value Define the value to give to the uniform
  78335. * @return the texture itself allowing "fluent" like uniform updates
  78336. */
  78337. ProceduralTexture.prototype.setFloats = function (name, value) {
  78338. this._checkUniform(name);
  78339. this._floatsArrays[name] = value;
  78340. return this;
  78341. };
  78342. /**
  78343. * Set a vec3 in the shader from a Color3.
  78344. * @param name Define the name of the uniform as defined in the shader
  78345. * @param value Define the value to give to the uniform
  78346. * @return the texture itself allowing "fluent" like uniform updates
  78347. */
  78348. ProceduralTexture.prototype.setColor3 = function (name, value) {
  78349. this._checkUniform(name);
  78350. this._colors3[name] = value;
  78351. return this;
  78352. };
  78353. /**
  78354. * Set a vec4 in the shader from a Color4.
  78355. * @param name Define the name of the uniform as defined in the shader
  78356. * @param value Define the value to give to the uniform
  78357. * @return the texture itself allowing "fluent" like uniform updates
  78358. */
  78359. ProceduralTexture.prototype.setColor4 = function (name, value) {
  78360. this._checkUniform(name);
  78361. this._colors4[name] = value;
  78362. return this;
  78363. };
  78364. /**
  78365. * Set a vec2 in the shader from a Vector2.
  78366. * @param name Define the name of the uniform as defined in the shader
  78367. * @param value Define the value to give to the uniform
  78368. * @return the texture itself allowing "fluent" like uniform updates
  78369. */
  78370. ProceduralTexture.prototype.setVector2 = function (name, value) {
  78371. this._checkUniform(name);
  78372. this._vectors2[name] = value;
  78373. return this;
  78374. };
  78375. /**
  78376. * Set a vec3 in the shader from a Vector3.
  78377. * @param name Define the name of the uniform as defined in the shader
  78378. * @param value Define the value to give to the uniform
  78379. * @return the texture itself allowing "fluent" like uniform updates
  78380. */
  78381. ProceduralTexture.prototype.setVector3 = function (name, value) {
  78382. this._checkUniform(name);
  78383. this._vectors3[name] = value;
  78384. return this;
  78385. };
  78386. /**
  78387. * Set a mat4 in the shader from a MAtrix.
  78388. * @param name Define the name of the uniform as defined in the shader
  78389. * @param value Define the value to give to the uniform
  78390. * @return the texture itself allowing "fluent" like uniform updates
  78391. */
  78392. ProceduralTexture.prototype.setMatrix = function (name, value) {
  78393. this._checkUniform(name);
  78394. this._matrices[name] = value;
  78395. return this;
  78396. };
  78397. /**
  78398. * Render the texture to its associated render target.
  78399. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  78400. */
  78401. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78402. var scene = this.getScene();
  78403. if (!scene) {
  78404. return;
  78405. }
  78406. var engine = this._engine;
  78407. // Render
  78408. engine.enableEffect(this._effect);
  78409. engine.setState(false);
  78410. // Texture
  78411. for (var name in this._textures) {
  78412. this._effect.setTexture(name, this._textures[name]);
  78413. }
  78414. // Float
  78415. for (name in this._ints) {
  78416. this._effect.setInt(name, this._ints[name]);
  78417. }
  78418. // Float
  78419. for (name in this._floats) {
  78420. this._effect.setFloat(name, this._floats[name]);
  78421. }
  78422. // Floats
  78423. for (name in this._floatsArrays) {
  78424. this._effect.setArray(name, this._floatsArrays[name]);
  78425. }
  78426. // Color3
  78427. for (name in this._colors3) {
  78428. this._effect.setColor3(name, this._colors3[name]);
  78429. }
  78430. // Color4
  78431. for (name in this._colors4) {
  78432. var color = this._colors4[name];
  78433. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  78434. }
  78435. // Vector2
  78436. for (name in this._vectors2) {
  78437. this._effect.setVector2(name, this._vectors2[name]);
  78438. }
  78439. // Vector3
  78440. for (name in this._vectors3) {
  78441. this._effect.setVector3(name, this._vectors3[name]);
  78442. }
  78443. // Matrix
  78444. for (name in this._matrices) {
  78445. this._effect.setMatrix(name, this._matrices[name]);
  78446. }
  78447. if (!this._texture) {
  78448. return;
  78449. }
  78450. if (this.isCube) {
  78451. for (var face = 0; face < 6; face++) {
  78452. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  78453. // VBOs
  78454. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  78455. this._effect.setFloat("face", face);
  78456. // Clear
  78457. engine.clear(scene.clearColor, true, true, true);
  78458. // Draw order
  78459. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78460. // Mipmaps
  78461. if (face === 5) {
  78462. engine.generateMipMapsForCubemap(this._texture);
  78463. }
  78464. }
  78465. }
  78466. else {
  78467. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  78468. // VBOs
  78469. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  78470. // Clear
  78471. engine.clear(scene.clearColor, true, true, true);
  78472. // Draw order
  78473. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78474. }
  78475. // Unbind
  78476. engine.unBindFramebuffer(this._texture, this.isCube);
  78477. if (this.onGenerated) {
  78478. this.onGenerated();
  78479. }
  78480. this.onGeneratedObservable.notifyObservers(this);
  78481. };
  78482. /**
  78483. * Clone the texture.
  78484. * @returns the cloned texture
  78485. */
  78486. ProceduralTexture.prototype.clone = function () {
  78487. var textureSize = this.getSize();
  78488. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  78489. // Base texture
  78490. newTexture.hasAlpha = this.hasAlpha;
  78491. newTexture.level = this.level;
  78492. // RenderTarget Texture
  78493. newTexture.coordinatesMode = this.coordinatesMode;
  78494. return newTexture;
  78495. };
  78496. /**
  78497. * Dispose the texture and release its asoociated resources.
  78498. */
  78499. ProceduralTexture.prototype.dispose = function () {
  78500. var scene = this.getScene();
  78501. if (!scene) {
  78502. return;
  78503. }
  78504. var index = scene.proceduralTextures.indexOf(this);
  78505. if (index >= 0) {
  78506. scene.proceduralTextures.splice(index, 1);
  78507. }
  78508. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78509. if (vertexBuffer) {
  78510. vertexBuffer.dispose();
  78511. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78512. }
  78513. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  78514. this._indexBuffer = null;
  78515. }
  78516. _super.prototype.dispose.call(this);
  78517. };
  78518. __decorate([
  78519. BABYLON.serialize()
  78520. ], ProceduralTexture.prototype, "isEnabled", void 0);
  78521. __decorate([
  78522. BABYLON.serialize()
  78523. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  78524. __decorate([
  78525. BABYLON.serialize()
  78526. ], ProceduralTexture.prototype, "_size", void 0);
  78527. __decorate([
  78528. BABYLON.serialize()
  78529. ], ProceduralTexture.prototype, "refreshRate", null);
  78530. return ProceduralTexture;
  78531. }(BABYLON.Texture));
  78532. BABYLON.ProceduralTexture = ProceduralTexture;
  78533. })(BABYLON || (BABYLON = {}));
  78534. //# sourceMappingURL=babylon.proceduralTexture.js.map
  78535. var BABYLON;
  78536. (function (BABYLON) {
  78537. /**
  78538. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  78539. * in a given scene.
  78540. */
  78541. var ProceduralTextureSceneComponent = /** @class */ (function () {
  78542. /**
  78543. * Creates a new instance of the component for the given scene
  78544. * @param scene Defines the scene to register the component in
  78545. */
  78546. function ProceduralTextureSceneComponent(scene) {
  78547. /**
  78548. * The component name helpfull to identify the component in the list of scene components.
  78549. */
  78550. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  78551. this.scene = scene;
  78552. this.scene.proceduralTextures = new Array();
  78553. scene.layers = new Array();
  78554. }
  78555. /**
  78556. * Registers the component in a given scene
  78557. */
  78558. ProceduralTextureSceneComponent.prototype.register = function () {
  78559. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  78560. };
  78561. /**
  78562. * Rebuilds the elements related to this component in case of
  78563. * context lost for instance.
  78564. */
  78565. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  78566. // Nothing to do here.
  78567. };
  78568. /**
  78569. * Disposes the component and the associated ressources.
  78570. */
  78571. ProceduralTextureSceneComponent.prototype.dispose = function () {
  78572. // Nothing to do here.
  78573. };
  78574. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  78575. if (this.scene.proceduralTexturesEnabled) {
  78576. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78577. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  78578. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  78579. if (proceduralTexture._shouldRender()) {
  78580. proceduralTexture.render();
  78581. }
  78582. }
  78583. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78584. }
  78585. };
  78586. return ProceduralTextureSceneComponent;
  78587. }());
  78588. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  78589. })(BABYLON || (BABYLON = {}));
  78590. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  78591. var BABYLON;
  78592. (function (BABYLON) {
  78593. /**
  78594. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78595. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  78596. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  78597. */
  78598. var CustomProceduralTexture = /** @class */ (function (_super) {
  78599. __extends(CustomProceduralTexture, _super);
  78600. /**
  78601. * Instantiates a new Custom Procedural Texture.
  78602. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78603. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  78604. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  78605. * @param name Define the name of the texture
  78606. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  78607. * @param size Define the size of the texture to create
  78608. * @param scene Define the scene the texture belongs to
  78609. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78610. * @param generateMipMaps Define if the texture should creates mip maps or not
  78611. */
  78612. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  78613. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  78614. _this._animate = true;
  78615. _this._time = 0;
  78616. _this._texturePath = texturePath;
  78617. //Try to load json
  78618. _this._loadJson(texturePath);
  78619. _this.refreshRate = 1;
  78620. return _this;
  78621. }
  78622. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  78623. var _this = this;
  78624. var noConfigFile = function () {
  78625. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  78626. try {
  78627. _this.setFragment(_this._texturePath);
  78628. }
  78629. catch (ex) {
  78630. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  78631. }
  78632. };
  78633. var configFileUrl = jsonUrl + "/config.json";
  78634. var xhr = new XMLHttpRequest();
  78635. xhr.open("GET", configFileUrl, true);
  78636. xhr.addEventListener("load", function () {
  78637. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78638. try {
  78639. _this._config = JSON.parse(xhr.response);
  78640. _this.updateShaderUniforms();
  78641. _this.updateTextures();
  78642. _this.setFragment(_this._texturePath + "/custom");
  78643. _this._animate = _this._config.animate;
  78644. _this.refreshRate = _this._config.refreshrate;
  78645. }
  78646. catch (ex) {
  78647. noConfigFile();
  78648. }
  78649. }
  78650. else {
  78651. noConfigFile();
  78652. }
  78653. }, false);
  78654. xhr.addEventListener("error", function () {
  78655. noConfigFile();
  78656. }, false);
  78657. try {
  78658. xhr.send();
  78659. }
  78660. catch (ex) {
  78661. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  78662. }
  78663. };
  78664. /**
  78665. * Is the texture ready to be used ? (rendered at least once)
  78666. * @returns true if ready, otherwise, false.
  78667. */
  78668. CustomProceduralTexture.prototype.isReady = function () {
  78669. if (!_super.prototype.isReady.call(this)) {
  78670. return false;
  78671. }
  78672. for (var name in this._textures) {
  78673. var texture = this._textures[name];
  78674. if (!texture.isReady()) {
  78675. return false;
  78676. }
  78677. }
  78678. return true;
  78679. };
  78680. /**
  78681. * Render the texture to its associated render target.
  78682. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  78683. */
  78684. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78685. var scene = this.getScene();
  78686. if (this._animate && scene) {
  78687. this._time += scene.getAnimationRatio() * 0.03;
  78688. this.updateShaderUniforms();
  78689. }
  78690. _super.prototype.render.call(this, useCameraPostProcess);
  78691. };
  78692. /**
  78693. * Update the list of dependant textures samplers in the shader.
  78694. */
  78695. CustomProceduralTexture.prototype.updateTextures = function () {
  78696. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  78697. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  78698. }
  78699. };
  78700. /**
  78701. * Update the uniform values of the procedural texture in the shader.
  78702. */
  78703. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  78704. if (this._config) {
  78705. for (var j = 0; j < this._config.uniforms.length; j++) {
  78706. var uniform = this._config.uniforms[j];
  78707. switch (uniform.type) {
  78708. case "float":
  78709. this.setFloat(uniform.name, uniform.value);
  78710. break;
  78711. case "color3":
  78712. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  78713. break;
  78714. case "color4":
  78715. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  78716. break;
  78717. case "vector2":
  78718. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  78719. break;
  78720. case "vector3":
  78721. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  78722. break;
  78723. }
  78724. }
  78725. }
  78726. this.setFloat("time", this._time);
  78727. };
  78728. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  78729. /**
  78730. * Define if the texture animates or not.
  78731. */
  78732. get: function () {
  78733. return this._animate;
  78734. },
  78735. set: function (value) {
  78736. this._animate = value;
  78737. },
  78738. enumerable: true,
  78739. configurable: true
  78740. });
  78741. return CustomProceduralTexture;
  78742. }(BABYLON.ProceduralTexture));
  78743. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  78744. })(BABYLON || (BABYLON = {}));
  78745. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  78746. var BABYLON;
  78747. (function (BABYLON) {
  78748. /**
  78749. * Manage the gamepad inputs to control a free camera.
  78750. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78751. */
  78752. var FreeCameraGamepadInput = /** @class */ (function () {
  78753. function FreeCameraGamepadInput() {
  78754. /**
  78755. * Defines the gamepad rotation sensiblity.
  78756. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78757. */
  78758. this.gamepadAngularSensibility = 200;
  78759. /**
  78760. * Defines the gamepad move sensiblity.
  78761. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78762. */
  78763. this.gamepadMoveSensibility = 40;
  78764. this._cameraTransform = BABYLON.Matrix.Identity();
  78765. this._deltaTransform = BABYLON.Vector3.Zero();
  78766. this._vector3 = BABYLON.Vector3.Zero();
  78767. this._vector2 = BABYLON.Vector2.Zero();
  78768. }
  78769. /**
  78770. * Attach the input controls to a specific dom element to get the input from.
  78771. * @param element Defines the element the controls should be listened from
  78772. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78773. */
  78774. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78775. var _this = this;
  78776. var manager = this.camera.getScene().gamepadManager;
  78777. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78778. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78779. // prioritize XBOX gamepads.
  78780. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78781. _this.gamepad = gamepad;
  78782. }
  78783. }
  78784. });
  78785. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78786. if (_this.gamepad === gamepad) {
  78787. _this.gamepad = null;
  78788. }
  78789. });
  78790. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78791. };
  78792. /**
  78793. * Detach the current controls from the specified dom element.
  78794. * @param element Defines the element to stop listening the inputs from
  78795. */
  78796. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  78797. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78798. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78799. this.gamepad = null;
  78800. };
  78801. /**
  78802. * Update the current camera state depending on the inputs that have been used this frame.
  78803. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78804. */
  78805. FreeCameraGamepadInput.prototype.checkInputs = function () {
  78806. if (this.gamepad && this.gamepad.leftStick) {
  78807. var camera = this.camera;
  78808. var LSValues = this.gamepad.leftStick;
  78809. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  78810. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78811. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  78812. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  78813. var RSValues = this.gamepad.rightStick;
  78814. if (RSValues) {
  78815. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  78816. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  78817. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  78818. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  78819. }
  78820. else {
  78821. RSValues = { x: 0, y: 0 };
  78822. }
  78823. if (!camera.rotationQuaternion) {
  78824. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  78825. }
  78826. else {
  78827. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  78828. }
  78829. var speed = camera._computeLocalCameraSpeed() * 50.0;
  78830. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  78831. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  78832. camera.cameraDirection.addInPlace(this._deltaTransform);
  78833. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  78834. camera.cameraRotation.addInPlace(this._vector2);
  78835. }
  78836. };
  78837. /**
  78838. * Gets the class name of the current intput.
  78839. * @returns the class name
  78840. */
  78841. FreeCameraGamepadInput.prototype.getClassName = function () {
  78842. return "FreeCameraGamepadInput";
  78843. };
  78844. /**
  78845. * Get the friendly name associated with the input class.
  78846. * @returns the input friendly name
  78847. */
  78848. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  78849. return "gamepad";
  78850. };
  78851. __decorate([
  78852. BABYLON.serialize()
  78853. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  78854. __decorate([
  78855. BABYLON.serialize()
  78856. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78857. return FreeCameraGamepadInput;
  78858. }());
  78859. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  78860. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  78861. })(BABYLON || (BABYLON = {}));
  78862. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  78863. var BABYLON;
  78864. (function (BABYLON) {
  78865. /**
  78866. * Manage the gamepad inputs to control an arc rotate camera.
  78867. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78868. */
  78869. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  78870. function ArcRotateCameraGamepadInput() {
  78871. /**
  78872. * Defines the gamepad rotation sensiblity.
  78873. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78874. */
  78875. this.gamepadRotationSensibility = 80;
  78876. /**
  78877. * Defines the gamepad move sensiblity.
  78878. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78879. */
  78880. this.gamepadMoveSensibility = 40;
  78881. }
  78882. /**
  78883. * Attach the input controls to a specific dom element to get the input from.
  78884. * @param element Defines the element the controls should be listened from
  78885. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78886. */
  78887. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78888. var _this = this;
  78889. var manager = this.camera.getScene().gamepadManager;
  78890. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78891. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78892. // prioritize XBOX gamepads.
  78893. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78894. _this.gamepad = gamepad;
  78895. }
  78896. }
  78897. });
  78898. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78899. if (_this.gamepad === gamepad) {
  78900. _this.gamepad = null;
  78901. }
  78902. });
  78903. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78904. };
  78905. /**
  78906. * Detach the current controls from the specified dom element.
  78907. * @param element Defines the element to stop listening the inputs from
  78908. */
  78909. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  78910. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78911. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78912. this.gamepad = null;
  78913. };
  78914. /**
  78915. * Update the current camera state depending on the inputs that have been used this frame.
  78916. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78917. */
  78918. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  78919. if (this.gamepad) {
  78920. var camera = this.camera;
  78921. var RSValues = this.gamepad.rightStick;
  78922. if (RSValues) {
  78923. if (RSValues.x != 0) {
  78924. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  78925. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  78926. camera.inertialAlphaOffset += normalizedRX;
  78927. }
  78928. }
  78929. if (RSValues.y != 0) {
  78930. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  78931. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  78932. camera.inertialBetaOffset += normalizedRY;
  78933. }
  78934. }
  78935. }
  78936. var LSValues = this.gamepad.leftStick;
  78937. if (LSValues && LSValues.y != 0) {
  78938. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78939. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  78940. this.camera.inertialRadiusOffset -= normalizedLY;
  78941. }
  78942. }
  78943. }
  78944. };
  78945. /**
  78946. * Gets the class name of the current intput.
  78947. * @returns the class name
  78948. */
  78949. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  78950. return "ArcRotateCameraGamepadInput";
  78951. };
  78952. /**
  78953. * Get the friendly name associated with the input class.
  78954. * @returns the input friendly name
  78955. */
  78956. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  78957. return "gamepad";
  78958. };
  78959. __decorate([
  78960. BABYLON.serialize()
  78961. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  78962. __decorate([
  78963. BABYLON.serialize()
  78964. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78965. return ArcRotateCameraGamepadInput;
  78966. }());
  78967. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  78968. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  78969. })(BABYLON || (BABYLON = {}));
  78970. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  78971. var BABYLON;
  78972. (function (BABYLON) {
  78973. /**
  78974. * Manager for handling gamepads
  78975. */
  78976. var GamepadManager = /** @class */ (function () {
  78977. /**
  78978. * Initializes the gamepad manager
  78979. * @param _scene BabylonJS scene
  78980. */
  78981. function GamepadManager(_scene) {
  78982. var _this = this;
  78983. this._scene = _scene;
  78984. this._babylonGamepads = [];
  78985. this._oneGamepadConnected = false;
  78986. /** @hidden */
  78987. this._isMonitoring = false;
  78988. /**
  78989. * observable to be triggered when the gamepad controller has been disconnected
  78990. */
  78991. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  78992. if (!BABYLON.Tools.IsWindowObjectExist()) {
  78993. this._gamepadEventSupported = false;
  78994. }
  78995. else {
  78996. this._gamepadEventSupported = 'GamepadEvent' in window;
  78997. this._gamepadSupport = (navigator.getGamepads ||
  78998. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  78999. }
  79000. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  79001. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  79002. for (var i in _this._babylonGamepads) {
  79003. var gamepad = _this._babylonGamepads[i];
  79004. if (gamepad && gamepad._isConnected) {
  79005. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  79006. }
  79007. }
  79008. });
  79009. this._onGamepadConnectedEvent = function (evt) {
  79010. var gamepad = evt.gamepad;
  79011. if (gamepad.index in _this._babylonGamepads) {
  79012. if (_this._babylonGamepads[gamepad.index].isConnected) {
  79013. return;
  79014. }
  79015. }
  79016. var newGamepad;
  79017. if (_this._babylonGamepads[gamepad.index]) {
  79018. newGamepad = _this._babylonGamepads[gamepad.index];
  79019. newGamepad.browserGamepad = gamepad;
  79020. newGamepad._isConnected = true;
  79021. }
  79022. else {
  79023. newGamepad = _this._addNewGamepad(gamepad);
  79024. }
  79025. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79026. _this._startMonitoringGamepads();
  79027. };
  79028. this._onGamepadDisconnectedEvent = function (evt) {
  79029. var gamepad = evt.gamepad;
  79030. // Remove the gamepad from the list of gamepads to monitor.
  79031. for (var i in _this._babylonGamepads) {
  79032. if (_this._babylonGamepads[i].index === gamepad.index) {
  79033. var disconnectedGamepad = _this._babylonGamepads[i];
  79034. disconnectedGamepad._isConnected = false;
  79035. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  79036. break;
  79037. }
  79038. }
  79039. };
  79040. if (this._gamepadSupport) {
  79041. //first add already-connected gamepads
  79042. this._updateGamepadObjects();
  79043. if (this._babylonGamepads.length) {
  79044. this._startMonitoringGamepads();
  79045. }
  79046. // Checking if the gamepad connected event is supported (like in Firefox)
  79047. if (this._gamepadEventSupported) {
  79048. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  79049. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  79050. }
  79051. else {
  79052. this._startMonitoringGamepads();
  79053. }
  79054. }
  79055. }
  79056. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  79057. /**
  79058. * The gamepads in the game pad manager
  79059. */
  79060. get: function () {
  79061. return this._babylonGamepads;
  79062. },
  79063. enumerable: true,
  79064. configurable: true
  79065. });
  79066. /**
  79067. * Get the gamepad controllers based on type
  79068. * @param type The type of gamepad controller
  79069. * @returns Nullable gamepad
  79070. */
  79071. GamepadManager.prototype.getGamepadByType = function (type) {
  79072. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  79073. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  79074. var gamepad = _a[_i];
  79075. if (gamepad && gamepad.type === type) {
  79076. return gamepad;
  79077. }
  79078. }
  79079. return null;
  79080. };
  79081. /**
  79082. * Disposes the gamepad manager
  79083. */
  79084. GamepadManager.prototype.dispose = function () {
  79085. if (this._gamepadEventSupported) {
  79086. if (this._onGamepadConnectedEvent) {
  79087. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  79088. }
  79089. if (this._onGamepadDisconnectedEvent) {
  79090. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  79091. }
  79092. this._onGamepadConnectedEvent = null;
  79093. this._onGamepadDisconnectedEvent = null;
  79094. }
  79095. this._babylonGamepads.forEach(function (gamepad) {
  79096. gamepad.dispose();
  79097. });
  79098. this.onGamepadConnectedObservable.clear();
  79099. this.onGamepadDisconnectedObservable.clear();
  79100. this._oneGamepadConnected = false;
  79101. this._stopMonitoringGamepads();
  79102. this._babylonGamepads = [];
  79103. };
  79104. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  79105. if (!this._oneGamepadConnected) {
  79106. this._oneGamepadConnected = true;
  79107. }
  79108. var newGamepad;
  79109. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  79110. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  79111. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  79112. }
  79113. // if pose is supported, use the (WebVR) pose enabled controller
  79114. else if (gamepad.pose) {
  79115. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  79116. }
  79117. else {
  79118. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  79119. }
  79120. this._babylonGamepads[newGamepad.index] = newGamepad;
  79121. return newGamepad;
  79122. };
  79123. GamepadManager.prototype._startMonitoringGamepads = function () {
  79124. if (!this._isMonitoring) {
  79125. this._isMonitoring = true;
  79126. //back-comp
  79127. if (!this._scene) {
  79128. this._checkGamepadsStatus();
  79129. }
  79130. }
  79131. };
  79132. GamepadManager.prototype._stopMonitoringGamepads = function () {
  79133. this._isMonitoring = false;
  79134. };
  79135. /** @hidden */
  79136. GamepadManager.prototype._checkGamepadsStatus = function () {
  79137. var _this = this;
  79138. // Hack to be compatible Chrome
  79139. this._updateGamepadObjects();
  79140. for (var i in this._babylonGamepads) {
  79141. var gamepad = this._babylonGamepads[i];
  79142. if (!gamepad || !gamepad.isConnected) {
  79143. continue;
  79144. }
  79145. gamepad.update();
  79146. }
  79147. if (this._isMonitoring && !this._scene) {
  79148. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  79149. }
  79150. };
  79151. // This function is called only on Chrome, which does not properly support
  79152. // connection/disconnection events and forces you to recopy again the gamepad object
  79153. GamepadManager.prototype._updateGamepadObjects = function () {
  79154. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  79155. for (var i = 0; i < gamepads.length; i++) {
  79156. var gamepad = gamepads[i];
  79157. if (gamepad) {
  79158. if (!this._babylonGamepads[gamepad.index]) {
  79159. var newGamepad = this._addNewGamepad(gamepad);
  79160. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79161. }
  79162. else {
  79163. // Forced to copy again this object for Chrome for unknown reason
  79164. this._babylonGamepads[i].browserGamepad = gamepad;
  79165. if (!this._babylonGamepads[i].isConnected) {
  79166. this._babylonGamepads[i]._isConnected = true;
  79167. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  79168. }
  79169. }
  79170. }
  79171. }
  79172. };
  79173. return GamepadManager;
  79174. }());
  79175. BABYLON.GamepadManager = GamepadManager;
  79176. })(BABYLON || (BABYLON = {}));
  79177. //# sourceMappingURL=babylon.gamepadManager.js.map
  79178. var BABYLON;
  79179. (function (BABYLON) {
  79180. /**
  79181. * Represents a gamepad control stick position
  79182. */
  79183. var StickValues = /** @class */ (function () {
  79184. /**
  79185. * Initializes the gamepad x and y control stick values
  79186. * @param x The x component of the gamepad control stick value
  79187. * @param y The y component of the gamepad control stick value
  79188. */
  79189. function StickValues(
  79190. /**
  79191. * The x component of the control stick
  79192. */
  79193. x,
  79194. /**
  79195. * The y component of the control stick
  79196. */
  79197. y) {
  79198. this.x = x;
  79199. this.y = y;
  79200. }
  79201. return StickValues;
  79202. }());
  79203. BABYLON.StickValues = StickValues;
  79204. /**
  79205. * Represents a gamepad
  79206. */
  79207. var Gamepad = /** @class */ (function () {
  79208. /**
  79209. * Initializes the gamepad
  79210. * @param id The id of the gamepad
  79211. * @param index The index of the gamepad
  79212. * @param browserGamepad The browser gamepad
  79213. * @param leftStickX The x component of the left joystick
  79214. * @param leftStickY The y component of the left joystick
  79215. * @param rightStickX The x component of the right joystick
  79216. * @param rightStickY The y component of the right joystick
  79217. */
  79218. function Gamepad(
  79219. /**
  79220. * The id of the gamepad
  79221. */
  79222. id,
  79223. /**
  79224. * The index of the gamepad
  79225. */
  79226. index,
  79227. /**
  79228. * The browser gamepad
  79229. */
  79230. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  79231. if (leftStickX === void 0) { leftStickX = 0; }
  79232. if (leftStickY === void 0) { leftStickY = 1; }
  79233. if (rightStickX === void 0) { rightStickX = 2; }
  79234. if (rightStickY === void 0) { rightStickY = 3; }
  79235. this.id = id;
  79236. this.index = index;
  79237. this.browserGamepad = browserGamepad;
  79238. this._leftStick = { x: 0, y: 0 };
  79239. this._rightStick = { x: 0, y: 0 };
  79240. /** @hidden */
  79241. this._isConnected = true;
  79242. /**
  79243. * Specifies whether the left control stick should be Y-inverted
  79244. */
  79245. this._invertLeftStickY = false;
  79246. this.type = Gamepad.GAMEPAD;
  79247. this._leftStickAxisX = leftStickX;
  79248. this._leftStickAxisY = leftStickY;
  79249. this._rightStickAxisX = rightStickX;
  79250. this._rightStickAxisY = rightStickY;
  79251. if (this.browserGamepad.axes.length >= 2) {
  79252. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  79253. }
  79254. if (this.browserGamepad.axes.length >= 4) {
  79255. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  79256. }
  79257. }
  79258. Object.defineProperty(Gamepad.prototype, "isConnected", {
  79259. /**
  79260. * Specifies if the gamepad has been connected
  79261. */
  79262. get: function () {
  79263. return this._isConnected;
  79264. },
  79265. enumerable: true,
  79266. configurable: true
  79267. });
  79268. /**
  79269. * Callback triggered when the left joystick has changed
  79270. * @param callback
  79271. */
  79272. Gamepad.prototype.onleftstickchanged = function (callback) {
  79273. this._onleftstickchanged = callback;
  79274. };
  79275. /**
  79276. * Callback triggered when the right joystick has changed
  79277. * @param callback
  79278. */
  79279. Gamepad.prototype.onrightstickchanged = function (callback) {
  79280. this._onrightstickchanged = callback;
  79281. };
  79282. Object.defineProperty(Gamepad.prototype, "leftStick", {
  79283. /**
  79284. * Gets the left joystick
  79285. */
  79286. get: function () {
  79287. return this._leftStick;
  79288. },
  79289. /**
  79290. * Sets the left joystick values
  79291. */
  79292. set: function (newValues) {
  79293. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  79294. this._onleftstickchanged(newValues);
  79295. }
  79296. this._leftStick = newValues;
  79297. },
  79298. enumerable: true,
  79299. configurable: true
  79300. });
  79301. Object.defineProperty(Gamepad.prototype, "rightStick", {
  79302. /**
  79303. * Gets the right joystick
  79304. */
  79305. get: function () {
  79306. return this._rightStick;
  79307. },
  79308. /**
  79309. * Sets the right joystick value
  79310. */
  79311. set: function (newValues) {
  79312. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  79313. this._onrightstickchanged(newValues);
  79314. }
  79315. this._rightStick = newValues;
  79316. },
  79317. enumerable: true,
  79318. configurable: true
  79319. });
  79320. /**
  79321. * Updates the gamepad joystick positions
  79322. */
  79323. Gamepad.prototype.update = function () {
  79324. if (this._leftStick) {
  79325. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  79326. if (this._invertLeftStickY) {
  79327. this.leftStick.y *= -1;
  79328. }
  79329. }
  79330. if (this._rightStick) {
  79331. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  79332. }
  79333. };
  79334. /**
  79335. * Disposes the gamepad
  79336. */
  79337. Gamepad.prototype.dispose = function () {
  79338. };
  79339. /**
  79340. * Represents a gamepad controller
  79341. */
  79342. Gamepad.GAMEPAD = 0;
  79343. /**
  79344. * Represents a generic controller
  79345. */
  79346. Gamepad.GENERIC = 1;
  79347. /**
  79348. * Represents an XBox controller
  79349. */
  79350. Gamepad.XBOX = 2;
  79351. /**
  79352. * Represents a pose-enabled controller
  79353. */
  79354. Gamepad.POSE_ENABLED = 3;
  79355. return Gamepad;
  79356. }());
  79357. BABYLON.Gamepad = Gamepad;
  79358. /**
  79359. * Represents a generic gamepad
  79360. */
  79361. var GenericPad = /** @class */ (function (_super) {
  79362. __extends(GenericPad, _super);
  79363. /**
  79364. * Initializes the generic gamepad
  79365. * @param id The id of the generic gamepad
  79366. * @param index The index of the generic gamepad
  79367. * @param browserGamepad The browser gamepad
  79368. */
  79369. function GenericPad(id, index, browserGamepad) {
  79370. var _this = _super.call(this, id, index, browserGamepad) || this;
  79371. /**
  79372. * Observable triggered when a button has been pressed
  79373. */
  79374. _this.onButtonDownObservable = new BABYLON.Observable();
  79375. /**
  79376. * Observable triggered when a button has been released
  79377. */
  79378. _this.onButtonUpObservable = new BABYLON.Observable();
  79379. _this.type = Gamepad.GENERIC;
  79380. _this._buttons = new Array(browserGamepad.buttons.length);
  79381. return _this;
  79382. }
  79383. /**
  79384. * Callback triggered when a button has been pressed
  79385. * @param callback Called when a button has been pressed
  79386. */
  79387. GenericPad.prototype.onbuttondown = function (callback) {
  79388. this._onbuttondown = callback;
  79389. };
  79390. /**
  79391. * Callback triggered when a button has been released
  79392. * @param callback Called when a button has been released
  79393. */
  79394. GenericPad.prototype.onbuttonup = function (callback) {
  79395. this._onbuttonup = callback;
  79396. };
  79397. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  79398. if (newValue !== currentValue) {
  79399. if (newValue === 1) {
  79400. if (this._onbuttondown) {
  79401. this._onbuttondown(buttonIndex);
  79402. }
  79403. this.onButtonDownObservable.notifyObservers(buttonIndex);
  79404. }
  79405. if (newValue === 0) {
  79406. if (this._onbuttonup) {
  79407. this._onbuttonup(buttonIndex);
  79408. }
  79409. this.onButtonUpObservable.notifyObservers(buttonIndex);
  79410. }
  79411. }
  79412. return newValue;
  79413. };
  79414. /**
  79415. * Updates the generic gamepad
  79416. */
  79417. GenericPad.prototype.update = function () {
  79418. _super.prototype.update.call(this);
  79419. for (var index = 0; index < this._buttons.length; index++) {
  79420. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  79421. }
  79422. };
  79423. /**
  79424. * Disposes the generic gamepad
  79425. */
  79426. GenericPad.prototype.dispose = function () {
  79427. _super.prototype.dispose.call(this);
  79428. this.onButtonDownObservable.clear();
  79429. this.onButtonUpObservable.clear();
  79430. };
  79431. return GenericPad;
  79432. }(Gamepad));
  79433. BABYLON.GenericPad = GenericPad;
  79434. })(BABYLON || (BABYLON = {}));
  79435. //# sourceMappingURL=babylon.gamepad.js.map
  79436. var BABYLON;
  79437. (function (BABYLON) {
  79438. /**
  79439. * Defines supported buttons for XBox360 compatible gamepads
  79440. */
  79441. var Xbox360Button;
  79442. (function (Xbox360Button) {
  79443. /** A */
  79444. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  79445. /** B */
  79446. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  79447. /** X */
  79448. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  79449. /** Y */
  79450. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  79451. /** Start */
  79452. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  79453. /** Back */
  79454. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  79455. /** Left button */
  79456. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  79457. /** Right button */
  79458. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  79459. /** Left stick */
  79460. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  79461. /** Right stick */
  79462. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  79463. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  79464. /** Defines values for XBox360 DPad */
  79465. var Xbox360Dpad;
  79466. (function (Xbox360Dpad) {
  79467. /** Up */
  79468. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  79469. /** Down */
  79470. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  79471. /** Left */
  79472. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  79473. /** Right */
  79474. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  79475. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  79476. /**
  79477. * Defines a XBox360 gamepad
  79478. */
  79479. var Xbox360Pad = /** @class */ (function (_super) {
  79480. __extends(Xbox360Pad, _super);
  79481. /**
  79482. * Creates a new XBox360 gamepad object
  79483. * @param id defines the id of this gamepad
  79484. * @param index defines its index
  79485. * @param gamepad defines the internal HTML gamepad object
  79486. * @param xboxOne defines if it is a XBox One gamepad
  79487. */
  79488. function Xbox360Pad(id, index, gamepad, xboxOne) {
  79489. if (xboxOne === void 0) { xboxOne = false; }
  79490. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  79491. _this._leftTrigger = 0;
  79492. _this._rightTrigger = 0;
  79493. /** Observable raised when a button is pressed */
  79494. _this.onButtonDownObservable = new BABYLON.Observable();
  79495. /** Observable raised when a button is released */
  79496. _this.onButtonUpObservable = new BABYLON.Observable();
  79497. /** Observable raised when a pad is pressed */
  79498. _this.onPadDownObservable = new BABYLON.Observable();
  79499. /** Observable raised when a pad is released */
  79500. _this.onPadUpObservable = new BABYLON.Observable();
  79501. _this._buttonA = 0;
  79502. _this._buttonB = 0;
  79503. _this._buttonX = 0;
  79504. _this._buttonY = 0;
  79505. _this._buttonBack = 0;
  79506. _this._buttonStart = 0;
  79507. _this._buttonLB = 0;
  79508. _this._buttonRB = 0;
  79509. _this._buttonLeftStick = 0;
  79510. _this._buttonRightStick = 0;
  79511. _this._dPadUp = 0;
  79512. _this._dPadDown = 0;
  79513. _this._dPadLeft = 0;
  79514. _this._dPadRight = 0;
  79515. _this._isXboxOnePad = false;
  79516. _this.type = BABYLON.Gamepad.XBOX;
  79517. _this._isXboxOnePad = xboxOne;
  79518. return _this;
  79519. }
  79520. /**
  79521. * Defines the callback to call when left trigger is pressed
  79522. * @param callback defines the callback to use
  79523. */
  79524. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  79525. this._onlefttriggerchanged = callback;
  79526. };
  79527. /**
  79528. * Defines the callback to call when right trigger is pressed
  79529. * @param callback defines the callback to use
  79530. */
  79531. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  79532. this._onrighttriggerchanged = callback;
  79533. };
  79534. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  79535. /**
  79536. * Gets the left trigger value
  79537. */
  79538. get: function () {
  79539. return this._leftTrigger;
  79540. },
  79541. /**
  79542. * Sets the left trigger value
  79543. */
  79544. set: function (newValue) {
  79545. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  79546. this._onlefttriggerchanged(newValue);
  79547. }
  79548. this._leftTrigger = newValue;
  79549. },
  79550. enumerable: true,
  79551. configurable: true
  79552. });
  79553. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  79554. /**
  79555. * Gets the right trigger value
  79556. */
  79557. get: function () {
  79558. return this._rightTrigger;
  79559. },
  79560. /**
  79561. * Sets the right trigger value
  79562. */
  79563. set: function (newValue) {
  79564. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  79565. this._onrighttriggerchanged(newValue);
  79566. }
  79567. this._rightTrigger = newValue;
  79568. },
  79569. enumerable: true,
  79570. configurable: true
  79571. });
  79572. /**
  79573. * Defines the callback to call when a button is pressed
  79574. * @param callback defines the callback to use
  79575. */
  79576. Xbox360Pad.prototype.onbuttondown = function (callback) {
  79577. this._onbuttondown = callback;
  79578. };
  79579. /**
  79580. * Defines the callback to call when a button is released
  79581. * @param callback defines the callback to use
  79582. */
  79583. Xbox360Pad.prototype.onbuttonup = function (callback) {
  79584. this._onbuttonup = callback;
  79585. };
  79586. /**
  79587. * Defines the callback to call when a pad is pressed
  79588. * @param callback defines the callback to use
  79589. */
  79590. Xbox360Pad.prototype.ondpaddown = function (callback) {
  79591. this._ondpaddown = callback;
  79592. };
  79593. /**
  79594. * Defines the callback to call when a pad is released
  79595. * @param callback defines the callback to use
  79596. */
  79597. Xbox360Pad.prototype.ondpadup = function (callback) {
  79598. this._ondpadup = callback;
  79599. };
  79600. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  79601. if (newValue !== currentValue) {
  79602. if (newValue === 1) {
  79603. if (this._onbuttondown) {
  79604. this._onbuttondown(buttonType);
  79605. }
  79606. this.onButtonDownObservable.notifyObservers(buttonType);
  79607. }
  79608. if (newValue === 0) {
  79609. if (this._onbuttonup) {
  79610. this._onbuttonup(buttonType);
  79611. }
  79612. this.onButtonUpObservable.notifyObservers(buttonType);
  79613. }
  79614. }
  79615. return newValue;
  79616. };
  79617. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  79618. if (newValue !== currentValue) {
  79619. if (newValue === 1) {
  79620. if (this._ondpaddown) {
  79621. this._ondpaddown(buttonType);
  79622. }
  79623. this.onPadDownObservable.notifyObservers(buttonType);
  79624. }
  79625. if (newValue === 0) {
  79626. if (this._ondpadup) {
  79627. this._ondpadup(buttonType);
  79628. }
  79629. this.onPadUpObservable.notifyObservers(buttonType);
  79630. }
  79631. }
  79632. return newValue;
  79633. };
  79634. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  79635. /**
  79636. * Gets the value of the `A` button
  79637. */
  79638. get: function () {
  79639. return this._buttonA;
  79640. },
  79641. /**
  79642. * Sets the value of the `A` button
  79643. */
  79644. set: function (value) {
  79645. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  79646. },
  79647. enumerable: true,
  79648. configurable: true
  79649. });
  79650. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  79651. /**
  79652. * Gets the value of the `B` button
  79653. */
  79654. get: function () {
  79655. return this._buttonB;
  79656. },
  79657. /**
  79658. * Sets the value of the `B` button
  79659. */
  79660. set: function (value) {
  79661. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  79662. },
  79663. enumerable: true,
  79664. configurable: true
  79665. });
  79666. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  79667. /**
  79668. * Gets the value of the `X` button
  79669. */
  79670. get: function () {
  79671. return this._buttonX;
  79672. },
  79673. /**
  79674. * Sets the value of the `X` button
  79675. */
  79676. set: function (value) {
  79677. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  79678. },
  79679. enumerable: true,
  79680. configurable: true
  79681. });
  79682. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  79683. /**
  79684. * Gets the value of the `Y` button
  79685. */
  79686. get: function () {
  79687. return this._buttonY;
  79688. },
  79689. /**
  79690. * Sets the value of the `Y` button
  79691. */
  79692. set: function (value) {
  79693. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  79694. },
  79695. enumerable: true,
  79696. configurable: true
  79697. });
  79698. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  79699. /**
  79700. * Gets the value of the `Start` button
  79701. */
  79702. get: function () {
  79703. return this._buttonStart;
  79704. },
  79705. /**
  79706. * Sets the value of the `Start` button
  79707. */
  79708. set: function (value) {
  79709. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  79710. },
  79711. enumerable: true,
  79712. configurable: true
  79713. });
  79714. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  79715. /**
  79716. * Gets the value of the `Back` button
  79717. */
  79718. get: function () {
  79719. return this._buttonBack;
  79720. },
  79721. /**
  79722. * Sets the value of the `Back` button
  79723. */
  79724. set: function (value) {
  79725. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  79726. },
  79727. enumerable: true,
  79728. configurable: true
  79729. });
  79730. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  79731. /**
  79732. * Gets the value of the `Left` button
  79733. */
  79734. get: function () {
  79735. return this._buttonLB;
  79736. },
  79737. /**
  79738. * Sets the value of the `Left` button
  79739. */
  79740. set: function (value) {
  79741. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  79742. },
  79743. enumerable: true,
  79744. configurable: true
  79745. });
  79746. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  79747. /**
  79748. * Gets the value of the `Right` button
  79749. */
  79750. get: function () {
  79751. return this._buttonRB;
  79752. },
  79753. /**
  79754. * Sets the value of the `Right` button
  79755. */
  79756. set: function (value) {
  79757. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  79758. },
  79759. enumerable: true,
  79760. configurable: true
  79761. });
  79762. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  79763. /**
  79764. * Gets the value of the Left joystick
  79765. */
  79766. get: function () {
  79767. return this._buttonLeftStick;
  79768. },
  79769. /**
  79770. * Sets the value of the Left joystick
  79771. */
  79772. set: function (value) {
  79773. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  79774. },
  79775. enumerable: true,
  79776. configurable: true
  79777. });
  79778. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  79779. /**
  79780. * Gets the value of the Right joystick
  79781. */
  79782. get: function () {
  79783. return this._buttonRightStick;
  79784. },
  79785. /**
  79786. * Sets the value of the Right joystick
  79787. */
  79788. set: function (value) {
  79789. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  79790. },
  79791. enumerable: true,
  79792. configurable: true
  79793. });
  79794. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  79795. /**
  79796. * Gets the value of D-pad up
  79797. */
  79798. get: function () {
  79799. return this._dPadUp;
  79800. },
  79801. /**
  79802. * Sets the value of D-pad up
  79803. */
  79804. set: function (value) {
  79805. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  79806. },
  79807. enumerable: true,
  79808. configurable: true
  79809. });
  79810. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  79811. /**
  79812. * Gets the value of D-pad down
  79813. */
  79814. get: function () {
  79815. return this._dPadDown;
  79816. },
  79817. /**
  79818. * Sets the value of D-pad down
  79819. */
  79820. set: function (value) {
  79821. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  79822. },
  79823. enumerable: true,
  79824. configurable: true
  79825. });
  79826. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  79827. /**
  79828. * Gets the value of D-pad left
  79829. */
  79830. get: function () {
  79831. return this._dPadLeft;
  79832. },
  79833. /**
  79834. * Sets the value of D-pad left
  79835. */
  79836. set: function (value) {
  79837. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  79838. },
  79839. enumerable: true,
  79840. configurable: true
  79841. });
  79842. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  79843. /**
  79844. * Gets the value of D-pad right
  79845. */
  79846. get: function () {
  79847. return this._dPadRight;
  79848. },
  79849. /**
  79850. * Sets the value of D-pad right
  79851. */
  79852. set: function (value) {
  79853. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  79854. },
  79855. enumerable: true,
  79856. configurable: true
  79857. });
  79858. /**
  79859. * Force the gamepad to synchronize with device values
  79860. */
  79861. Xbox360Pad.prototype.update = function () {
  79862. _super.prototype.update.call(this);
  79863. if (this._isXboxOnePad) {
  79864. this.buttonA = this.browserGamepad.buttons[0].value;
  79865. this.buttonB = this.browserGamepad.buttons[1].value;
  79866. this.buttonX = this.browserGamepad.buttons[2].value;
  79867. this.buttonY = this.browserGamepad.buttons[3].value;
  79868. this.buttonLB = this.browserGamepad.buttons[4].value;
  79869. this.buttonRB = this.browserGamepad.buttons[5].value;
  79870. this.leftTrigger = this.browserGamepad.axes[2];
  79871. this.rightTrigger = this.browserGamepad.axes[5];
  79872. this.buttonBack = this.browserGamepad.buttons[9].value;
  79873. this.buttonStart = this.browserGamepad.buttons[8].value;
  79874. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  79875. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  79876. this.dPadUp = this.browserGamepad.buttons[11].value;
  79877. this.dPadDown = this.browserGamepad.buttons[12].value;
  79878. this.dPadLeft = this.browserGamepad.buttons[13].value;
  79879. this.dPadRight = this.browserGamepad.buttons[14].value;
  79880. }
  79881. else {
  79882. this.buttonA = this.browserGamepad.buttons[0].value;
  79883. this.buttonB = this.browserGamepad.buttons[1].value;
  79884. this.buttonX = this.browserGamepad.buttons[2].value;
  79885. this.buttonY = this.browserGamepad.buttons[3].value;
  79886. this.buttonLB = this.browserGamepad.buttons[4].value;
  79887. this.buttonRB = this.browserGamepad.buttons[5].value;
  79888. this.leftTrigger = this.browserGamepad.buttons[6].value;
  79889. this.rightTrigger = this.browserGamepad.buttons[7].value;
  79890. this.buttonBack = this.browserGamepad.buttons[8].value;
  79891. this.buttonStart = this.browserGamepad.buttons[9].value;
  79892. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  79893. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  79894. this.dPadUp = this.browserGamepad.buttons[12].value;
  79895. this.dPadDown = this.browserGamepad.buttons[13].value;
  79896. this.dPadLeft = this.browserGamepad.buttons[14].value;
  79897. this.dPadRight = this.browserGamepad.buttons[15].value;
  79898. }
  79899. };
  79900. /**
  79901. * Disposes the gamepad
  79902. */
  79903. Xbox360Pad.prototype.dispose = function () {
  79904. _super.prototype.dispose.call(this);
  79905. this.onButtonDownObservable.clear();
  79906. this.onButtonUpObservable.clear();
  79907. this.onPadDownObservable.clear();
  79908. this.onPadUpObservable.clear();
  79909. };
  79910. return Xbox360Pad;
  79911. }(BABYLON.Gamepad));
  79912. BABYLON.Xbox360Pad = Xbox360Pad;
  79913. })(BABYLON || (BABYLON = {}));
  79914. //# sourceMappingURL=babylon.xboxGamepad.js.map
  79915. var BABYLON;
  79916. (function (BABYLON) {
  79917. /**
  79918. * Defines the types of pose enabled controllers that are supported
  79919. */
  79920. var PoseEnabledControllerType;
  79921. (function (PoseEnabledControllerType) {
  79922. /**
  79923. * HTC Vive
  79924. */
  79925. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  79926. /**
  79927. * Oculus Rift
  79928. */
  79929. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  79930. /**
  79931. * Windows mixed reality
  79932. */
  79933. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  79934. /**
  79935. * Samsung gear VR
  79936. */
  79937. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  79938. /**
  79939. * Google Daydream
  79940. */
  79941. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  79942. /**
  79943. * Generic
  79944. */
  79945. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  79946. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  79947. /**
  79948. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79949. */
  79950. var PoseEnabledControllerHelper = /** @class */ (function () {
  79951. function PoseEnabledControllerHelper() {
  79952. }
  79953. /**
  79954. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79955. * @param vrGamepad the gamepad to initialized
  79956. * @returns a vr controller of the type the gamepad identified as
  79957. */
  79958. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  79959. // Oculus Touch
  79960. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  79961. return new BABYLON.OculusTouchController(vrGamepad);
  79962. }
  79963. // Windows Mixed Reality controllers
  79964. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  79965. return new BABYLON.WindowsMotionController(vrGamepad);
  79966. }
  79967. // HTC Vive
  79968. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  79969. return new BABYLON.ViveController(vrGamepad);
  79970. }
  79971. // Samsung/Oculus Gear VR or Oculus Go
  79972. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  79973. return new BABYLON.GearVRController(vrGamepad);
  79974. }
  79975. // Google Daydream
  79976. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  79977. return new BABYLON.DaydreamController(vrGamepad);
  79978. }
  79979. // Generic
  79980. else {
  79981. return new BABYLON.GenericController(vrGamepad);
  79982. }
  79983. };
  79984. return PoseEnabledControllerHelper;
  79985. }());
  79986. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  79987. /**
  79988. * Defines the PoseEnabledController object that contains state of a vr capable controller
  79989. */
  79990. var PoseEnabledController = /** @class */ (function (_super) {
  79991. __extends(PoseEnabledController, _super);
  79992. /**
  79993. * Creates a new PoseEnabledController from a gamepad
  79994. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  79995. */
  79996. function PoseEnabledController(browserGamepad) {
  79997. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  79998. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79999. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80000. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  80001. /**
  80002. * The device position in babylon space
  80003. */
  80004. _this.devicePosition = BABYLON.Vector3.Zero();
  80005. /**
  80006. * The device rotation in babylon space
  80007. */
  80008. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  80009. /**
  80010. * The scale factor of the device in babylon space
  80011. */
  80012. _this.deviceScaleFactor = 1;
  80013. // Used to convert 6dof controllers to 3dof
  80014. _this._trackPosition = true;
  80015. _this._maxRotationDistFromHeadset = Math.PI / 5;
  80016. _this._draggedRoomRotation = 0;
  80017. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  80018. /**
  80019. * Internal, matrix used to convert room space to babylon space
  80020. * @hidden
  80021. */
  80022. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80023. /**
  80024. * Node to be used when casting a ray from the controller
  80025. * @hidden
  80026. */
  80027. _this._pointingPoseNode = null;
  80028. _this._workingMatrix = BABYLON.Matrix.Identity();
  80029. /**
  80030. * @hidden
  80031. */
  80032. _this._meshAttachedObservable = new BABYLON.Observable();
  80033. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  80034. _this.controllerType = PoseEnabledControllerType.GENERIC;
  80035. _this.position = BABYLON.Vector3.Zero();
  80036. _this.rotationQuaternion = new BABYLON.Quaternion();
  80037. _this._calculatedPosition = BABYLON.Vector3.Zero();
  80038. _this._calculatedRotation = new BABYLON.Quaternion();
  80039. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  80040. return _this;
  80041. }
  80042. /**
  80043. * @hidden
  80044. */
  80045. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  80046. if (this._trackPosition) {
  80047. this._calculatedPosition.copyFrom(fixedPosition);
  80048. this._trackPosition = false;
  80049. }
  80050. };
  80051. /**
  80052. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  80053. */
  80054. PoseEnabledController.prototype.update = function () {
  80055. _super.prototype.update.call(this);
  80056. this._updatePoseAndMesh();
  80057. };
  80058. /**
  80059. * Updates only the pose device and mesh without doing any button event checking
  80060. */
  80061. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  80062. var pose = this.browserGamepad.pose;
  80063. this.updateFromDevice(pose);
  80064. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  80065. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  80066. camera._computeDevicePosition();
  80067. this._deviceToWorld.setTranslation(camera.devicePosition);
  80068. if (camera.deviceRotationQuaternion) {
  80069. var camera = camera;
  80070. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  80071. // Find the radian distance away that the headset is from the controllers rotation
  80072. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  80073. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  80074. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  80075. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  80076. this._draggedRoomRotation += rotationAmount;
  80077. // Rotate controller around headset
  80078. var sin = Math.sin(-rotationAmount);
  80079. var cos = Math.cos(-rotationAmount);
  80080. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  80081. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  80082. }
  80083. }
  80084. }
  80085. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  80086. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  80087. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80088. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  80089. if (this._mesh) {
  80090. this._mesh.position.copyFrom(this.devicePosition);
  80091. if (this._mesh.rotationQuaternion) {
  80092. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  80093. }
  80094. }
  80095. };
  80096. /**
  80097. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  80098. * @param poseData raw pose fromthe device
  80099. */
  80100. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  80101. if (poseData) {
  80102. this.rawPose = poseData;
  80103. if (poseData.position) {
  80104. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  80105. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  80106. this._deviceRoomPosition.z *= -1;
  80107. }
  80108. if (this._trackPosition) {
  80109. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  80110. }
  80111. this._calculatedPosition.addInPlace(this.position);
  80112. }
  80113. var pose = this.rawPose;
  80114. if (poseData.orientation && pose.orientation) {
  80115. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  80116. if (this._mesh) {
  80117. if (this._mesh.getScene().useRightHandedSystem) {
  80118. this._deviceRoomRotationQuaternion.z *= -1;
  80119. this._deviceRoomRotationQuaternion.w *= -1;
  80120. }
  80121. else {
  80122. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  80123. }
  80124. }
  80125. // if the camera is set, rotate to the camera's rotation
  80126. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  80127. }
  80128. }
  80129. };
  80130. /**
  80131. * Attaches a mesh to the controller
  80132. * @param mesh the mesh to be attached
  80133. */
  80134. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  80135. if (this._mesh) {
  80136. this._mesh.parent = null;
  80137. }
  80138. this._mesh = mesh;
  80139. if (this._poseControlledCamera) {
  80140. this._mesh.parent = this._poseControlledCamera;
  80141. }
  80142. if (!this._mesh.rotationQuaternion) {
  80143. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  80144. }
  80145. // 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
  80146. this._updatePoseAndMesh();
  80147. if (this._pointingPoseNode) {
  80148. var parents = [];
  80149. var obj = this._pointingPoseNode;
  80150. while (obj.parent) {
  80151. parents.push(obj.parent);
  80152. obj = obj.parent;
  80153. }
  80154. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  80155. }
  80156. this._meshAttachedObservable.notifyObservers(mesh);
  80157. };
  80158. /**
  80159. * Attaches the controllers mesh to a camera
  80160. * @param camera the camera the mesh should be attached to
  80161. */
  80162. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  80163. this._poseControlledCamera = camera;
  80164. if (this._mesh) {
  80165. this._mesh.parent = this._poseControlledCamera;
  80166. }
  80167. };
  80168. /**
  80169. * Disposes of the controller
  80170. */
  80171. PoseEnabledController.prototype.dispose = function () {
  80172. if (this._mesh) {
  80173. this._mesh.dispose();
  80174. }
  80175. this._mesh = null;
  80176. _super.prototype.dispose.call(this);
  80177. };
  80178. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  80179. /**
  80180. * The mesh that is attached to the controller
  80181. */
  80182. get: function () {
  80183. return this._mesh;
  80184. },
  80185. enumerable: true,
  80186. configurable: true
  80187. });
  80188. /**
  80189. * Gets the ray of the controller in the direction the controller is pointing
  80190. * @param length the length the resulting ray should be
  80191. * @returns a ray in the direction the controller is pointing
  80192. */
  80193. PoseEnabledController.prototype.getForwardRay = function (length) {
  80194. if (length === void 0) { length = 100; }
  80195. if (!this.mesh) {
  80196. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  80197. }
  80198. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  80199. var origin = m.getTranslation();
  80200. var forward = new BABYLON.Vector3(0, 0, -1);
  80201. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  80202. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  80203. return new BABYLON.Ray(origin, direction, length);
  80204. };
  80205. /**
  80206. * Name of the child mesh that can be used to cast a ray from the controller
  80207. */
  80208. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  80209. return PoseEnabledController;
  80210. }(BABYLON.Gamepad));
  80211. BABYLON.PoseEnabledController = PoseEnabledController;
  80212. })(BABYLON || (BABYLON = {}));
  80213. //# sourceMappingURL=babylon.poseEnabledController.js.map
  80214. var BABYLON;
  80215. (function (BABYLON) {
  80216. /**
  80217. * Defines the WebVRController object that represents controllers tracked in 3D space
  80218. */
  80219. var WebVRController = /** @class */ (function (_super) {
  80220. __extends(WebVRController, _super);
  80221. /**
  80222. * Creates a new WebVRController from a gamepad
  80223. * @param vrGamepad the gamepad that the WebVRController should be created from
  80224. */
  80225. function WebVRController(vrGamepad) {
  80226. var _this = _super.call(this, vrGamepad) || this;
  80227. // Observables
  80228. /**
  80229. * Fired when the trigger state has changed
  80230. */
  80231. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  80232. /**
  80233. * Fired when the main button state has changed
  80234. */
  80235. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  80236. /**
  80237. * Fired when the secondary button state has changed
  80238. */
  80239. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  80240. /**
  80241. * Fired when the pad state has changed
  80242. */
  80243. _this.onPadStateChangedObservable = new BABYLON.Observable();
  80244. /**
  80245. * Fired when controllers stick values have changed
  80246. */
  80247. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  80248. /**
  80249. * X and Y axis corrisponding to the controllers joystick
  80250. */
  80251. _this.pad = { x: 0, y: 0 };
  80252. // avoid GC, store state in a tmp object
  80253. _this._changes = {
  80254. pressChanged: false,
  80255. touchChanged: false,
  80256. valueChanged: false,
  80257. changed: false
  80258. };
  80259. _this._buttons = new Array(vrGamepad.buttons.length);
  80260. _this.hand = vrGamepad.hand;
  80261. return _this;
  80262. }
  80263. /**
  80264. * Fired when a controller button's state has changed
  80265. * @param callback the callback containing the button that was modified
  80266. */
  80267. WebVRController.prototype.onButtonStateChange = function (callback) {
  80268. this._onButtonStateChange = callback;
  80269. };
  80270. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  80271. /**
  80272. * The default controller model for the controller
  80273. */
  80274. get: function () {
  80275. return this._defaultModel;
  80276. },
  80277. enumerable: true,
  80278. configurable: true
  80279. });
  80280. /**
  80281. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  80282. */
  80283. WebVRController.prototype.update = function () {
  80284. _super.prototype.update.call(this);
  80285. for (var index = 0; index < this._buttons.length; index++) {
  80286. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  80287. }
  80288. ;
  80289. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  80290. this.pad.x = this.leftStick.x;
  80291. this.pad.y = this.leftStick.y;
  80292. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  80293. }
  80294. };
  80295. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  80296. if (!newState) {
  80297. newState = {
  80298. pressed: false,
  80299. touched: false,
  80300. value: 0
  80301. };
  80302. }
  80303. if (!currentState) {
  80304. this._buttons[buttonIndex] = {
  80305. pressed: newState.pressed,
  80306. touched: newState.touched,
  80307. value: newState.value
  80308. };
  80309. return;
  80310. }
  80311. this._checkChanges(newState, currentState);
  80312. if (this._changes.changed) {
  80313. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  80314. this._handleButtonChange(buttonIndex, newState, this._changes);
  80315. }
  80316. this._buttons[buttonIndex].pressed = newState.pressed;
  80317. this._buttons[buttonIndex].touched = newState.touched;
  80318. // oculus triggers are never 0, thou not touched.
  80319. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  80320. };
  80321. WebVRController.prototype._checkChanges = function (newState, currentState) {
  80322. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  80323. this._changes.touchChanged = newState.touched !== currentState.touched;
  80324. this._changes.valueChanged = newState.value !== currentState.value;
  80325. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  80326. return this._changes;
  80327. };
  80328. /**
  80329. * Disposes of th webVRCOntroller
  80330. */
  80331. WebVRController.prototype.dispose = function () {
  80332. _super.prototype.dispose.call(this);
  80333. this.onTriggerStateChangedObservable.clear();
  80334. this.onMainButtonStateChangedObservable.clear();
  80335. this.onSecondaryButtonStateChangedObservable.clear();
  80336. this.onPadStateChangedObservable.clear();
  80337. this.onPadValuesChangedObservable.clear();
  80338. };
  80339. return WebVRController;
  80340. }(BABYLON.PoseEnabledController));
  80341. BABYLON.WebVRController = WebVRController;
  80342. })(BABYLON || (BABYLON = {}));
  80343. //# sourceMappingURL=babylon.webVRController.js.map
  80344. var BABYLON;
  80345. (function (BABYLON) {
  80346. /**
  80347. * Oculus Touch Controller
  80348. */
  80349. var OculusTouchController = /** @class */ (function (_super) {
  80350. __extends(OculusTouchController, _super);
  80351. /**
  80352. * Creates a new OculusTouchController from a gamepad
  80353. * @param vrGamepad the gamepad that the controller should be created from
  80354. */
  80355. function OculusTouchController(vrGamepad) {
  80356. var _this = _super.call(this, vrGamepad) || this;
  80357. /**
  80358. * Fired when the secondary trigger on this controller is modified
  80359. */
  80360. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  80361. /**
  80362. * Fired when the thumb rest on this controller is modified
  80363. */
  80364. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  80365. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  80366. return _this;
  80367. }
  80368. /**
  80369. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80370. * @param scene scene in which to add meshes
  80371. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80372. */
  80373. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80374. var _this = this;
  80375. var meshName;
  80376. // Hand
  80377. if (this.hand === 'left') {
  80378. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  80379. }
  80380. else { // Right is the default if no hand is specified
  80381. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  80382. }
  80383. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  80384. /*
  80385. Parent Mesh name: oculus_touch_left
  80386. - body
  80387. - trigger
  80388. - thumbstick
  80389. - grip
  80390. - button_y
  80391. - button_x
  80392. - button_enter
  80393. */
  80394. _this._defaultModel = newMeshes[1];
  80395. _this.attachToMesh(_this._defaultModel);
  80396. if (meshLoaded) {
  80397. meshLoaded(_this._defaultModel);
  80398. }
  80399. });
  80400. };
  80401. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  80402. /**
  80403. * Fired when the A button on this controller is modified
  80404. */
  80405. get: function () {
  80406. if (this.hand === 'right') {
  80407. return this.onMainButtonStateChangedObservable;
  80408. }
  80409. else {
  80410. throw new Error('No A button on left hand');
  80411. }
  80412. },
  80413. enumerable: true,
  80414. configurable: true
  80415. });
  80416. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  80417. /**
  80418. * Fired when the B button on this controller is modified
  80419. */
  80420. get: function () {
  80421. if (this.hand === 'right') {
  80422. return this.onSecondaryButtonStateChangedObservable;
  80423. }
  80424. else {
  80425. throw new Error('No B button on left hand');
  80426. }
  80427. },
  80428. enumerable: true,
  80429. configurable: true
  80430. });
  80431. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  80432. /**
  80433. * Fired when the X button on this controller is modified
  80434. */
  80435. get: function () {
  80436. if (this.hand === 'left') {
  80437. return this.onMainButtonStateChangedObservable;
  80438. }
  80439. else {
  80440. throw new Error('No X button on right hand');
  80441. }
  80442. },
  80443. enumerable: true,
  80444. configurable: true
  80445. });
  80446. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  80447. /**
  80448. * Fired when the Y button on this controller is modified
  80449. */
  80450. get: function () {
  80451. if (this.hand === 'left') {
  80452. return this.onSecondaryButtonStateChangedObservable;
  80453. }
  80454. else {
  80455. throw new Error('No Y button on right hand');
  80456. }
  80457. },
  80458. enumerable: true,
  80459. configurable: true
  80460. });
  80461. /**
  80462. * Called once for each button that changed state since the last frame
  80463. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  80464. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  80465. * 2) secondary trigger (same)
  80466. * 3) A (right) X (left), touch, pressed = value
  80467. * 4) B / Y
  80468. * 5) thumb rest
  80469. * @param buttonIdx Which button index changed
  80470. * @param state New state of the button
  80471. * @param changes Which properties on the state changed since last frame
  80472. */
  80473. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80474. var notifyObject = state; //{ state: state, changes: changes };
  80475. var triggerDirection = this.hand === 'right' ? -1 : 1;
  80476. switch (buttonIdx) {
  80477. case 0:
  80478. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80479. return;
  80480. case 1: // index trigger
  80481. if (this._defaultModel) {
  80482. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  80483. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  80484. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  80485. }
  80486. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80487. return;
  80488. case 2: // secondary trigger
  80489. if (this._defaultModel) {
  80490. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  80491. }
  80492. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  80493. return;
  80494. case 3:
  80495. if (this._defaultModel) {
  80496. if (notifyObject.pressed) {
  80497. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  80498. }
  80499. else {
  80500. (this._defaultModel.getChildren()[1]).position.y = 0;
  80501. }
  80502. }
  80503. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80504. return;
  80505. case 4:
  80506. if (this._defaultModel) {
  80507. if (notifyObject.pressed) {
  80508. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80509. }
  80510. else {
  80511. (this._defaultModel.getChildren()[2]).position.y = 0;
  80512. }
  80513. }
  80514. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80515. return;
  80516. case 5:
  80517. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  80518. return;
  80519. }
  80520. };
  80521. /**
  80522. * Base Url for the controller model.
  80523. */
  80524. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  80525. /**
  80526. * File name for the left controller model.
  80527. */
  80528. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  80529. /**
  80530. * File name for the right controller model.
  80531. */
  80532. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  80533. return OculusTouchController;
  80534. }(BABYLON.WebVRController));
  80535. BABYLON.OculusTouchController = OculusTouchController;
  80536. })(BABYLON || (BABYLON = {}));
  80537. //# sourceMappingURL=babylon.oculusTouchController.js.map
  80538. var BABYLON;
  80539. (function (BABYLON) {
  80540. /**
  80541. * Vive Controller
  80542. */
  80543. var ViveController = /** @class */ (function (_super) {
  80544. __extends(ViveController, _super);
  80545. /**
  80546. * Creates a new ViveController from a gamepad
  80547. * @param vrGamepad the gamepad that the controller should be created from
  80548. */
  80549. function ViveController(vrGamepad) {
  80550. var _this = _super.call(this, vrGamepad) || this;
  80551. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  80552. _this._invertLeftStickY = true;
  80553. return _this;
  80554. }
  80555. /**
  80556. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80557. * @param scene scene in which to add meshes
  80558. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80559. */
  80560. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80561. var _this = this;
  80562. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  80563. /*
  80564. Parent Mesh name: ViveWand
  80565. - body
  80566. - r_gripper
  80567. - l_gripper
  80568. - menu_button
  80569. - system_button
  80570. - trackpad
  80571. - trigger
  80572. - LED
  80573. */
  80574. _this._defaultModel = newMeshes[1];
  80575. _this.attachToMesh(_this._defaultModel);
  80576. if (meshLoaded) {
  80577. meshLoaded(_this._defaultModel);
  80578. }
  80579. });
  80580. };
  80581. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  80582. /**
  80583. * Fired when the left button on this controller is modified
  80584. */
  80585. get: function () {
  80586. return this.onMainButtonStateChangedObservable;
  80587. },
  80588. enumerable: true,
  80589. configurable: true
  80590. });
  80591. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  80592. /**
  80593. * Fired when the right button on this controller is modified
  80594. */
  80595. get: function () {
  80596. return this.onMainButtonStateChangedObservable;
  80597. },
  80598. enumerable: true,
  80599. configurable: true
  80600. });
  80601. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  80602. /**
  80603. * Fired when the menu button on this controller is modified
  80604. */
  80605. get: function () {
  80606. return this.onSecondaryButtonStateChangedObservable;
  80607. },
  80608. enumerable: true,
  80609. configurable: true
  80610. });
  80611. /**
  80612. * Called once for each button that changed state since the last frame
  80613. * Vive mapping:
  80614. * 0: touchpad
  80615. * 1: trigger
  80616. * 2: left AND right buttons
  80617. * 3: menu button
  80618. * @param buttonIdx Which button index changed
  80619. * @param state New state of the button
  80620. * @param changes Which properties on the state changed since last frame
  80621. */
  80622. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80623. var notifyObject = state; //{ state: state, changes: changes };
  80624. switch (buttonIdx) {
  80625. case 0:
  80626. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80627. return;
  80628. case 1: // index trigger
  80629. if (this._defaultModel) {
  80630. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  80631. }
  80632. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80633. return;
  80634. case 2: // left AND right button
  80635. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80636. return;
  80637. case 3:
  80638. if (this._defaultModel) {
  80639. if (notifyObject.pressed) {
  80640. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80641. }
  80642. else {
  80643. (this._defaultModel.getChildren()[2]).position.y = 0;
  80644. }
  80645. }
  80646. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80647. return;
  80648. }
  80649. };
  80650. /**
  80651. * Base Url for the controller model.
  80652. */
  80653. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  80654. /**
  80655. * File name for the controller model.
  80656. */
  80657. ViveController.MODEL_FILENAME = 'wand.babylon';
  80658. return ViveController;
  80659. }(BABYLON.WebVRController));
  80660. BABYLON.ViveController = ViveController;
  80661. })(BABYLON || (BABYLON = {}));
  80662. //# sourceMappingURL=babylon.viveController.js.map
  80663. var BABYLON;
  80664. (function (BABYLON) {
  80665. /**
  80666. * Generic Controller
  80667. */
  80668. var GenericController = /** @class */ (function (_super) {
  80669. __extends(GenericController, _super);
  80670. /**
  80671. * Creates a new GenericController from a gamepad
  80672. * @param vrGamepad the gamepad that the controller should be created from
  80673. */
  80674. function GenericController(vrGamepad) {
  80675. return _super.call(this, vrGamepad) || this;
  80676. }
  80677. /**
  80678. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80679. * @param scene scene in which to add meshes
  80680. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80681. */
  80682. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80683. var _this = this;
  80684. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  80685. _this._defaultModel = newMeshes[1];
  80686. _this.attachToMesh(_this._defaultModel);
  80687. if (meshLoaded) {
  80688. meshLoaded(_this._defaultModel);
  80689. }
  80690. });
  80691. };
  80692. /**
  80693. * Called once for each button that changed state since the last frame
  80694. * @param buttonIdx Which button index changed
  80695. * @param state New state of the button
  80696. * @param changes Which properties on the state changed since last frame
  80697. */
  80698. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80699. console.log("Button id: " + buttonIdx + "state: ");
  80700. console.dir(state);
  80701. };
  80702. /**
  80703. * Base Url for the controller model.
  80704. */
  80705. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80706. /**
  80707. * File name for the controller model.
  80708. */
  80709. GenericController.MODEL_FILENAME = 'generic.babylon';
  80710. return GenericController;
  80711. }(BABYLON.WebVRController));
  80712. BABYLON.GenericController = GenericController;
  80713. })(BABYLON || (BABYLON = {}));
  80714. //# sourceMappingURL=babylon.genericController.js.map
  80715. var BABYLON;
  80716. (function (BABYLON) {
  80717. /**
  80718. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  80719. */
  80720. var LoadedMeshInfo = /** @class */ (function () {
  80721. function LoadedMeshInfo() {
  80722. /**
  80723. * Map of the button meshes contained in the controller
  80724. */
  80725. this.buttonMeshes = {};
  80726. /**
  80727. * Map of the axis meshes contained in the controller
  80728. */
  80729. this.axisMeshes = {};
  80730. }
  80731. return LoadedMeshInfo;
  80732. }());
  80733. /**
  80734. * Defines the WindowsMotionController object that the state of the windows motion controller
  80735. */
  80736. var WindowsMotionController = /** @class */ (function (_super) {
  80737. __extends(WindowsMotionController, _super);
  80738. /**
  80739. * Creates a new WindowsMotionController from a gamepad
  80740. * @param vrGamepad the gamepad that the controller should be created from
  80741. */
  80742. function WindowsMotionController(vrGamepad) {
  80743. var _this = _super.call(this, vrGamepad) || this;
  80744. _this._mapping = {
  80745. // Semantic button names
  80746. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  80747. // A mapping of the button name to glTF model node name
  80748. // that should be transformed by button value.
  80749. buttonMeshNames: {
  80750. 'trigger': 'SELECT',
  80751. 'menu': 'MENU',
  80752. 'grip': 'GRASP',
  80753. 'thumbstick': 'THUMBSTICK_PRESS',
  80754. 'trackpad': 'TOUCHPAD_PRESS'
  80755. },
  80756. // This mapping is used to translate from the Motion Controller to Babylon semantics
  80757. buttonObservableNames: {
  80758. 'trigger': 'onTriggerStateChangedObservable',
  80759. 'menu': 'onSecondaryButtonStateChangedObservable',
  80760. 'grip': 'onMainButtonStateChangedObservable',
  80761. 'thumbstick': 'onPadStateChangedObservable',
  80762. 'trackpad': 'onTrackpadChangedObservable'
  80763. },
  80764. // A mapping of the axis name to glTF model node name
  80765. // that should be transformed by axis value.
  80766. // This array mirrors the browserGamepad.axes array, such that
  80767. // the mesh corresponding to axis 0 is in this array index 0.
  80768. axisMeshNames: [
  80769. 'THUMBSTICK_X',
  80770. 'THUMBSTICK_Y',
  80771. 'TOUCHPAD_TOUCH_X',
  80772. 'TOUCHPAD_TOUCH_Y'
  80773. ],
  80774. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  80775. };
  80776. /**
  80777. * Fired when the trackpad on this controller is clicked
  80778. */
  80779. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  80780. /**
  80781. * Fired when the trackpad on this controller is modified
  80782. */
  80783. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  80784. /**
  80785. * The current x and y values of this controller's trackpad
  80786. */
  80787. _this.trackpad = { x: 0, y: 0 };
  80788. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  80789. _this._loadedMeshInfo = null;
  80790. return _this;
  80791. }
  80792. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  80793. /**
  80794. * Fired when the trigger on this controller is modified
  80795. */
  80796. get: function () {
  80797. return this.onTriggerStateChangedObservable;
  80798. },
  80799. enumerable: true,
  80800. configurable: true
  80801. });
  80802. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  80803. /**
  80804. * Fired when the menu button on this controller is modified
  80805. */
  80806. get: function () {
  80807. return this.onSecondaryButtonStateChangedObservable;
  80808. },
  80809. enumerable: true,
  80810. configurable: true
  80811. });
  80812. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  80813. /**
  80814. * Fired when the grip button on this controller is modified
  80815. */
  80816. get: function () {
  80817. return this.onMainButtonStateChangedObservable;
  80818. },
  80819. enumerable: true,
  80820. configurable: true
  80821. });
  80822. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  80823. /**
  80824. * Fired when the thumbstick button on this controller is modified
  80825. */
  80826. get: function () {
  80827. return this.onPadStateChangedObservable;
  80828. },
  80829. enumerable: true,
  80830. configurable: true
  80831. });
  80832. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  80833. /**
  80834. * Fired when the touchpad button on this controller is modified
  80835. */
  80836. get: function () {
  80837. return this.onTrackpadChangedObservable;
  80838. },
  80839. enumerable: true,
  80840. configurable: true
  80841. });
  80842. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  80843. /**
  80844. * Fired when the touchpad values on this controller are modified
  80845. */
  80846. get: function () {
  80847. return this.onTrackpadValuesChangedObservable;
  80848. },
  80849. enumerable: true,
  80850. configurable: true
  80851. });
  80852. WindowsMotionController.prototype._updateTrackpad = function () {
  80853. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  80854. this.trackpad.x = this.browserGamepad["axes"][2];
  80855. this.trackpad.y = this.browserGamepad["axes"][3];
  80856. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  80857. }
  80858. };
  80859. /**
  80860. * Called once per frame by the engine.
  80861. */
  80862. WindowsMotionController.prototype.update = function () {
  80863. _super.prototype.update.call(this);
  80864. if (this.browserGamepad.axes) {
  80865. this._updateTrackpad();
  80866. // Only need to animate axes if there is a loaded mesh
  80867. if (this._loadedMeshInfo) {
  80868. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  80869. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  80870. }
  80871. }
  80872. }
  80873. };
  80874. /**
  80875. * Called once for each button that changed state since the last frame
  80876. * @param buttonIdx Which button index changed
  80877. * @param state New state of the button
  80878. * @param changes Which properties on the state changed since last frame
  80879. */
  80880. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80881. var buttonName = this._mapping.buttons[buttonIdx];
  80882. if (!buttonName) {
  80883. return;
  80884. }
  80885. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  80886. this._updateTrackpad();
  80887. // Only emit events for buttons that we know how to map from index to name
  80888. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  80889. if (observable) {
  80890. observable.notifyObservers(state);
  80891. }
  80892. this._lerpButtonTransform(buttonName, state.value);
  80893. };
  80894. /**
  80895. * Moves the buttons on the controller mesh based on their current state
  80896. * @param buttonName the name of the button to move
  80897. * @param buttonValue the value of the button which determines the buttons new position
  80898. */
  80899. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  80900. // If there is no loaded mesh, there is nothing to transform.
  80901. if (!this._loadedMeshInfo) {
  80902. return;
  80903. }
  80904. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  80905. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80906. return;
  80907. }
  80908. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  80909. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  80910. };
  80911. /**
  80912. * Moves the axis on the controller mesh based on its current state
  80913. * @param axis the index of the axis
  80914. * @param axisValue the value of the axis which determines the meshes new position
  80915. * @hidden
  80916. */
  80917. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  80918. if (!this._loadedMeshInfo) {
  80919. return;
  80920. }
  80921. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  80922. if (!meshInfo) {
  80923. return;
  80924. }
  80925. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80926. return;
  80927. }
  80928. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  80929. var lerpValue = axisValue * 0.5 + 0.5;
  80930. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  80931. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  80932. };
  80933. /**
  80934. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80935. * @param scene scene in which to add meshes
  80936. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80937. */
  80938. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  80939. var _this = this;
  80940. if (forceDefault === void 0) { forceDefault = false; }
  80941. var path;
  80942. var filename;
  80943. // Checking if GLB loader is present
  80944. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  80945. // Determine the device specific folder based on the ID suffix
  80946. var device = 'default';
  80947. if (this.id && !forceDefault) {
  80948. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  80949. device = ((match && match[0]) || device);
  80950. }
  80951. // Hand
  80952. if (this.hand === 'left') {
  80953. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  80954. }
  80955. else { // Right is the default if no hand is specified
  80956. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  80957. }
  80958. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  80959. }
  80960. else {
  80961. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  80962. path = BABYLON.GenericController.MODEL_BASE_URL;
  80963. filename = BABYLON.GenericController.MODEL_FILENAME;
  80964. }
  80965. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  80966. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  80967. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  80968. if (!_this._loadedMeshInfo) {
  80969. return;
  80970. }
  80971. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  80972. _this.attachToMesh(_this._defaultModel);
  80973. if (meshLoaded) {
  80974. meshLoaded(_this._defaultModel);
  80975. }
  80976. }, null, function (scene, message) {
  80977. BABYLON.Tools.Log(message);
  80978. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  80979. if (!forceDefault) {
  80980. _this.initControllerMesh(scene, meshLoaded, true);
  80981. }
  80982. });
  80983. };
  80984. /**
  80985. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  80986. * can be transformed by button presses and axes values, based on this._mapping.
  80987. *
  80988. * @param scene scene in which the meshes exist
  80989. * @param meshes list of meshes that make up the controller model to process
  80990. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  80991. */
  80992. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  80993. var loadedMeshInfo = null;
  80994. // Create a new mesh to contain the glTF hierarchy
  80995. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  80996. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  80997. var childMesh = null;
  80998. for (var i = 0; i < meshes.length; i++) {
  80999. var mesh = meshes[i];
  81000. if (!mesh.parent) {
  81001. // Exclude controller meshes from picking results
  81002. mesh.isPickable = false;
  81003. // Handle root node, attach to the new parentMesh
  81004. childMesh = mesh;
  81005. break;
  81006. }
  81007. }
  81008. if (childMesh) {
  81009. childMesh.setParent(parentMesh);
  81010. // Create our mesh info. Note that this method will always return non-null.
  81011. loadedMeshInfo = this.createMeshInfo(parentMesh);
  81012. }
  81013. else {
  81014. BABYLON.Tools.Warn('Could not find root node in model file.');
  81015. }
  81016. return loadedMeshInfo;
  81017. };
  81018. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  81019. var loadedMeshInfo = new LoadedMeshInfo();
  81020. var i;
  81021. loadedMeshInfo.rootNode = rootNode;
  81022. // Reset the caches
  81023. loadedMeshInfo.buttonMeshes = {};
  81024. loadedMeshInfo.axisMeshes = {};
  81025. // Button Meshes
  81026. for (i = 0; i < this._mapping.buttons.length; i++) {
  81027. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  81028. if (!buttonMeshName) {
  81029. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  81030. continue;
  81031. }
  81032. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  81033. if (!buttonMesh) {
  81034. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  81035. continue;
  81036. }
  81037. var buttonMeshInfo = {
  81038. index: i,
  81039. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  81040. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  81041. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  81042. };
  81043. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  81044. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  81045. }
  81046. else {
  81047. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  81048. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  81049. '(VALUE: ' + !!buttonMeshInfo.value +
  81050. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  81051. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  81052. ')');
  81053. }
  81054. }
  81055. // Axis Meshes
  81056. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  81057. var axisMeshName = this._mapping.axisMeshNames[i];
  81058. if (!axisMeshName) {
  81059. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  81060. continue;
  81061. }
  81062. var axisMesh = getChildByName(rootNode, axisMeshName);
  81063. if (!axisMesh) {
  81064. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  81065. continue;
  81066. }
  81067. var axisMeshInfo = {
  81068. index: i,
  81069. value: getImmediateChildByName(axisMesh, 'VALUE'),
  81070. min: getImmediateChildByName(axisMesh, 'MIN'),
  81071. max: getImmediateChildByName(axisMesh, 'MAX')
  81072. };
  81073. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  81074. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  81075. }
  81076. else {
  81077. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  81078. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  81079. '(VALUE: ' + !!axisMeshInfo.value +
  81080. ', MIN: ' + !!axisMeshInfo.min +
  81081. ', MAX:' + !!axisMeshInfo.max +
  81082. ')');
  81083. }
  81084. }
  81085. // Pointing Ray
  81086. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  81087. if (!loadedMeshInfo.pointingPoseNode) {
  81088. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  81089. }
  81090. else {
  81091. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  81092. }
  81093. return loadedMeshInfo;
  81094. // Look through all children recursively. This will return null if no mesh exists with the given name.
  81095. function getChildByName(node, name) {
  81096. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  81097. }
  81098. // Look through only immediate children. This will return null if no mesh exists with the given name.
  81099. function getImmediateChildByName(node, name) {
  81100. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  81101. }
  81102. };
  81103. /**
  81104. * Gets the ray of the controller in the direction the controller is pointing
  81105. * @param length the length the resulting ray should be
  81106. * @returns a ray in the direction the controller is pointing
  81107. */
  81108. WindowsMotionController.prototype.getForwardRay = function (length) {
  81109. if (length === void 0) { length = 100; }
  81110. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  81111. return _super.prototype.getForwardRay.call(this, length);
  81112. }
  81113. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  81114. var origin = m.getTranslation();
  81115. var forward = new BABYLON.Vector3(0, 0, -1);
  81116. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81117. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81118. return new BABYLON.Ray(origin, direction, length);
  81119. };
  81120. /**
  81121. * Disposes of the controller
  81122. */
  81123. WindowsMotionController.prototype.dispose = function () {
  81124. _super.prototype.dispose.call(this);
  81125. this.onTrackpadChangedObservable.clear();
  81126. };
  81127. /**
  81128. * The base url used to load the left and right controller models
  81129. */
  81130. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  81131. /**
  81132. * The name of the left controller model file
  81133. */
  81134. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  81135. /**
  81136. * The name of the right controller model file
  81137. */
  81138. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  81139. /**
  81140. * The controller name prefix for this controller type
  81141. */
  81142. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  81143. /**
  81144. * The controller id pattern for this controller type
  81145. */
  81146. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  81147. return WindowsMotionController;
  81148. }(BABYLON.WebVRController));
  81149. BABYLON.WindowsMotionController = WindowsMotionController;
  81150. })(BABYLON || (BABYLON = {}));
  81151. //# sourceMappingURL=babylon.windowsMotionController.js.map
  81152. var BABYLON;
  81153. (function (BABYLON) {
  81154. /**
  81155. * Gear VR Controller
  81156. */
  81157. var GearVRController = /** @class */ (function (_super) {
  81158. __extends(GearVRController, _super);
  81159. /**
  81160. * Creates a new GearVRController from a gamepad
  81161. * @param vrGamepad the gamepad that the controller should be created from
  81162. */
  81163. function GearVRController(vrGamepad) {
  81164. var _this = _super.call(this, vrGamepad) || this;
  81165. _this._buttonIndexToObservableNameMap = [
  81166. 'onTrackpadChangedObservable',
  81167. 'onTriggerStateChangedObservable' // Trigger
  81168. ];
  81169. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  81170. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  81171. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  81172. _this._disableTrackPosition(_this._calculatedPosition);
  81173. return _this;
  81174. }
  81175. /**
  81176. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81177. * @param scene scene in which to add meshes
  81178. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81179. */
  81180. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81181. var _this = this;
  81182. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  81183. // Offset the controller so it will rotate around the users wrist
  81184. var mesh = new BABYLON.Mesh("", scene);
  81185. newMeshes[1].parent = mesh;
  81186. newMeshes[1].position.z = -0.15;
  81187. _this._defaultModel = mesh;
  81188. _this.attachToMesh(_this._defaultModel);
  81189. if (meshLoaded) {
  81190. meshLoaded(_this._defaultModel);
  81191. }
  81192. });
  81193. };
  81194. /**
  81195. * Called once for each button that changed state since the last frame
  81196. * @param buttonIdx Which button index changed
  81197. * @param state New state of the button
  81198. * @param changes Which properties on the state changed since last frame
  81199. */
  81200. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81201. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  81202. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  81203. // Only emit events for buttons that we know how to map from index to observable
  81204. var observable = this[observableName];
  81205. if (observable) {
  81206. observable.notifyObservers(state);
  81207. }
  81208. }
  81209. };
  81210. /**
  81211. * Base Url for the controller model.
  81212. */
  81213. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81214. /**
  81215. * File name for the controller model.
  81216. */
  81217. GearVRController.MODEL_FILENAME = 'generic.babylon';
  81218. /**
  81219. * Gamepad Id prefix used to identify this controller.
  81220. */
  81221. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  81222. return GearVRController;
  81223. }(BABYLON.WebVRController));
  81224. BABYLON.GearVRController = GearVRController;
  81225. })(BABYLON || (BABYLON = {}));
  81226. //# sourceMappingURL=babylon.gearVRController.js.map
  81227. var BABYLON;
  81228. (function (BABYLON) {
  81229. /**
  81230. * Google Daydream controller
  81231. */
  81232. var DaydreamController = /** @class */ (function (_super) {
  81233. __extends(DaydreamController, _super);
  81234. /**
  81235. * Creates a new DaydreamController from a gamepad
  81236. * @param vrGamepad the gamepad that the controller should be created from
  81237. */
  81238. function DaydreamController(vrGamepad) {
  81239. var _this = _super.call(this, vrGamepad) || this;
  81240. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  81241. return _this;
  81242. }
  81243. /**
  81244. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81245. * @param scene scene in which to add meshes
  81246. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81247. */
  81248. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81249. var _this = this;
  81250. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  81251. _this._defaultModel = newMeshes[1];
  81252. _this.attachToMesh(_this._defaultModel);
  81253. if (meshLoaded) {
  81254. meshLoaded(_this._defaultModel);
  81255. }
  81256. });
  81257. };
  81258. /**
  81259. * Called once for each button that changed state since the last frame
  81260. * @param buttonIdx Which button index changed
  81261. * @param state New state of the button
  81262. * @param changes Which properties on the state changed since last frame
  81263. */
  81264. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81265. // Daydream controller only has 1 GamepadButton (on the trackpad).
  81266. if (buttonIdx === 0) {
  81267. var observable = this.onTriggerStateChangedObservable;
  81268. if (observable) {
  81269. observable.notifyObservers(state);
  81270. }
  81271. }
  81272. else {
  81273. // If the app or home buttons are ever made available
  81274. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  81275. }
  81276. };
  81277. /**
  81278. * Base Url for the controller model.
  81279. */
  81280. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81281. /**
  81282. * File name for the controller model.
  81283. */
  81284. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  81285. /**
  81286. * Gamepad Id prefix used to identify Daydream Controller.
  81287. */
  81288. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  81289. return DaydreamController;
  81290. }(BABYLON.WebVRController));
  81291. BABYLON.DaydreamController = DaydreamController;
  81292. })(BABYLON || (BABYLON = {}));
  81293. //# sourceMappingURL=babylon.daydreamController.js.map
  81294. var BABYLON;
  81295. (function (BABYLON) {
  81296. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  81297. get: function () {
  81298. if (!this._gamepadManager) {
  81299. this._gamepadManager = new BABYLON.GamepadManager(this);
  81300. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  81301. if (!component) {
  81302. component = new GamepadSystemSceneComponent(this);
  81303. this._addComponent(component);
  81304. }
  81305. }
  81306. return this._gamepadManager;
  81307. },
  81308. enumerable: true,
  81309. configurable: true
  81310. });
  81311. /**
  81312. * Adds a gamepad to the free camera inputs manager
  81313. */
  81314. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  81315. this.add(new BABYLON.FreeCameraGamepadInput());
  81316. return this;
  81317. };
  81318. /**
  81319. * Adds a gamepad to the arc rotate camera inputs manager
  81320. */
  81321. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  81322. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  81323. return this;
  81324. };
  81325. /**
  81326. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  81327. */
  81328. var GamepadSystemSceneComponent = /** @class */ (function () {
  81329. /**
  81330. * Creates a new instance of the component for the given scene
  81331. * @param scene Defines the scene to register the component in
  81332. */
  81333. function GamepadSystemSceneComponent(scene) {
  81334. /**
  81335. * The component name helpfull to identify the component in the list of scene components.
  81336. */
  81337. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  81338. this.scene = scene;
  81339. }
  81340. /**
  81341. * Registers the component in a given scene
  81342. */
  81343. GamepadSystemSceneComponent.prototype.register = function () {
  81344. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  81345. };
  81346. /**
  81347. * Rebuilds the elements related to this component in case of
  81348. * context lost for instance.
  81349. */
  81350. GamepadSystemSceneComponent.prototype.rebuild = function () {
  81351. // Nothing to do for gamepads
  81352. };
  81353. /**
  81354. * Disposes the component and the associated ressources
  81355. */
  81356. GamepadSystemSceneComponent.prototype.dispose = function () {
  81357. var gamepadManager = this.scene._gamepadManager;
  81358. if (gamepadManager) {
  81359. gamepadManager.dispose();
  81360. this.scene._gamepadManager = null;
  81361. }
  81362. };
  81363. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  81364. var gamepadManager = this.scene._gamepadManager;
  81365. if (gamepadManager && gamepadManager._isMonitoring) {
  81366. gamepadManager._checkGamepadsStatus();
  81367. }
  81368. };
  81369. return GamepadSystemSceneComponent;
  81370. }());
  81371. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  81372. })(BABYLON || (BABYLON = {}));
  81373. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  81374. var BABYLON;
  81375. (function (BABYLON) {
  81376. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  81377. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  81378. });
  81379. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  81380. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  81381. });
  81382. /**
  81383. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  81384. * an arc rotate version arcFollowCamera are available.
  81385. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81386. */
  81387. var FollowCamera = /** @class */ (function (_super) {
  81388. __extends(FollowCamera, _super);
  81389. /**
  81390. * Instantiates the follow camera.
  81391. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81392. * @param name Define the name of the camera in the scene
  81393. * @param position Define the position of the camera
  81394. * @param scene Define the scene the camera belong to
  81395. * @param lockedTarget Define the target of the camera
  81396. */
  81397. function FollowCamera(name, position, scene, lockedTarget) {
  81398. if (lockedTarget === void 0) { lockedTarget = null; }
  81399. var _this = _super.call(this, name, position, scene) || this;
  81400. /**
  81401. * Distance the follow camera should follow an object at
  81402. */
  81403. _this.radius = 12;
  81404. /**
  81405. * Define a rotation offset between the camera and the object it follows
  81406. */
  81407. _this.rotationOffset = 0;
  81408. /**
  81409. * Define a height offset between the camera and the object it follows.
  81410. * It can help following an object from the top (like a car chaing a plane)
  81411. */
  81412. _this.heightOffset = 4;
  81413. /**
  81414. * Define how fast the camera can accelerate to follow it s target.
  81415. */
  81416. _this.cameraAcceleration = 0.05;
  81417. /**
  81418. * Define the speed limit of the camera following an object.
  81419. */
  81420. _this.maxCameraSpeed = 20;
  81421. _this.lockedTarget = lockedTarget;
  81422. return _this;
  81423. }
  81424. FollowCamera.prototype._follow = function (cameraTarget) {
  81425. if (!cameraTarget)
  81426. return;
  81427. var yRotation;
  81428. if (cameraTarget.rotationQuaternion) {
  81429. var rotMatrix = new BABYLON.Matrix();
  81430. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  81431. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  81432. }
  81433. else {
  81434. yRotation = cameraTarget.rotation.y;
  81435. }
  81436. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  81437. var targetPosition = cameraTarget.getAbsolutePosition();
  81438. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  81439. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  81440. var dx = targetX - this.position.x;
  81441. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  81442. var dz = (targetZ) - this.position.z;
  81443. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  81444. var vy = dy * this.cameraAcceleration;
  81445. var vz = dz * this.cameraAcceleration * 2;
  81446. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  81447. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81448. }
  81449. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  81450. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81451. }
  81452. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  81453. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81454. }
  81455. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  81456. this.setTarget(targetPosition);
  81457. };
  81458. /** @hidden */
  81459. FollowCamera.prototype._checkInputs = function () {
  81460. _super.prototype._checkInputs.call(this);
  81461. if (this.lockedTarget) {
  81462. this._follow(this.lockedTarget);
  81463. }
  81464. };
  81465. /**
  81466. * Gets the camera class name.
  81467. * @returns the class name
  81468. */
  81469. FollowCamera.prototype.getClassName = function () {
  81470. return "FollowCamera";
  81471. };
  81472. __decorate([
  81473. BABYLON.serialize()
  81474. ], FollowCamera.prototype, "radius", void 0);
  81475. __decorate([
  81476. BABYLON.serialize()
  81477. ], FollowCamera.prototype, "rotationOffset", void 0);
  81478. __decorate([
  81479. BABYLON.serialize()
  81480. ], FollowCamera.prototype, "heightOffset", void 0);
  81481. __decorate([
  81482. BABYLON.serialize()
  81483. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  81484. __decorate([
  81485. BABYLON.serialize()
  81486. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  81487. __decorate([
  81488. BABYLON.serializeAsMeshReference("lockedTargetId")
  81489. ], FollowCamera.prototype, "lockedTarget", void 0);
  81490. return FollowCamera;
  81491. }(BABYLON.TargetCamera));
  81492. BABYLON.FollowCamera = FollowCamera;
  81493. /**
  81494. * Arc Rotate version of the follow camera.
  81495. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  81496. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81497. */
  81498. var ArcFollowCamera = /** @class */ (function (_super) {
  81499. __extends(ArcFollowCamera, _super);
  81500. /**
  81501. * Instantiates a new ArcFollowCamera
  81502. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81503. * @param name Define the name of the camera
  81504. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  81505. * @param beta Define the rotation angle of the camera around the elevation axis
  81506. * @param radius Define the radius of the camera from its target point
  81507. * @param target Define the target of the camera
  81508. * @param scene Define the scene the camera belongs to
  81509. */
  81510. function ArcFollowCamera(name,
  81511. /** The longitudinal angle of the camera */
  81512. alpha,
  81513. /** The latitudinal angle of the camera */
  81514. beta,
  81515. /** The radius of the camera from its target */
  81516. radius,
  81517. /** Define the camera target (the messh it should follow) */
  81518. target, scene) {
  81519. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  81520. _this.alpha = alpha;
  81521. _this.beta = beta;
  81522. _this.radius = radius;
  81523. _this.target = target;
  81524. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  81525. _this._follow();
  81526. return _this;
  81527. }
  81528. ArcFollowCamera.prototype._follow = function () {
  81529. if (!this.target) {
  81530. return;
  81531. }
  81532. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  81533. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  81534. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  81535. var targetPosition = this.target.getAbsolutePosition();
  81536. this.position = targetPosition.add(this._cartesianCoordinates);
  81537. this.setTarget(targetPosition);
  81538. };
  81539. /** @hidden */
  81540. ArcFollowCamera.prototype._checkInputs = function () {
  81541. _super.prototype._checkInputs.call(this);
  81542. this._follow();
  81543. };
  81544. /**
  81545. * Returns the class name of the object.
  81546. * It is mostly used internally for serialization purposes.
  81547. */
  81548. ArcFollowCamera.prototype.getClassName = function () {
  81549. return "ArcFollowCamera";
  81550. };
  81551. return ArcFollowCamera;
  81552. }(BABYLON.TargetCamera));
  81553. BABYLON.ArcFollowCamera = ArcFollowCamera;
  81554. })(BABYLON || (BABYLON = {}));
  81555. //# sourceMappingURL=babylon.followCamera.js.map
  81556. var BABYLON;
  81557. (function (BABYLON) {
  81558. /**
  81559. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  81560. * which still works and will still be found in many Playgrounds.
  81561. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81562. */
  81563. var UniversalCamera = /** @class */ (function (_super) {
  81564. __extends(UniversalCamera, _super);
  81565. /**
  81566. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  81567. * which still works and will still be found in many Playgrounds.
  81568. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81569. * @param name Define the name of the camera in the scene
  81570. * @param position Define the start position of the camera in the scene
  81571. * @param scene Define the scene the camera belongs to
  81572. */
  81573. function UniversalCamera(name, position, scene) {
  81574. var _this = _super.call(this, name, position, scene) || this;
  81575. _this.inputs.addGamepad();
  81576. return _this;
  81577. }
  81578. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  81579. /**
  81580. * Defines the gamepad rotation sensiblity.
  81581. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81582. */
  81583. get: function () {
  81584. var gamepad = this.inputs.attached["gamepad"];
  81585. if (gamepad)
  81586. return gamepad.gamepadAngularSensibility;
  81587. return 0;
  81588. },
  81589. set: function (value) {
  81590. var gamepad = this.inputs.attached["gamepad"];
  81591. if (gamepad)
  81592. gamepad.gamepadAngularSensibility = value;
  81593. },
  81594. enumerable: true,
  81595. configurable: true
  81596. });
  81597. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  81598. /**
  81599. * Defines the gamepad move sensiblity.
  81600. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81601. */
  81602. get: function () {
  81603. var gamepad = this.inputs.attached["gamepad"];
  81604. if (gamepad)
  81605. return gamepad.gamepadMoveSensibility;
  81606. return 0;
  81607. },
  81608. set: function (value) {
  81609. var gamepad = this.inputs.attached["gamepad"];
  81610. if (gamepad)
  81611. gamepad.gamepadMoveSensibility = value;
  81612. },
  81613. enumerable: true,
  81614. configurable: true
  81615. });
  81616. /**
  81617. * Gets the current object class name.
  81618. * @return the class name
  81619. */
  81620. UniversalCamera.prototype.getClassName = function () {
  81621. return "UniversalCamera";
  81622. };
  81623. return UniversalCamera;
  81624. }(BABYLON.TouchCamera));
  81625. BABYLON.UniversalCamera = UniversalCamera;
  81626. })(BABYLON || (BABYLON = {}));
  81627. //# sourceMappingURL=babylon.universalCamera.js.map
  81628. var BABYLON;
  81629. (function (BABYLON) {
  81630. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  81631. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  81632. });
  81633. /**
  81634. * This represents a FPS type of camera. This is only here for back compat purpose.
  81635. * Please use the UniversalCamera instead as both are identical.
  81636. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81637. */
  81638. var GamepadCamera = /** @class */ (function (_super) {
  81639. __extends(GamepadCamera, _super);
  81640. /**
  81641. * Instantiates a new Gamepad Camera
  81642. * This represents a FPS type of camera. This is only here for back compat purpose.
  81643. * Please use the UniversalCamera instead as both are identical.
  81644. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81645. * @param name Define the name of the camera in the scene
  81646. * @param position Define the start position of the camera in the scene
  81647. * @param scene Define the scene the camera belongs to
  81648. */
  81649. function GamepadCamera(name, position, scene) {
  81650. return _super.call(this, name, position, scene) || this;
  81651. }
  81652. /**
  81653. * Gets the current object class name.
  81654. * @return the class name
  81655. */
  81656. GamepadCamera.prototype.getClassName = function () {
  81657. return "GamepadCamera";
  81658. };
  81659. return GamepadCamera;
  81660. }(BABYLON.UniversalCamera));
  81661. BABYLON.GamepadCamera = GamepadCamera;
  81662. })(BABYLON || (BABYLON = {}));
  81663. //# sourceMappingURL=babylon.gamepadCamera.js.map
  81664. var BABYLON;
  81665. (function (BABYLON) {
  81666. /**
  81667. * PostProcessRenderPipelineManager class
  81668. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81669. */
  81670. var PostProcessRenderPipelineManager = /** @class */ (function () {
  81671. /**
  81672. * Initializes a PostProcessRenderPipelineManager
  81673. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81674. */
  81675. function PostProcessRenderPipelineManager() {
  81676. this._renderPipelines = {};
  81677. }
  81678. /**
  81679. * Adds a pipeline to the manager
  81680. * @param renderPipeline The pipeline to add
  81681. */
  81682. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  81683. this._renderPipelines[renderPipeline._name] = renderPipeline;
  81684. };
  81685. /**
  81686. * Attaches a camera to the pipeline
  81687. * @param renderPipelineName The name of the pipeline to attach to
  81688. * @param cameras the camera to attach
  81689. * @param unique if the camera can be attached multiple times to the pipeline
  81690. */
  81691. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  81692. if (unique === void 0) { unique = false; }
  81693. var renderPipeline = this._renderPipelines[renderPipelineName];
  81694. if (!renderPipeline) {
  81695. return;
  81696. }
  81697. renderPipeline._attachCameras(cameras, unique);
  81698. };
  81699. /**
  81700. * Detaches a camera from the pipeline
  81701. * @param renderPipelineName The name of the pipeline to detach from
  81702. * @param cameras the camera to detach
  81703. */
  81704. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  81705. var renderPipeline = this._renderPipelines[renderPipelineName];
  81706. if (!renderPipeline) {
  81707. return;
  81708. }
  81709. renderPipeline._detachCameras(cameras);
  81710. };
  81711. /**
  81712. * Enables an effect by name on a pipeline
  81713. * @param renderPipelineName the name of the pipeline to enable the effect in
  81714. * @param renderEffectName the name of the effect to enable
  81715. * @param cameras the cameras that the effect should be enabled on
  81716. */
  81717. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81718. var renderPipeline = this._renderPipelines[renderPipelineName];
  81719. if (!renderPipeline) {
  81720. return;
  81721. }
  81722. renderPipeline._enableEffect(renderEffectName, cameras);
  81723. };
  81724. /**
  81725. * Disables an effect by name on a pipeline
  81726. * @param renderPipelineName the name of the pipeline to disable the effect in
  81727. * @param renderEffectName the name of the effect to disable
  81728. * @param cameras the cameras that the effect should be disabled on
  81729. */
  81730. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81731. var renderPipeline = this._renderPipelines[renderPipelineName];
  81732. if (!renderPipeline) {
  81733. return;
  81734. }
  81735. renderPipeline._disableEffect(renderEffectName, cameras);
  81736. };
  81737. /**
  81738. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  81739. */
  81740. PostProcessRenderPipelineManager.prototype.update = function () {
  81741. for (var renderPipelineName in this._renderPipelines) {
  81742. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81743. var pipeline = this._renderPipelines[renderPipelineName];
  81744. if (!pipeline.isSupported) {
  81745. pipeline.dispose();
  81746. delete this._renderPipelines[renderPipelineName];
  81747. }
  81748. else {
  81749. pipeline._update();
  81750. }
  81751. }
  81752. }
  81753. };
  81754. /** @hidden */
  81755. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  81756. for (var renderPipelineName in this._renderPipelines) {
  81757. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81758. var pipeline = this._renderPipelines[renderPipelineName];
  81759. pipeline._rebuild();
  81760. }
  81761. }
  81762. };
  81763. /**
  81764. * Disposes of the manager and pipelines
  81765. */
  81766. PostProcessRenderPipelineManager.prototype.dispose = function () {
  81767. for (var renderPipelineName in this._renderPipelines) {
  81768. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81769. var pipeline = this._renderPipelines[renderPipelineName];
  81770. pipeline.dispose();
  81771. }
  81772. }
  81773. };
  81774. return PostProcessRenderPipelineManager;
  81775. }());
  81776. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  81777. })(BABYLON || (BABYLON = {}));
  81778. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  81779. var BABYLON;
  81780. (function (BABYLON) {
  81781. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  81782. get: function () {
  81783. if (!this._postProcessRenderPipelineManager) {
  81784. // Register the G Buffer component to the scene.
  81785. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  81786. if (!component) {
  81787. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  81788. this._addComponent(component);
  81789. }
  81790. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  81791. }
  81792. return this._postProcessRenderPipelineManager;
  81793. },
  81794. enumerable: true,
  81795. configurable: true
  81796. });
  81797. /**
  81798. * Defines the Render Pipeline scene component responsible to rendering pipelines
  81799. */
  81800. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  81801. /**
  81802. * Creates a new instance of the component for the given scene
  81803. * @param scene Defines the scene to register the component in
  81804. */
  81805. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  81806. /**
  81807. * The component name helpfull to identify the component in the list of scene components.
  81808. */
  81809. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  81810. this.scene = scene;
  81811. }
  81812. /**
  81813. * Registers the component in a given scene
  81814. */
  81815. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  81816. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  81817. };
  81818. /**
  81819. * Rebuilds the elements related to this component in case of
  81820. * context lost for instance.
  81821. */
  81822. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  81823. if (this.scene._postProcessRenderPipelineManager) {
  81824. this.scene._postProcessRenderPipelineManager._rebuild();
  81825. }
  81826. };
  81827. /**
  81828. * Disposes the component and the associated ressources
  81829. */
  81830. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  81831. if (this.scene._postProcessRenderPipelineManager) {
  81832. this.scene._postProcessRenderPipelineManager.dispose();
  81833. }
  81834. };
  81835. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81836. if (this.scene._postProcessRenderPipelineManager) {
  81837. this.scene._postProcessRenderPipelineManager.update();
  81838. }
  81839. };
  81840. return PostProcessRenderPipelineManagerSceneComponent;
  81841. }());
  81842. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  81843. })(BABYLON || (BABYLON = {}));
  81844. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  81845. var BABYLON;
  81846. (function (BABYLON) {
  81847. /**
  81848. * This represents a set of one or more post processes in Babylon.
  81849. * A post process can be used to apply a shader to a texture after it is rendered.
  81850. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81851. */
  81852. var PostProcessRenderEffect = /** @class */ (function () {
  81853. /**
  81854. * Instantiates a post process render effect.
  81855. * A post process can be used to apply a shader to a texture after it is rendered.
  81856. * @param engine The engine the effect is tied to
  81857. * @param name The name of the effect
  81858. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  81859. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  81860. */
  81861. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  81862. this._name = name;
  81863. this._singleInstance = singleInstance || true;
  81864. this._getPostProcesses = getPostProcesses;
  81865. this._cameras = {};
  81866. this._indicesForCamera = {};
  81867. this._postProcesses = {};
  81868. }
  81869. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  81870. /**
  81871. * Checks if all the post processes in the effect are supported.
  81872. */
  81873. get: function () {
  81874. for (var index in this._postProcesses) {
  81875. if (this._postProcesses.hasOwnProperty(index)) {
  81876. var pps = this._postProcesses[index];
  81877. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  81878. if (!pps[ppIndex].isSupported) {
  81879. return false;
  81880. }
  81881. }
  81882. }
  81883. }
  81884. return true;
  81885. },
  81886. enumerable: true,
  81887. configurable: true
  81888. });
  81889. /**
  81890. * Updates the current state of the effect
  81891. * @hidden
  81892. */
  81893. PostProcessRenderEffect.prototype._update = function () {
  81894. };
  81895. /**
  81896. * Attaches the effect on cameras
  81897. * @param cameras The camera to attach to.
  81898. * @hidden
  81899. */
  81900. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  81901. var _this = this;
  81902. var cameraKey;
  81903. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81904. if (!cams) {
  81905. return;
  81906. }
  81907. for (var i = 0; i < cams.length; i++) {
  81908. var camera = cams[i];
  81909. var cameraName = camera.name;
  81910. if (this._singleInstance) {
  81911. cameraKey = 0;
  81912. }
  81913. else {
  81914. cameraKey = cameraName;
  81915. }
  81916. if (!this._postProcesses[cameraKey]) {
  81917. var postProcess = this._getPostProcesses();
  81918. if (postProcess) {
  81919. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  81920. }
  81921. }
  81922. if (!this._indicesForCamera[cameraName]) {
  81923. this._indicesForCamera[cameraName] = [];
  81924. }
  81925. this._postProcesses[cameraKey].forEach(function (postProcess) {
  81926. var index = camera.attachPostProcess(postProcess);
  81927. _this._indicesForCamera[cameraName].push(index);
  81928. });
  81929. if (!this._cameras[cameraName]) {
  81930. this._cameras[cameraName] = camera;
  81931. }
  81932. }
  81933. };
  81934. /**
  81935. * Detatches the effect on cameras
  81936. * @param cameras The camera to detatch from.
  81937. * @hidden
  81938. */
  81939. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  81940. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81941. if (!cams) {
  81942. return;
  81943. }
  81944. for (var i = 0; i < cams.length; i++) {
  81945. var camera = cams[i];
  81946. var cameraName = camera.name;
  81947. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81948. camera.detachPostProcess(postProcess);
  81949. });
  81950. if (this._cameras[cameraName]) {
  81951. //this._indicesForCamera.splice(index, 1);
  81952. this._cameras[cameraName] = null;
  81953. }
  81954. }
  81955. };
  81956. /**
  81957. * Enables the effect on given cameras
  81958. * @param cameras The camera to enable.
  81959. * @hidden
  81960. */
  81961. PostProcessRenderEffect.prototype._enable = function (cameras) {
  81962. var _this = this;
  81963. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81964. if (!cams) {
  81965. return;
  81966. }
  81967. for (var i = 0; i < cams.length; i++) {
  81968. var camera = cams[i];
  81969. var cameraName = camera.name;
  81970. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  81971. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  81972. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81973. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  81974. });
  81975. }
  81976. }
  81977. }
  81978. };
  81979. /**
  81980. * Disables the effect on the given cameras
  81981. * @param cameras The camera to disable.
  81982. * @hidden
  81983. */
  81984. PostProcessRenderEffect.prototype._disable = function (cameras) {
  81985. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81986. if (!cams) {
  81987. return;
  81988. }
  81989. for (var i = 0; i < cams.length; i++) {
  81990. var camera = cams[i];
  81991. var cameraName = camera.name;
  81992. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81993. camera.detachPostProcess(postProcess);
  81994. });
  81995. }
  81996. };
  81997. /**
  81998. * Gets a list of the post processes contained in the effect.
  81999. * @param camera The camera to get the post processes on.
  82000. * @returns The list of the post processes in the effect.
  82001. */
  82002. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  82003. if (this._singleInstance) {
  82004. return this._postProcesses[0];
  82005. }
  82006. else {
  82007. if (!camera) {
  82008. return null;
  82009. }
  82010. return this._postProcesses[camera.name];
  82011. }
  82012. };
  82013. return PostProcessRenderEffect;
  82014. }());
  82015. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  82016. })(BABYLON || (BABYLON = {}));
  82017. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  82018. var BABYLON;
  82019. (function (BABYLON) {
  82020. /**
  82021. * PostProcessRenderPipeline
  82022. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82023. */
  82024. var PostProcessRenderPipeline = /** @class */ (function () {
  82025. /**
  82026. * Initializes a PostProcessRenderPipeline
  82027. * @param engine engine to add the pipeline to
  82028. * @param name name of the pipeline
  82029. */
  82030. function PostProcessRenderPipeline(engine, name) {
  82031. this.engine = engine;
  82032. this._name = name;
  82033. this._renderEffects = {};
  82034. this._renderEffectsForIsolatedPass = new Array();
  82035. this._cameras = [];
  82036. }
  82037. /**
  82038. * "PostProcessRenderPipeline"
  82039. * @returns "PostProcessRenderPipeline"
  82040. */
  82041. PostProcessRenderPipeline.prototype.getClassName = function () {
  82042. return "PostProcessRenderPipeline";
  82043. };
  82044. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  82045. /**
  82046. * If all the render effects in the pipeline are support
  82047. */
  82048. get: function () {
  82049. for (var renderEffectName in this._renderEffects) {
  82050. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82051. if (!this._renderEffects[renderEffectName].isSupported) {
  82052. return false;
  82053. }
  82054. }
  82055. }
  82056. return true;
  82057. },
  82058. enumerable: true,
  82059. configurable: true
  82060. });
  82061. /**
  82062. * Adds an effect to the pipeline
  82063. * @param renderEffect the effect to add
  82064. */
  82065. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  82066. this._renderEffects[renderEffect._name] = renderEffect;
  82067. };
  82068. // private
  82069. /** @hidden */
  82070. PostProcessRenderPipeline.prototype._rebuild = function () {
  82071. };
  82072. /** @hidden */
  82073. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  82074. var renderEffects = this._renderEffects[renderEffectName];
  82075. if (!renderEffects) {
  82076. return;
  82077. }
  82078. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82079. };
  82080. /** @hidden */
  82081. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  82082. var renderEffects = this._renderEffects[renderEffectName];
  82083. if (!renderEffects) {
  82084. return;
  82085. }
  82086. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82087. };
  82088. /** @hidden */
  82089. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  82090. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82091. if (!cams) {
  82092. return;
  82093. }
  82094. var indicesToDelete = [];
  82095. var i;
  82096. for (i = 0; i < cams.length; i++) {
  82097. var camera = cams[i];
  82098. var cameraName = camera.name;
  82099. if (this._cameras.indexOf(camera) === -1) {
  82100. this._cameras[cameraName] = camera;
  82101. }
  82102. else if (unique) {
  82103. indicesToDelete.push(i);
  82104. }
  82105. }
  82106. for (i = 0; i < indicesToDelete.length; i++) {
  82107. cameras.splice(indicesToDelete[i], 1);
  82108. }
  82109. for (var renderEffectName in this._renderEffects) {
  82110. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82111. this._renderEffects[renderEffectName]._attachCameras(cams);
  82112. }
  82113. }
  82114. };
  82115. /** @hidden */
  82116. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  82117. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82118. if (!cams) {
  82119. return;
  82120. }
  82121. for (var renderEffectName in this._renderEffects) {
  82122. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82123. this._renderEffects[renderEffectName]._detachCameras(cams);
  82124. }
  82125. }
  82126. for (var i = 0; i < cams.length; i++) {
  82127. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  82128. }
  82129. };
  82130. /** @hidden */
  82131. PostProcessRenderPipeline.prototype._update = function () {
  82132. for (var renderEffectName in this._renderEffects) {
  82133. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82134. this._renderEffects[renderEffectName]._update();
  82135. }
  82136. }
  82137. for (var i = 0; i < this._cameras.length; i++) {
  82138. var cameraName = this._cameras[i].name;
  82139. if (this._renderEffectsForIsolatedPass[cameraName]) {
  82140. this._renderEffectsForIsolatedPass[cameraName]._update();
  82141. }
  82142. }
  82143. };
  82144. /** @hidden */
  82145. PostProcessRenderPipeline.prototype._reset = function () {
  82146. this._renderEffects = {};
  82147. this._renderEffectsForIsolatedPass = new Array();
  82148. };
  82149. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  82150. // 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)
  82151. var effectKeys = Object.keys(this._renderEffects);
  82152. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  82153. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  82154. if (postProcesses) {
  82155. postProcesses[0].samples = sampleCount;
  82156. return true;
  82157. }
  82158. }
  82159. return false;
  82160. };
  82161. /**
  82162. * Disposes of the pipeline
  82163. */
  82164. PostProcessRenderPipeline.prototype.dispose = function () {
  82165. // Must be implemented by children
  82166. };
  82167. __decorate([
  82168. BABYLON.serialize()
  82169. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  82170. return PostProcessRenderPipeline;
  82171. }());
  82172. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  82173. })(BABYLON || (BABYLON = {}));
  82174. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  82175. var BABYLON;
  82176. (function (BABYLON) {
  82177. /**
  82178. * This represents a depth renderer in Babylon.
  82179. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  82180. */
  82181. var DepthRenderer = /** @class */ (function () {
  82182. /**
  82183. * Instantiates a depth renderer
  82184. * @param scene The scene the renderer belongs to
  82185. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  82186. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  82187. */
  82188. function DepthRenderer(scene, type, camera) {
  82189. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  82190. if (camera === void 0) { camera = null; }
  82191. var _this = this;
  82192. /**
  82193. * Specifiess that the depth renderer will only be used within
  82194. * the camera it is created for.
  82195. * This can help forcing its rendering during the camera processing.
  82196. */
  82197. this.useOnlyInActiveCamera = false;
  82198. this._scene = scene;
  82199. // Register the G Buffer component to the scene.
  82200. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  82201. if (!component) {
  82202. component = new BABYLON.DepthRendererSceneComponent(scene);
  82203. scene._addComponent(component);
  82204. }
  82205. this._camera = camera;
  82206. var engine = scene.getEngine();
  82207. // Render target
  82208. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  82209. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82210. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82211. this._depthMap.refreshRate = 1;
  82212. this._depthMap.renderParticles = false;
  82213. this._depthMap.renderList = null;
  82214. // Camera to get depth map from to support multiple concurrent cameras
  82215. this._depthMap.activeCamera = this._camera;
  82216. this._depthMap.ignoreCameraViewport = true;
  82217. this._depthMap.useCameraPostProcesses = false;
  82218. // set default depth value to 1.0 (far away)
  82219. this._depthMap.onClearObservable.add(function (engine) {
  82220. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  82221. });
  82222. // Custom render function
  82223. var renderSubMesh = function (subMesh) {
  82224. var mesh = subMesh.getRenderingMesh();
  82225. var scene = _this._scene;
  82226. var engine = scene.getEngine();
  82227. var material = subMesh.getMaterial();
  82228. if (!material) {
  82229. return;
  82230. }
  82231. // Culling and reverse (right handed system)
  82232. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  82233. // Managing instances
  82234. var batch = mesh._getInstancesRenderList(subMesh._id);
  82235. if (batch.mustReturn) {
  82236. return;
  82237. }
  82238. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82239. var camera = _this._camera || scene.activeCamera;
  82240. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  82241. engine.enableEffect(_this._effect);
  82242. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  82243. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82244. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  82245. // Alpha test
  82246. if (material && material.needAlphaTesting()) {
  82247. var alphaTexture = material.getAlphaTestTexture();
  82248. if (alphaTexture) {
  82249. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82250. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82251. }
  82252. }
  82253. // Bones
  82254. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82255. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82256. }
  82257. // Draw
  82258. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82259. }
  82260. };
  82261. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82262. var index;
  82263. if (depthOnlySubMeshes.length) {
  82264. engine.setColorWrite(false);
  82265. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82266. renderSubMesh(depthOnlySubMeshes.data[index]);
  82267. }
  82268. engine.setColorWrite(true);
  82269. }
  82270. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82271. renderSubMesh(opaqueSubMeshes.data[index]);
  82272. }
  82273. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82274. renderSubMesh(alphaTestSubMeshes.data[index]);
  82275. }
  82276. };
  82277. }
  82278. /**
  82279. * Creates the depth rendering effect and checks if the effect is ready.
  82280. * @param subMesh The submesh to be used to render the depth map of
  82281. * @param useInstances If multiple world instances should be used
  82282. * @returns if the depth renderer is ready to render the depth map
  82283. */
  82284. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  82285. var material = subMesh.getMaterial();
  82286. if (material.disableDepthWrite) {
  82287. return false;
  82288. }
  82289. var defines = [];
  82290. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82291. var mesh = subMesh.getMesh();
  82292. // Alpha test
  82293. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  82294. defines.push("#define ALPHATEST");
  82295. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82296. attribs.push(BABYLON.VertexBuffer.UVKind);
  82297. defines.push("#define UV1");
  82298. }
  82299. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82300. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82301. defines.push("#define UV2");
  82302. }
  82303. }
  82304. // Bones
  82305. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82306. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82307. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82308. if (mesh.numBoneInfluencers > 4) {
  82309. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82310. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82311. }
  82312. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82313. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82314. }
  82315. else {
  82316. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82317. }
  82318. // Instances
  82319. if (useInstances) {
  82320. defines.push("#define INSTANCES");
  82321. attribs.push("world0");
  82322. attribs.push("world1");
  82323. attribs.push("world2");
  82324. attribs.push("world3");
  82325. }
  82326. // Get correct effect
  82327. var join = defines.join("\n");
  82328. if (this._cachedDefines !== join) {
  82329. this._cachedDefines = join;
  82330. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  82331. }
  82332. return this._effect.isReady();
  82333. };
  82334. /**
  82335. * Gets the texture which the depth map will be written to.
  82336. * @returns The depth map texture
  82337. */
  82338. DepthRenderer.prototype.getDepthMap = function () {
  82339. return this._depthMap;
  82340. };
  82341. /**
  82342. * Disposes of the depth renderer.
  82343. */
  82344. DepthRenderer.prototype.dispose = function () {
  82345. this._depthMap.dispose();
  82346. };
  82347. return DepthRenderer;
  82348. }());
  82349. BABYLON.DepthRenderer = DepthRenderer;
  82350. })(BABYLON || (BABYLON = {}));
  82351. //# sourceMappingURL=babylon.depthRenderer.js.map
  82352. var BABYLON;
  82353. (function (BABYLON) {
  82354. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  82355. camera = camera || this.activeCamera;
  82356. if (!camera) {
  82357. throw "No camera available to enable depth renderer";
  82358. }
  82359. if (!this._depthRenderer) {
  82360. this._depthRenderer = {};
  82361. }
  82362. if (!this._depthRenderer[camera.id]) {
  82363. var textureType = 0;
  82364. if (this.getEngine().getCaps().textureHalfFloatRender) {
  82365. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82366. }
  82367. else if (this.getEngine().getCaps().textureFloatRender) {
  82368. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82369. }
  82370. else {
  82371. throw "Depth renderer does not support int texture type";
  82372. }
  82373. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  82374. }
  82375. return this._depthRenderer[camera.id];
  82376. };
  82377. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  82378. camera = camera || this.activeCamera;
  82379. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  82380. return;
  82381. }
  82382. this._depthRenderer[camera.id].dispose();
  82383. delete this._depthRenderer[camera.id];
  82384. };
  82385. /**
  82386. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  82387. * in several rendering techniques.
  82388. */
  82389. var DepthRendererSceneComponent = /** @class */ (function () {
  82390. /**
  82391. * Creates a new instance of the component for the given scene
  82392. * @param scene Defines the scene to register the component in
  82393. */
  82394. function DepthRendererSceneComponent(scene) {
  82395. /**
  82396. * The component name helpfull to identify the component in the list of scene components.
  82397. */
  82398. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  82399. this.scene = scene;
  82400. }
  82401. /**
  82402. * Registers the component in a given scene
  82403. */
  82404. DepthRendererSceneComponent.prototype.register = function () {
  82405. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  82406. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  82407. };
  82408. /**
  82409. * Rebuilds the elements related to this component in case of
  82410. * context lost for instance.
  82411. */
  82412. DepthRendererSceneComponent.prototype.rebuild = function () {
  82413. // Nothing to do for this component
  82414. };
  82415. /**
  82416. * Disposes the component and the associated ressources
  82417. */
  82418. DepthRendererSceneComponent.prototype.dispose = function () {
  82419. for (var key in this.scene._depthRenderer) {
  82420. this.scene._depthRenderer[key].dispose();
  82421. }
  82422. };
  82423. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82424. if (this.scene._depthRenderer) {
  82425. for (var key in this.scene._depthRenderer) {
  82426. var depthRenderer = this.scene._depthRenderer[key];
  82427. if (!depthRenderer.useOnlyInActiveCamera) {
  82428. renderTargets.push(depthRenderer.getDepthMap());
  82429. }
  82430. }
  82431. }
  82432. };
  82433. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  82434. if (this.scene._depthRenderer) {
  82435. for (var key in this.scene._depthRenderer) {
  82436. var depthRenderer = this.scene._depthRenderer[key];
  82437. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  82438. renderTargets.push(depthRenderer.getDepthMap());
  82439. }
  82440. }
  82441. }
  82442. };
  82443. return DepthRendererSceneComponent;
  82444. }());
  82445. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  82446. })(BABYLON || (BABYLON = {}));
  82447. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  82448. var BABYLON;
  82449. (function (BABYLON) {
  82450. /**
  82451. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  82452. */
  82453. var GeometryBufferRenderer = /** @class */ (function () {
  82454. /**
  82455. * Creates a new G Buffer for the scene
  82456. * @param scene The scene the buffer belongs to
  82457. * @param ratio How big is the buffer related to the main canvas.
  82458. */
  82459. function GeometryBufferRenderer(scene, ratio) {
  82460. if (ratio === void 0) { ratio = 1; }
  82461. this._enablePosition = false;
  82462. this._scene = scene;
  82463. this._ratio = ratio;
  82464. // Register the G Buffer component to the scene.
  82465. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  82466. if (!component) {
  82467. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  82468. scene._addComponent(component);
  82469. }
  82470. // Render target
  82471. this._createRenderTargets();
  82472. }
  82473. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  82474. /**
  82475. * Set the render list (meshes to be rendered) used in the G buffer.
  82476. */
  82477. set: function (meshes) {
  82478. this._multiRenderTarget.renderList = meshes;
  82479. },
  82480. enumerable: true,
  82481. configurable: true
  82482. });
  82483. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  82484. /**
  82485. * Gets wether or not G buffer are supported by the running hardware.
  82486. * This requires draw buffer supports
  82487. */
  82488. get: function () {
  82489. return this._multiRenderTarget.isSupported;
  82490. },
  82491. enumerable: true,
  82492. configurable: true
  82493. });
  82494. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  82495. /**
  82496. * Gets wether or not position are enabled for the G buffer.
  82497. */
  82498. get: function () {
  82499. return this._enablePosition;
  82500. },
  82501. /**
  82502. * Sets wether or not position are enabled for the G buffer.
  82503. */
  82504. set: function (enable) {
  82505. this._enablePosition = enable;
  82506. this.dispose();
  82507. this._createRenderTargets();
  82508. },
  82509. enumerable: true,
  82510. configurable: true
  82511. });
  82512. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  82513. /**
  82514. * Gets the scene associated with the buffer.
  82515. */
  82516. get: function () {
  82517. return this._scene;
  82518. },
  82519. enumerable: true,
  82520. configurable: true
  82521. });
  82522. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  82523. /**
  82524. * Gets the ratio used by the buffer during its creation.
  82525. * How big is the buffer related to the main canvas.
  82526. */
  82527. get: function () {
  82528. return this._ratio;
  82529. },
  82530. enumerable: true,
  82531. configurable: true
  82532. });
  82533. /**
  82534. * Checks wether everything is ready to render a submesh to the G buffer.
  82535. * @param subMesh the submesh to check readiness for
  82536. * @param useInstances is the mesh drawn using instance or not
  82537. * @returns true if ready otherwise false
  82538. */
  82539. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  82540. var material = subMesh.getMaterial();
  82541. if (material && material.disableDepthWrite) {
  82542. return false;
  82543. }
  82544. var defines = [];
  82545. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82546. var mesh = subMesh.getMesh();
  82547. // Alpha test
  82548. if (material && material.needAlphaTesting()) {
  82549. defines.push("#define ALPHATEST");
  82550. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82551. attribs.push(BABYLON.VertexBuffer.UVKind);
  82552. defines.push("#define UV1");
  82553. }
  82554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82556. defines.push("#define UV2");
  82557. }
  82558. }
  82559. // Buffers
  82560. if (this._enablePosition) {
  82561. defines.push("#define POSITION");
  82562. }
  82563. // Bones
  82564. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82565. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82566. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82567. if (mesh.numBoneInfluencers > 4) {
  82568. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82569. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82570. }
  82571. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82572. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82573. }
  82574. else {
  82575. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82576. }
  82577. // Instances
  82578. if (useInstances) {
  82579. defines.push("#define INSTANCES");
  82580. attribs.push("world0");
  82581. attribs.push("world1");
  82582. attribs.push("world2");
  82583. attribs.push("world3");
  82584. }
  82585. // Get correct effect
  82586. var join = defines.join("\n");
  82587. if (this._cachedDefines !== join) {
  82588. this._cachedDefines = join;
  82589. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  82590. }
  82591. return this._effect.isReady();
  82592. };
  82593. /**
  82594. * Gets the current underlying G Buffer.
  82595. * @returns the buffer
  82596. */
  82597. GeometryBufferRenderer.prototype.getGBuffer = function () {
  82598. return this._multiRenderTarget;
  82599. };
  82600. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  82601. /**
  82602. * Gets the number of samples used to render the buffer (anti aliasing).
  82603. */
  82604. get: function () {
  82605. return this._multiRenderTarget.samples;
  82606. },
  82607. /**
  82608. * Sets the number of samples used to render the buffer (anti aliasing).
  82609. */
  82610. set: function (value) {
  82611. this._multiRenderTarget.samples = value;
  82612. },
  82613. enumerable: true,
  82614. configurable: true
  82615. });
  82616. /**
  82617. * Disposes the renderer and frees up associated resources.
  82618. */
  82619. GeometryBufferRenderer.prototype.dispose = function () {
  82620. this.getGBuffer().dispose();
  82621. };
  82622. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  82623. var _this = this;
  82624. var engine = this._scene.getEngine();
  82625. var count = this._enablePosition ? 3 : 2;
  82626. 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 });
  82627. if (!this.isSupported) {
  82628. return;
  82629. }
  82630. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82631. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82632. this._multiRenderTarget.refreshRate = 1;
  82633. this._multiRenderTarget.renderParticles = false;
  82634. this._multiRenderTarget.renderList = null;
  82635. // set default depth value to 1.0 (far away)
  82636. this._multiRenderTarget.onClearObservable.add(function (engine) {
  82637. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  82638. });
  82639. // Custom render function
  82640. var renderSubMesh = function (subMesh) {
  82641. var mesh = subMesh.getRenderingMesh();
  82642. var scene = _this._scene;
  82643. var engine = scene.getEngine();
  82644. var material = subMesh.getMaterial();
  82645. if (!material) {
  82646. return;
  82647. }
  82648. // Culling
  82649. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  82650. // Managing instances
  82651. var batch = mesh._getInstancesRenderList(subMesh._id);
  82652. if (batch.mustReturn) {
  82653. return;
  82654. }
  82655. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82656. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  82657. engine.enableEffect(_this._effect);
  82658. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  82659. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82660. _this._effect.setMatrix("view", scene.getViewMatrix());
  82661. // Alpha test
  82662. if (material && material.needAlphaTesting()) {
  82663. var alphaTexture = material.getAlphaTestTexture();
  82664. if (alphaTexture) {
  82665. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82666. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82667. }
  82668. }
  82669. // Bones
  82670. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82671. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82672. }
  82673. // Draw
  82674. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82675. }
  82676. };
  82677. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82678. var index;
  82679. if (depthOnlySubMeshes.length) {
  82680. engine.setColorWrite(false);
  82681. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82682. renderSubMesh(depthOnlySubMeshes.data[index]);
  82683. }
  82684. engine.setColorWrite(true);
  82685. }
  82686. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82687. renderSubMesh(opaqueSubMeshes.data[index]);
  82688. }
  82689. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82690. renderSubMesh(alphaTestSubMeshes.data[index]);
  82691. }
  82692. };
  82693. };
  82694. return GeometryBufferRenderer;
  82695. }());
  82696. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  82697. })(BABYLON || (BABYLON = {}));
  82698. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  82699. var BABYLON;
  82700. (function (BABYLON) {
  82701. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  82702. get: function () {
  82703. this._geometryBufferRenderer;
  82704. },
  82705. set: function (value) {
  82706. if (value && value.isSupported) {
  82707. this._geometryBufferRenderer = value;
  82708. }
  82709. ;
  82710. },
  82711. enumerable: true,
  82712. configurable: true
  82713. });
  82714. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  82715. if (ratio === void 0) { ratio = 1; }
  82716. if (this._geometryBufferRenderer) {
  82717. return this._geometryBufferRenderer;
  82718. }
  82719. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  82720. if (!this._geometryBufferRenderer.isSupported) {
  82721. this._geometryBufferRenderer = null;
  82722. }
  82723. return this._geometryBufferRenderer;
  82724. };
  82725. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  82726. if (!this._geometryBufferRenderer) {
  82727. return;
  82728. }
  82729. this._geometryBufferRenderer.dispose();
  82730. this._geometryBufferRenderer = null;
  82731. };
  82732. /**
  82733. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  82734. * in several rendering techniques.
  82735. */
  82736. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  82737. /**
  82738. * Creates a new instance of the component for the given scene
  82739. * @param scene Defines the scene to register the component in
  82740. */
  82741. function GeometryBufferRendererSceneComponent(scene) {
  82742. /**
  82743. * The component name helpful to identify the component in the list of scene components.
  82744. */
  82745. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  82746. this.scene = scene;
  82747. }
  82748. /**
  82749. * Registers the component in a given scene
  82750. */
  82751. GeometryBufferRendererSceneComponent.prototype.register = function () {
  82752. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  82753. };
  82754. /**
  82755. * Rebuilds the elements related to this component in case of
  82756. * context lost for instance.
  82757. */
  82758. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  82759. // Nothing to do for this component
  82760. };
  82761. /**
  82762. * Disposes the component and the associated ressources
  82763. */
  82764. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  82765. // Nothing to do for this component
  82766. };
  82767. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82768. if (this.scene._geometryBufferRenderer) {
  82769. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  82770. }
  82771. };
  82772. return GeometryBufferRendererSceneComponent;
  82773. }());
  82774. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  82775. })(BABYLON || (BABYLON = {}));
  82776. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  82777. var BABYLON;
  82778. (function (BABYLON) {
  82779. var SSAORenderingPipeline = /** @class */ (function (_super) {
  82780. __extends(SSAORenderingPipeline, _super);
  82781. /**
  82782. * @constructor
  82783. * @param {string} name - The rendering pipeline name
  82784. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82785. * @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 }
  82786. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82787. */
  82788. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  82789. var _this = _super.call(this, scene.getEngine(), name) || this;
  82790. // Members
  82791. /**
  82792. * The PassPostProcess id in the pipeline that contains the original scene color
  82793. */
  82794. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82795. /**
  82796. * The SSAO PostProcess id in the pipeline
  82797. */
  82798. _this.SSAORenderEffect = "SSAORenderEffect";
  82799. /**
  82800. * The horizontal blur PostProcess id in the pipeline
  82801. */
  82802. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82803. /**
  82804. * The vertical blur PostProcess id in the pipeline
  82805. */
  82806. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82807. /**
  82808. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82809. */
  82810. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82811. /**
  82812. * The output strength of the SSAO post-process. Default value is 1.0.
  82813. */
  82814. _this.totalStrength = 1.0;
  82815. /**
  82816. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  82817. */
  82818. _this.radius = 0.0001;
  82819. /**
  82820. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  82821. * Must not be equal to fallOff and superior to fallOff.
  82822. * Default value is 0.975
  82823. */
  82824. _this.area = 0.0075;
  82825. /**
  82826. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  82827. * Must not be equal to area and inferior to area.
  82828. * Default value is 0.0
  82829. */
  82830. _this.fallOff = 0.000001;
  82831. /**
  82832. * The base color of the SSAO post-process
  82833. * The final result is "base + ssao" between [0, 1]
  82834. */
  82835. _this.base = 0.5;
  82836. _this._firstUpdate = true;
  82837. _this._scene = scene;
  82838. // Set up assets
  82839. _this._createRandomTexture();
  82840. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  82841. var ssaoRatio = ratio.ssaoRatio || ratio;
  82842. var combineRatio = ratio.combineRatio || ratio;
  82843. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  82844. _this._createSSAOPostProcess(ssaoRatio);
  82845. _this._createBlurPostProcess(ssaoRatio);
  82846. _this._createSSAOCombinePostProcess(combineRatio);
  82847. // Set up pipeline
  82848. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  82849. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  82850. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  82851. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  82852. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  82853. // Finish
  82854. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82855. if (cameras)
  82856. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82857. return _this;
  82858. }
  82859. // Public Methods
  82860. /**
  82861. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  82862. */
  82863. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82864. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82865. for (var i = 0; i < this._scene.cameras.length; i++) {
  82866. var camera = this._scene.cameras[i];
  82867. this._originalColorPostProcess.dispose(camera);
  82868. this._ssaoPostProcess.dispose(camera);
  82869. this._blurHPostProcess.dispose(camera);
  82870. this._blurVPostProcess.dispose(camera);
  82871. this._ssaoCombinePostProcess.dispose(camera);
  82872. }
  82873. this._randomTexture.dispose();
  82874. if (disableDepthRender)
  82875. this._scene.disableDepthRenderer();
  82876. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82877. _super.prototype.dispose.call(this);
  82878. };
  82879. // Private Methods
  82880. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  82881. var _this = this;
  82882. var size = 16;
  82883. 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);
  82884. 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);
  82885. this._blurHPostProcess.onActivateObservable.add(function () {
  82886. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  82887. _this._blurHPostProcess.kernel = size * dw;
  82888. });
  82889. this._blurVPostProcess.onActivateObservable.add(function () {
  82890. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  82891. _this._blurVPostProcess.kernel = size * dw;
  82892. });
  82893. };
  82894. /** @hidden */
  82895. SSAORenderingPipeline.prototype._rebuild = function () {
  82896. this._firstUpdate = true;
  82897. _super.prototype._rebuild.call(this);
  82898. };
  82899. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  82900. var _this = this;
  82901. var numSamples = 16;
  82902. var sampleSphere = [
  82903. 0.5381, 0.1856, -0.4319,
  82904. 0.1379, 0.2486, 0.4430,
  82905. 0.3371, 0.5679, -0.0057,
  82906. -0.6999, -0.0451, -0.0019,
  82907. 0.0689, -0.1598, -0.8547,
  82908. 0.0560, 0.0069, -0.1843,
  82909. -0.0146, 0.1402, 0.0762,
  82910. 0.0100, -0.1924, -0.0344,
  82911. -0.3577, -0.5301, -0.4358,
  82912. -0.3169, 0.1063, 0.0158,
  82913. 0.0103, -0.5869, 0.0046,
  82914. -0.0897, -0.4940, 0.3287,
  82915. 0.7119, -0.0154, -0.0918,
  82916. -0.0533, 0.0596, -0.5411,
  82917. 0.0352, -0.0631, 0.5460,
  82918. -0.4776, 0.2847, -0.0271
  82919. ];
  82920. var samplesFactor = 1.0 / numSamples;
  82921. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  82922. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  82923. "area", "fallOff", "base", "range", "viewport"
  82924. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  82925. this._ssaoPostProcess.onApply = function (effect) {
  82926. if (_this._firstUpdate) {
  82927. effect.setArray3("sampleSphere", sampleSphere);
  82928. effect.setFloat("samplesFactor", samplesFactor);
  82929. effect.setFloat("randTextureTiles", 4.0);
  82930. }
  82931. effect.setFloat("totalStrength", _this.totalStrength);
  82932. effect.setFloat("radius", _this.radius);
  82933. effect.setFloat("area", _this.area);
  82934. effect.setFloat("fallOff", _this.fallOff);
  82935. effect.setFloat("base", _this.base);
  82936. effect.setTexture("textureSampler", _this._depthTexture);
  82937. effect.setTexture("randomSampler", _this._randomTexture);
  82938. };
  82939. };
  82940. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  82941. var _this = this;
  82942. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82943. this._ssaoCombinePostProcess.onApply = function (effect) {
  82944. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  82945. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  82946. };
  82947. };
  82948. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  82949. var size = 512;
  82950. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82951. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82952. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82953. var context = this._randomTexture.getContext();
  82954. var rand = function (min, max) {
  82955. return Math.random() * (max - min) + min;
  82956. };
  82957. var randVector = BABYLON.Vector3.Zero();
  82958. for (var x = 0; x < size; x++) {
  82959. for (var y = 0; y < size; y++) {
  82960. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  82961. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  82962. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  82963. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  82964. context.fillRect(x, y, 1, 1);
  82965. }
  82966. }
  82967. this._randomTexture.update(false);
  82968. };
  82969. __decorate([
  82970. BABYLON.serialize()
  82971. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  82972. __decorate([
  82973. BABYLON.serialize()
  82974. ], SSAORenderingPipeline.prototype, "radius", void 0);
  82975. __decorate([
  82976. BABYLON.serialize()
  82977. ], SSAORenderingPipeline.prototype, "area", void 0);
  82978. __decorate([
  82979. BABYLON.serialize()
  82980. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  82981. __decorate([
  82982. BABYLON.serialize()
  82983. ], SSAORenderingPipeline.prototype, "base", void 0);
  82984. return SSAORenderingPipeline;
  82985. }(BABYLON.PostProcessRenderPipeline));
  82986. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  82987. })(BABYLON || (BABYLON = {}));
  82988. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  82989. var BABYLON;
  82990. (function (BABYLON) {
  82991. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  82992. __extends(SSAO2RenderingPipeline, _super);
  82993. /**
  82994. * @constructor
  82995. * @param {string} name - The rendering pipeline name
  82996. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82997. * @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 }
  82998. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82999. */
  83000. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  83001. var _this = _super.call(this, scene.getEngine(), name) || this;
  83002. // Members
  83003. /**
  83004. * The PassPostProcess id in the pipeline that contains the original scene color
  83005. */
  83006. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83007. /**
  83008. * The SSAO PostProcess id in the pipeline
  83009. */
  83010. _this.SSAORenderEffect = "SSAORenderEffect";
  83011. /**
  83012. * The horizontal blur PostProcess id in the pipeline
  83013. */
  83014. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83015. /**
  83016. * The vertical blur PostProcess id in the pipeline
  83017. */
  83018. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83019. /**
  83020. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83021. */
  83022. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83023. /**
  83024. * The output strength of the SSAO post-process. Default value is 1.0.
  83025. */
  83026. _this.totalStrength = 1.0;
  83027. /**
  83028. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  83029. */
  83030. _this.maxZ = 100.0;
  83031. /**
  83032. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  83033. */
  83034. _this.minZAspect = 0.2;
  83035. _this._samples = 8;
  83036. _this._textureSamples = 1;
  83037. /**
  83038. * Are we using bilateral blur ?
  83039. */
  83040. _this._expensiveBlur = true;
  83041. /**
  83042. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  83043. */
  83044. _this.radius = 2.0;
  83045. /**
  83046. * The base color of the SSAO post-process
  83047. * The final result is "base + ssao" between [0, 1]
  83048. */
  83049. _this.base = 0;
  83050. _this._firstUpdate = true;
  83051. _this._bits = new Uint32Array(1);
  83052. _this._scene = scene;
  83053. _this._ratio = ratio;
  83054. if (!_this.isSupported) {
  83055. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  83056. return _this;
  83057. }
  83058. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  83059. var blurRatio = _this._ratio.blurRatio || ratio;
  83060. // Set up assets
  83061. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  83062. _this._createRandomTexture();
  83063. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  83064. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  83065. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83066. _this._originalColorPostProcess.samples = _this.textureSamples;
  83067. _this._createSSAOPostProcess(1.0);
  83068. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  83069. _this._createSSAOCombinePostProcess(blurRatio);
  83070. // Set up pipeline
  83071. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83072. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83073. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83074. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83075. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83076. // Finish
  83077. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83078. if (cameras)
  83079. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83080. return _this;
  83081. }
  83082. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  83083. get: function () {
  83084. return this._samples;
  83085. },
  83086. /**
  83087. * Number of samples used for the SSAO calculations. Default value is 8
  83088. */
  83089. set: function (n) {
  83090. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  83091. this._samples = n;
  83092. this._sampleSphere = this._generateHemisphere();
  83093. this._firstUpdate = true;
  83094. },
  83095. enumerable: true,
  83096. configurable: true
  83097. });
  83098. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  83099. get: function () {
  83100. return this._textureSamples;
  83101. },
  83102. /**
  83103. * Number of samples to use for antialiasing
  83104. */
  83105. set: function (n) {
  83106. this._textureSamples = n;
  83107. this._originalColorPostProcess.samples = n;
  83108. this._blurHPostProcess.samples = n;
  83109. this._blurVPostProcess.samples = n;
  83110. this._ssaoPostProcess.samples = n;
  83111. this._ssaoCombinePostProcess.samples = n;
  83112. },
  83113. enumerable: true,
  83114. configurable: true
  83115. });
  83116. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  83117. get: function () {
  83118. return this._expensiveBlur;
  83119. },
  83120. set: function (b) {
  83121. 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"]);
  83122. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  83123. this._expensiveBlur = b;
  83124. this._firstUpdate = true;
  83125. },
  83126. enumerable: true,
  83127. configurable: true
  83128. });
  83129. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  83130. /**
  83131. * Support test.
  83132. */
  83133. get: function () {
  83134. var engine = BABYLON.Engine.LastCreatedEngine;
  83135. if (!engine) {
  83136. return false;
  83137. }
  83138. return engine.getCaps().drawBuffersExtension;
  83139. },
  83140. enumerable: true,
  83141. configurable: true
  83142. });
  83143. // Public Methods
  83144. /**
  83145. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  83146. */
  83147. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  83148. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  83149. for (var i = 0; i < this._scene.cameras.length; i++) {
  83150. var camera = this._scene.cameras[i];
  83151. this._originalColorPostProcess.dispose(camera);
  83152. this._ssaoPostProcess.dispose(camera);
  83153. this._blurHPostProcess.dispose(camera);
  83154. this._blurVPostProcess.dispose(camera);
  83155. this._ssaoCombinePostProcess.dispose(camera);
  83156. }
  83157. this._randomTexture.dispose();
  83158. if (disableGeometryBufferRenderer)
  83159. this._scene.disableGeometryBufferRenderer();
  83160. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83161. _super.prototype.dispose.call(this);
  83162. };
  83163. // Private Methods
  83164. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  83165. var _this = this;
  83166. this._samplerOffsets = [];
  83167. var expensive = this.expensiveBlur;
  83168. for (var i = -8; i < 8; i++) {
  83169. this._samplerOffsets.push(i * 2 + 0.5);
  83170. }
  83171. 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");
  83172. this._blurHPostProcess.onApply = function (effect) {
  83173. if (!_this._scene.activeCamera) {
  83174. return;
  83175. }
  83176. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  83177. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83178. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83179. effect.setFloat("radius", _this.radius);
  83180. effect.setTexture("depthSampler", _this._depthTexture);
  83181. if (_this._firstUpdate) {
  83182. effect.setArray("samplerOffsets", _this._samplerOffsets);
  83183. }
  83184. };
  83185. 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");
  83186. this._blurVPostProcess.onApply = function (effect) {
  83187. if (!_this._scene.activeCamera) {
  83188. return;
  83189. }
  83190. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  83191. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83192. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83193. effect.setFloat("radius", _this.radius);
  83194. effect.setTexture("depthSampler", _this._depthTexture);
  83195. if (_this._firstUpdate) {
  83196. effect.setArray("samplerOffsets", _this._samplerOffsets);
  83197. _this._firstUpdate = false;
  83198. }
  83199. };
  83200. this._blurHPostProcess.samples = this.textureSamples;
  83201. this._blurVPostProcess.samples = this.textureSamples;
  83202. };
  83203. /** @hidden */
  83204. SSAO2RenderingPipeline.prototype._rebuild = function () {
  83205. this._firstUpdate = true;
  83206. _super.prototype._rebuild.call(this);
  83207. };
  83208. //Van der Corput radical inverse
  83209. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  83210. this._bits[0] = i;
  83211. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  83212. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  83213. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  83214. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  83215. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  83216. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  83217. };
  83218. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  83219. return [i / n, this._radicalInverse_VdC(i)];
  83220. };
  83221. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  83222. var phi = v * 2.0 * Math.PI;
  83223. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  83224. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  83225. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  83226. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  83227. };
  83228. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  83229. var numSamples = this.samples;
  83230. var result = [];
  83231. var vector;
  83232. var i = 0;
  83233. while (i < numSamples) {
  83234. if (numSamples < 16) {
  83235. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  83236. }
  83237. else {
  83238. var rand = this._hammersley(i, numSamples);
  83239. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  83240. }
  83241. result.push(vector.x, vector.y, vector.z);
  83242. i++;
  83243. }
  83244. return result;
  83245. };
  83246. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  83247. var _this = this;
  83248. var numSamples = this.samples;
  83249. this._sampleSphere = this._generateHemisphere();
  83250. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  83251. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  83252. "base", "range", "projection", "near", "far", "texelSize",
  83253. "xViewport", "yViewport", "maxZ", "minZAspect"
  83254. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  83255. this._ssaoPostProcess.onApply = function (effect) {
  83256. if (_this._firstUpdate) {
  83257. effect.setArray3("sampleSphere", _this._sampleSphere);
  83258. effect.setFloat("randTextureTiles", 32.0);
  83259. }
  83260. if (!_this._scene.activeCamera) {
  83261. return;
  83262. }
  83263. effect.setFloat("samplesFactor", 1 / _this.samples);
  83264. effect.setFloat("totalStrength", _this.totalStrength);
  83265. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  83266. effect.setFloat("radius", _this.radius);
  83267. effect.setFloat("maxZ", _this.maxZ);
  83268. effect.setFloat("minZAspect", _this.minZAspect);
  83269. effect.setFloat("base", _this.base);
  83270. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83271. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83272. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  83273. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  83274. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  83275. effect.setTexture("textureSampler", _this._depthTexture);
  83276. effect.setTexture("normalSampler", _this._normalTexture);
  83277. effect.setTexture("randomSampler", _this._randomTexture);
  83278. };
  83279. this._ssaoPostProcess.samples = this.textureSamples;
  83280. };
  83281. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  83282. var _this = this;
  83283. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83284. this._ssaoCombinePostProcess.onApply = function (effect) {
  83285. var viewport = _this._scene.activeCamera.viewport;
  83286. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  83287. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  83288. };
  83289. this._ssaoCombinePostProcess.samples = this.textureSamples;
  83290. };
  83291. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  83292. var size = 128;
  83293. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83294. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83295. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83296. var context = this._randomTexture.getContext();
  83297. var rand = function (min, max) {
  83298. return Math.random() * (max - min) + min;
  83299. };
  83300. var randVector = BABYLON.Vector3.Zero();
  83301. for (var x = 0; x < size; x++) {
  83302. for (var y = 0; y < size; y++) {
  83303. randVector.x = rand(0.0, 1.0);
  83304. randVector.y = rand(0.0, 1.0);
  83305. randVector.z = 0.0;
  83306. randVector.normalize();
  83307. randVector.scaleInPlace(255);
  83308. randVector.x = Math.floor(randVector.x);
  83309. randVector.y = Math.floor(randVector.y);
  83310. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  83311. context.fillRect(x, y, 1, 1);
  83312. }
  83313. }
  83314. this._randomTexture.update(false);
  83315. };
  83316. /**
  83317. * Serialize the rendering pipeline (Used when exporting)
  83318. * @returns the serialized object
  83319. */
  83320. SSAO2RenderingPipeline.prototype.serialize = function () {
  83321. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83322. serializationObject.customType = "SSAO2RenderingPipeline";
  83323. return serializationObject;
  83324. };
  83325. /**
  83326. * Parse the serialized pipeline
  83327. * @param source Source pipeline.
  83328. * @param scene The scene to load the pipeline to.
  83329. * @param rootUrl The URL of the serialized pipeline.
  83330. * @returns An instantiated pipeline from the serialized object.
  83331. */
  83332. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  83333. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  83334. };
  83335. __decorate([
  83336. BABYLON.serialize()
  83337. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  83338. __decorate([
  83339. BABYLON.serialize()
  83340. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  83341. __decorate([
  83342. BABYLON.serialize()
  83343. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  83344. __decorate([
  83345. BABYLON.serialize("samples")
  83346. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  83347. __decorate([
  83348. BABYLON.serialize("textureSamples")
  83349. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  83350. __decorate([
  83351. BABYLON.serialize()
  83352. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  83353. __decorate([
  83354. BABYLON.serialize("expensiveBlur")
  83355. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  83356. __decorate([
  83357. BABYLON.serialize()
  83358. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  83359. __decorate([
  83360. BABYLON.serialize()
  83361. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  83362. return SSAO2RenderingPipeline;
  83363. }(BABYLON.PostProcessRenderPipeline));
  83364. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  83365. })(BABYLON || (BABYLON = {}));
  83366. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  83367. // BABYLON.JS Chromatic Aberration GLSL Shader
  83368. // Author: Olivier Guyot
  83369. // Separates very slightly R, G and B colors on the edges of the screen
  83370. // Inspired by Francois Tarlier & Martins Upitis
  83371. var BABYLON;
  83372. (function (BABYLON) {
  83373. var LensRenderingPipeline = /** @class */ (function (_super) {
  83374. __extends(LensRenderingPipeline, _super);
  83375. /**
  83376. * @constructor
  83377. *
  83378. * Effect parameters are as follow:
  83379. * {
  83380. * chromatic_aberration: number; // from 0 to x (1 for realism)
  83381. * edge_blur: number; // from 0 to x (1 for realism)
  83382. * distortion: number; // from 0 to x (1 for realism)
  83383. * grain_amount: number; // from 0 to 1
  83384. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  83385. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  83386. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  83387. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  83388. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  83389. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  83390. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  83391. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  83392. * }
  83393. * Note: if an effect parameter is unset, effect is disabled
  83394. *
  83395. * @param {string} name - The rendering pipeline name
  83396. * @param {object} parameters - An object containing all parameters (see above)
  83397. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83398. * @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)
  83399. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83400. */
  83401. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  83402. if (ratio === void 0) { ratio = 1.0; }
  83403. var _this = _super.call(this, scene.getEngine(), name) || this;
  83404. // Lens effects can be of the following:
  83405. // - chromatic aberration (slight shift of RGB colors)
  83406. // - blur on the edge of the lens
  83407. // - lens distortion
  83408. // - depth-of-field blur & highlights enhancing
  83409. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  83410. // - grain effect (noise or custom texture)
  83411. // Two additional texture samplers are needed:
  83412. // - depth map (for depth-of-field)
  83413. // - grain texture
  83414. /**
  83415. * The chromatic aberration PostProcess id in the pipeline
  83416. */
  83417. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  83418. /**
  83419. * The highlights enhancing PostProcess id in the pipeline
  83420. */
  83421. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  83422. /**
  83423. * The depth-of-field PostProcess id in the pipeline
  83424. */
  83425. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  83426. _this._scene = scene;
  83427. // Fetch texture samplers
  83428. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  83429. if (parameters.grain_texture) {
  83430. _this._grainTexture = parameters.grain_texture;
  83431. }
  83432. else {
  83433. _this._createGrainTexture();
  83434. }
  83435. // save parameters
  83436. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  83437. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  83438. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  83439. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  83440. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  83441. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  83442. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  83443. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  83444. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  83445. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  83446. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  83447. // Create effects
  83448. _this._createChromaticAberrationPostProcess(ratio);
  83449. _this._createHighlightsPostProcess(ratio);
  83450. _this._createDepthOfFieldPostProcess(ratio / 4);
  83451. // Set up pipeline
  83452. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  83453. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  83454. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  83455. if (_this._highlightsGain === -1) {
  83456. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  83457. }
  83458. // Finish
  83459. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83460. if (cameras) {
  83461. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83462. }
  83463. return _this;
  83464. }
  83465. // public methods (self explanatory)
  83466. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  83467. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  83468. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  83469. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  83470. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  83471. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  83472. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  83473. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  83474. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  83475. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  83476. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  83477. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  83478. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  83479. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  83480. };
  83481. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  83482. this._highlightsPostProcess.updateEffect();
  83483. };
  83484. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  83485. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  83486. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  83487. this._highlightsGain = amount;
  83488. };
  83489. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  83490. if (this._highlightsGain === -1) {
  83491. this._highlightsGain = 1.0;
  83492. }
  83493. this._highlightsThreshold = amount;
  83494. };
  83495. LensRenderingPipeline.prototype.disableHighlights = function () {
  83496. this._highlightsGain = -1;
  83497. };
  83498. /**
  83499. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  83500. */
  83501. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  83502. if (disableDepthRender === void 0) { disableDepthRender = false; }
  83503. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83504. this._chromaticAberrationPostProcess = null;
  83505. this._highlightsPostProcess = null;
  83506. this._depthOfFieldPostProcess = null;
  83507. this._grainTexture.dispose();
  83508. if (disableDepthRender)
  83509. this._scene.disableDepthRenderer();
  83510. };
  83511. // colors shifting and distortion
  83512. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  83513. var _this = this;
  83514. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  83515. [], // samplers
  83516. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83517. this._chromaticAberrationPostProcess.onApply = function (effect) {
  83518. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  83519. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83520. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83521. effect.setFloat('radialIntensity', 1);
  83522. effect.setFloat2('direction', 17, 17);
  83523. effect.setFloat2('centerPosition', 0.5, 0.5);
  83524. };
  83525. };
  83526. // highlights enhancing
  83527. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  83528. var _this = this;
  83529. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  83530. [], // samplers
  83531. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  83532. this._highlightsPostProcess.onApply = function (effect) {
  83533. effect.setFloat('gain', _this._highlightsGain);
  83534. effect.setFloat('threshold', _this._highlightsThreshold);
  83535. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  83536. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83537. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83538. };
  83539. };
  83540. // colors shifting and distortion
  83541. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  83542. var _this = this;
  83543. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  83544. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  83545. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  83546. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83547. this._depthOfFieldPostProcess.onApply = function (effect) {
  83548. effect.setTexture("depthSampler", _this._depthTexture);
  83549. effect.setTexture("grainSampler", _this._grainTexture);
  83550. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  83551. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  83552. effect.setFloat('grain_amount', _this._grainAmount);
  83553. effect.setBool('blur_noise', _this._blurNoise);
  83554. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83555. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83556. effect.setFloat('distortion', _this._distortion);
  83557. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  83558. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  83559. effect.setFloat('aperture', _this._dofAperture);
  83560. effect.setFloat('darken', _this._dofDarken);
  83561. effect.setFloat('edge_blur', _this._edgeBlur);
  83562. effect.setBool('highlights', (_this._highlightsGain !== -1));
  83563. if (_this._scene.activeCamera) {
  83564. effect.setFloat('near', _this._scene.activeCamera.minZ);
  83565. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  83566. }
  83567. };
  83568. };
  83569. // creates a black and white random noise texture, 512x512
  83570. LensRenderingPipeline.prototype._createGrainTexture = function () {
  83571. var size = 512;
  83572. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83573. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83574. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83575. var context = this._grainTexture.getContext();
  83576. var rand = function (min, max) {
  83577. return Math.random() * (max - min) + min;
  83578. };
  83579. var value;
  83580. for (var x = 0; x < size; x++) {
  83581. for (var y = 0; y < size; y++) {
  83582. value = Math.floor(rand(0.42, 0.58) * 255);
  83583. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  83584. context.fillRect(x, y, 1, 1);
  83585. }
  83586. }
  83587. this._grainTexture.update(false);
  83588. };
  83589. return LensRenderingPipeline;
  83590. }(BABYLON.PostProcessRenderPipeline));
  83591. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  83592. })(BABYLON || (BABYLON = {}));
  83593. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  83594. var BABYLON;
  83595. (function (BABYLON) {
  83596. /**
  83597. * Standard rendering pipeline
  83598. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  83599. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  83600. */
  83601. var StandardRenderingPipeline = /** @class */ (function (_super) {
  83602. __extends(StandardRenderingPipeline, _super);
  83603. /**
  83604. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  83605. * @constructor
  83606. * @param {string} name - The rendering pipeline name
  83607. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83608. * @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)
  83609. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  83610. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83611. */
  83612. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  83613. if (originalPostProcess === void 0) { originalPostProcess = null; }
  83614. var _this = _super.call(this, scene.getEngine(), name) || this;
  83615. /**
  83616. * Post-process used to down scale an image x4
  83617. */
  83618. _this.downSampleX4PostProcess = null;
  83619. /**
  83620. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  83621. */
  83622. _this.brightPassPostProcess = null;
  83623. /**
  83624. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  83625. */
  83626. _this.blurHPostProcesses = [];
  83627. /**
  83628. * Post-process array storing all the vertical blur post-processes used by the pipeline
  83629. */
  83630. _this.blurVPostProcesses = [];
  83631. /**
  83632. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  83633. */
  83634. _this.textureAdderPostProcess = null;
  83635. /**
  83636. * Post-process used to create volumetric lighting effect
  83637. */
  83638. _this.volumetricLightPostProcess = null;
  83639. /**
  83640. * Post-process used to smooth the previous volumetric light post-process on the X axis
  83641. */
  83642. _this.volumetricLightSmoothXPostProcess = null;
  83643. /**
  83644. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  83645. */
  83646. _this.volumetricLightSmoothYPostProcess = null;
  83647. /**
  83648. * Post-process used to merge the volumetric light effect and the real scene color
  83649. */
  83650. _this.volumetricLightMergePostProces = null;
  83651. /**
  83652. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  83653. */
  83654. _this.volumetricLightFinalPostProcess = null;
  83655. /**
  83656. * Base post-process used to calculate the average luminance of the final image for HDR
  83657. */
  83658. _this.luminancePostProcess = null;
  83659. /**
  83660. * Post-processes used to create down sample post-processes in order to get
  83661. * the average luminance of the final image for HDR
  83662. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  83663. */
  83664. _this.luminanceDownSamplePostProcesses = [];
  83665. /**
  83666. * Post-process used to create a HDR effect (light adaptation)
  83667. */
  83668. _this.hdrPostProcess = null;
  83669. /**
  83670. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  83671. */
  83672. _this.textureAdderFinalPostProcess = null;
  83673. /**
  83674. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  83675. */
  83676. _this.lensFlareFinalPostProcess = null;
  83677. /**
  83678. * Post-process used to merge the final HDR post-process and the real scene color
  83679. */
  83680. _this.hdrFinalPostProcess = null;
  83681. /**
  83682. * Post-process used to create a lens flare effect
  83683. */
  83684. _this.lensFlarePostProcess = null;
  83685. /**
  83686. * Post-process that merges the result of the lens flare post-process and the real scene color
  83687. */
  83688. _this.lensFlareComposePostProcess = null;
  83689. /**
  83690. * Post-process used to create a motion blur effect
  83691. */
  83692. _this.motionBlurPostProcess = null;
  83693. /**
  83694. * Post-process used to create a depth of field effect
  83695. */
  83696. _this.depthOfFieldPostProcess = null;
  83697. /**
  83698. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  83699. */
  83700. _this.fxaaPostProcess = null;
  83701. // Values
  83702. /**
  83703. * Represents the brightness threshold in order to configure the illuminated surfaces
  83704. */
  83705. _this.brightThreshold = 1.0;
  83706. /**
  83707. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  83708. */
  83709. _this.blurWidth = 512.0;
  83710. /**
  83711. * Sets if the blur for highlighted surfaces must be only horizontal
  83712. */
  83713. _this.horizontalBlur = false;
  83714. /**
  83715. * Sets the overall exposure used by the pipeline
  83716. */
  83717. _this.exposure = 1.0;
  83718. /**
  83719. * Texture used typically to simulate "dirty" on camera lens
  83720. */
  83721. _this.lensTexture = null;
  83722. /**
  83723. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  83724. */
  83725. _this.volumetricLightCoefficient = 0.2;
  83726. /**
  83727. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  83728. */
  83729. _this.volumetricLightPower = 4.0;
  83730. /**
  83731. * Used the set the blur intensity to smooth the volumetric lights
  83732. */
  83733. _this.volumetricLightBlurScale = 64.0;
  83734. /**
  83735. * Light (spot or directional) used to generate the volumetric lights rays
  83736. * The source light must have a shadow generate so the pipeline can get its
  83737. * depth map
  83738. */
  83739. _this.sourceLight = null;
  83740. /**
  83741. * For eye adaptation, represents the minimum luminance the eye can see
  83742. */
  83743. _this.hdrMinimumLuminance = 1.0;
  83744. /**
  83745. * For eye adaptation, represents the decrease luminance speed
  83746. */
  83747. _this.hdrDecreaseRate = 0.5;
  83748. /**
  83749. * For eye adaptation, represents the increase luminance speed
  83750. */
  83751. _this.hdrIncreaseRate = 0.5;
  83752. /**
  83753. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  83754. */
  83755. _this.lensColorTexture = null;
  83756. /**
  83757. * The overall strengh for the lens flare effect
  83758. */
  83759. _this.lensFlareStrength = 20.0;
  83760. /**
  83761. * Dispersion coefficient for lens flare ghosts
  83762. */
  83763. _this.lensFlareGhostDispersal = 1.4;
  83764. /**
  83765. * Main lens flare halo width
  83766. */
  83767. _this.lensFlareHaloWidth = 0.7;
  83768. /**
  83769. * Based on the lens distortion effect, defines how much the lens flare result
  83770. * is distorted
  83771. */
  83772. _this.lensFlareDistortionStrength = 16.0;
  83773. /**
  83774. * Lens star texture must be used to simulate rays on the flares and is available
  83775. * in the documentation
  83776. */
  83777. _this.lensStarTexture = null;
  83778. /**
  83779. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  83780. * flare effect by taking account of the dirt texture
  83781. */
  83782. _this.lensFlareDirtTexture = null;
  83783. /**
  83784. * Represents the focal length for the depth of field effect
  83785. */
  83786. _this.depthOfFieldDistance = 10.0;
  83787. /**
  83788. * Represents the blur intensity for the blurred part of the depth of field effect
  83789. */
  83790. _this.depthOfFieldBlurWidth = 64.0;
  83791. /**
  83792. * For motion blur, defines how much the image is blurred by the movement
  83793. */
  83794. _this.motionStrength = 1.0;
  83795. /**
  83796. * List of animations for the pipeline (IAnimatable implementation)
  83797. */
  83798. _this.animations = [];
  83799. _this._currentDepthOfFieldSource = null;
  83800. _this._hdrCurrentLuminance = 1.0;
  83801. // Getters and setters
  83802. _this._bloomEnabled = false;
  83803. _this._depthOfFieldEnabled = false;
  83804. _this._vlsEnabled = false;
  83805. _this._lensFlareEnabled = false;
  83806. _this._hdrEnabled = false;
  83807. _this._motionBlurEnabled = false;
  83808. _this._fxaaEnabled = false;
  83809. _this._motionBlurSamples = 64.0;
  83810. _this._volumetricLightStepsCount = 50.0;
  83811. _this._samples = 1;
  83812. _this._cameras = cameras || [];
  83813. // Initialize
  83814. _this._scene = scene;
  83815. _this._basePostProcess = originalPostProcess;
  83816. _this._ratio = ratio;
  83817. // Misc
  83818. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83819. // Finish
  83820. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83821. _this._buildPipeline();
  83822. return _this;
  83823. }
  83824. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  83825. /**
  83826. * Specifies if the bloom pipeline is enabled
  83827. */
  83828. get: function () {
  83829. return this._bloomEnabled;
  83830. },
  83831. set: function (enabled) {
  83832. if (this._bloomEnabled === enabled) {
  83833. return;
  83834. }
  83835. this._bloomEnabled = enabled;
  83836. this._buildPipeline();
  83837. },
  83838. enumerable: true,
  83839. configurable: true
  83840. });
  83841. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  83842. /**
  83843. * Specifies if the depth of field pipeline is enabed
  83844. */
  83845. get: function () {
  83846. return this._depthOfFieldEnabled;
  83847. },
  83848. set: function (enabled) {
  83849. if (this._depthOfFieldEnabled === enabled) {
  83850. return;
  83851. }
  83852. this._depthOfFieldEnabled = enabled;
  83853. this._buildPipeline();
  83854. },
  83855. enumerable: true,
  83856. configurable: true
  83857. });
  83858. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  83859. /**
  83860. * Specifies if the lens flare pipeline is enabed
  83861. */
  83862. get: function () {
  83863. return this._lensFlareEnabled;
  83864. },
  83865. set: function (enabled) {
  83866. if (this._lensFlareEnabled === enabled) {
  83867. return;
  83868. }
  83869. this._lensFlareEnabled = enabled;
  83870. this._buildPipeline();
  83871. },
  83872. enumerable: true,
  83873. configurable: true
  83874. });
  83875. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  83876. /**
  83877. * Specifies if the HDR pipeline is enabled
  83878. */
  83879. get: function () {
  83880. return this._hdrEnabled;
  83881. },
  83882. set: function (enabled) {
  83883. if (this._hdrEnabled === enabled) {
  83884. return;
  83885. }
  83886. this._hdrEnabled = enabled;
  83887. this._buildPipeline();
  83888. },
  83889. enumerable: true,
  83890. configurable: true
  83891. });
  83892. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  83893. /**
  83894. * Specifies if the volumetric lights scattering effect is enabled
  83895. */
  83896. get: function () {
  83897. return this._vlsEnabled;
  83898. },
  83899. set: function (enabled) {
  83900. if (this._vlsEnabled === enabled) {
  83901. return;
  83902. }
  83903. if (enabled) {
  83904. var geometry = this._scene.enableGeometryBufferRenderer();
  83905. if (!geometry) {
  83906. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  83907. return;
  83908. }
  83909. }
  83910. this._vlsEnabled = enabled;
  83911. this._buildPipeline();
  83912. },
  83913. enumerable: true,
  83914. configurable: true
  83915. });
  83916. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  83917. /**
  83918. * Specifies if the motion blur effect is enabled
  83919. */
  83920. get: function () {
  83921. return this._motionBlurEnabled;
  83922. },
  83923. set: function (enabled) {
  83924. if (this._motionBlurEnabled === enabled) {
  83925. return;
  83926. }
  83927. this._motionBlurEnabled = enabled;
  83928. this._buildPipeline();
  83929. },
  83930. enumerable: true,
  83931. configurable: true
  83932. });
  83933. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  83934. /**
  83935. * Specifies if anti-aliasing is enabled
  83936. */
  83937. get: function () {
  83938. return this._fxaaEnabled;
  83939. },
  83940. set: function (enabled) {
  83941. if (this._fxaaEnabled === enabled) {
  83942. return;
  83943. }
  83944. this._fxaaEnabled = enabled;
  83945. this._buildPipeline();
  83946. },
  83947. enumerable: true,
  83948. configurable: true
  83949. });
  83950. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  83951. /**
  83952. * Specifies the number of steps used to calculate the volumetric lights
  83953. * Typically in interval [50, 200]
  83954. */
  83955. get: function () {
  83956. return this._volumetricLightStepsCount;
  83957. },
  83958. set: function (count) {
  83959. if (this.volumetricLightPostProcess) {
  83960. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  83961. }
  83962. this._volumetricLightStepsCount = count;
  83963. },
  83964. enumerable: true,
  83965. configurable: true
  83966. });
  83967. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  83968. /**
  83969. * Specifies the number of samples used for the motion blur effect
  83970. * Typically in interval [16, 64]
  83971. */
  83972. get: function () {
  83973. return this._motionBlurSamples;
  83974. },
  83975. set: function (samples) {
  83976. if (this.motionBlurPostProcess) {
  83977. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  83978. }
  83979. this._motionBlurSamples = samples;
  83980. },
  83981. enumerable: true,
  83982. configurable: true
  83983. });
  83984. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  83985. /**
  83986. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  83987. */
  83988. get: function () {
  83989. return this._samples;
  83990. },
  83991. set: function (sampleCount) {
  83992. if (this._samples === sampleCount) {
  83993. return;
  83994. }
  83995. this._samples = sampleCount;
  83996. this._buildPipeline();
  83997. },
  83998. enumerable: true,
  83999. configurable: true
  84000. });
  84001. StandardRenderingPipeline.prototype._buildPipeline = function () {
  84002. var _this = this;
  84003. var ratio = this._ratio;
  84004. var scene = this._scene;
  84005. this._disposePostProcesses();
  84006. this._reset();
  84007. // Create pass post-process
  84008. if (!this._basePostProcess) {
  84009. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  84010. this.originalPostProcess.onApply = function (effect) {
  84011. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  84012. };
  84013. }
  84014. else {
  84015. this.originalPostProcess = this._basePostProcess;
  84016. }
  84017. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  84018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  84019. }
  84020. this._currentDepthOfFieldSource = this.originalPostProcess;
  84021. if (this._bloomEnabled) {
  84022. // Create down sample X4 post-process
  84023. this._createDownSampleX4PostProcess(scene, ratio / 2);
  84024. // Create bright pass post-process
  84025. this._createBrightPassPostProcess(scene, ratio / 2);
  84026. // Create gaussian blur post-processes (down sampling blurs)
  84027. this._createBlurPostProcesses(scene, ratio / 4, 1);
  84028. // Create texture adder post-process
  84029. this._createTextureAdderPostProcess(scene, ratio);
  84030. // Create depth-of-field source post-process
  84031. 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);
  84032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  84033. }
  84034. if (this._vlsEnabled) {
  84035. // Create volumetric light
  84036. this._createVolumetricLightPostProcess(scene, ratio);
  84037. // Create volumetric light final post-process
  84038. 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);
  84039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  84040. }
  84041. if (this._lensFlareEnabled) {
  84042. // Create lens flare post-process
  84043. this._createLensFlarePostProcess(scene, ratio);
  84044. // Create depth-of-field source post-process post lens-flare and disable it now
  84045. 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);
  84046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  84047. }
  84048. if (this._hdrEnabled) {
  84049. // Create luminance
  84050. this._createLuminancePostProcesses(scene, this._floatTextureType);
  84051. // Create HDR
  84052. this._createHdrPostProcess(scene, ratio);
  84053. // Create depth-of-field source post-process post hdr and disable it now
  84054. 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);
  84055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  84056. }
  84057. if (this._depthOfFieldEnabled) {
  84058. // Create gaussian blur used by depth-of-field
  84059. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  84060. // Create depth-of-field post-process
  84061. this._createDepthOfFieldPostProcess(scene, ratio);
  84062. }
  84063. if (this._motionBlurEnabled) {
  84064. // Create motion blur post-process
  84065. this._createMotionBlurPostProcess(scene, ratio);
  84066. }
  84067. if (this._fxaaEnabled) {
  84068. // Create fxaa post-process
  84069. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84070. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  84071. }
  84072. if (this._cameras !== null) {
  84073. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84074. }
  84075. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  84076. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84077. }
  84078. };
  84079. // Down Sample X4 Post-Processs
  84080. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  84081. var _this = this;
  84082. var downSampleX4Offsets = new Array(32);
  84083. 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);
  84084. this.downSampleX4PostProcess.onApply = function (effect) {
  84085. var id = 0;
  84086. var width = _this.downSampleX4PostProcess.width;
  84087. var height = _this.downSampleX4PostProcess.height;
  84088. for (var i = -2; i < 2; i++) {
  84089. for (var j = -2; j < 2; j++) {
  84090. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  84091. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  84092. id += 2;
  84093. }
  84094. }
  84095. effect.setArray2("dsOffsets", downSampleX4Offsets);
  84096. };
  84097. // Add to pipeline
  84098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  84099. };
  84100. // Brightpass Post-Process
  84101. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  84102. var _this = this;
  84103. var brightOffsets = new Array(8);
  84104. 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);
  84105. this.brightPassPostProcess.onApply = function (effect) {
  84106. var sU = (1.0 / _this.brightPassPostProcess.width);
  84107. var sV = (1.0 / _this.brightPassPostProcess.height);
  84108. brightOffsets[0] = -0.5 * sU;
  84109. brightOffsets[1] = 0.5 * sV;
  84110. brightOffsets[2] = 0.5 * sU;
  84111. brightOffsets[3] = 0.5 * sV;
  84112. brightOffsets[4] = -0.5 * sU;
  84113. brightOffsets[5] = -0.5 * sV;
  84114. brightOffsets[6] = 0.5 * sU;
  84115. brightOffsets[7] = -0.5 * sV;
  84116. effect.setArray2("dsOffsets", brightOffsets);
  84117. effect.setFloat("brightThreshold", _this.brightThreshold);
  84118. };
  84119. // Add to pipeline
  84120. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  84121. };
  84122. // Create blur H&V post-processes
  84123. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  84124. var _this = this;
  84125. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  84126. var engine = scene.getEngine();
  84127. 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);
  84128. 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);
  84129. blurX.onActivateObservable.add(function () {
  84130. var dw = blurX.width / engine.getRenderWidth();
  84131. blurX.kernel = _this[blurWidthKey] * dw;
  84132. });
  84133. blurY.onActivateObservable.add(function () {
  84134. var dw = blurY.height / engine.getRenderHeight();
  84135. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  84136. });
  84137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  84138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  84139. this.blurHPostProcesses.push(blurX);
  84140. this.blurVPostProcesses.push(blurY);
  84141. };
  84142. // Create texture adder post-process
  84143. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  84144. var _this = this;
  84145. 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);
  84146. this.textureAdderPostProcess.onApply = function (effect) {
  84147. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  84148. effect.setTexture("lensSampler", _this.lensTexture);
  84149. effect.setFloat("exposure", _this.exposure);
  84150. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  84151. };
  84152. // Add to pipeline
  84153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  84154. };
  84155. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  84156. var _this = this;
  84157. var geometryRenderer = scene.enableGeometryBufferRenderer();
  84158. geometryRenderer.enablePosition = true;
  84159. var geometry = geometryRenderer.getGBuffer();
  84160. // Base post-process
  84161. 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));
  84162. var depthValues = BABYLON.Vector2.Zero();
  84163. this.volumetricLightPostProcess.onApply = function (effect) {
  84164. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  84165. var generator = _this.sourceLight.getShadowGenerator();
  84166. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  84167. effect.setTexture("positionSampler", geometry.textures[2]);
  84168. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  84169. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  84170. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  84171. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  84172. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  84173. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  84174. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  84175. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  84176. effect.setVector2("depthValues", depthValues);
  84177. }
  84178. };
  84179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  84180. // Smooth
  84181. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  84182. // Merge
  84183. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  84184. this.volumetricLightMergePostProces.onApply = function (effect) {
  84185. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  84186. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  84187. };
  84188. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  84189. };
  84190. // Create luminance
  84191. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  84192. var _this = this;
  84193. // Create luminance
  84194. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  84195. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  84196. var offsets = [];
  84197. this.luminancePostProcess.onApply = function (effect) {
  84198. var sU = (1.0 / _this.luminancePostProcess.width);
  84199. var sV = (1.0 / _this.luminancePostProcess.height);
  84200. offsets[0] = -0.5 * sU;
  84201. offsets[1] = 0.5 * sV;
  84202. offsets[2] = 0.5 * sU;
  84203. offsets[3] = 0.5 * sV;
  84204. offsets[4] = -0.5 * sU;
  84205. offsets[5] = -0.5 * sV;
  84206. offsets[6] = 0.5 * sU;
  84207. offsets[7] = -0.5 * sV;
  84208. effect.setArray2("lumOffsets", offsets);
  84209. };
  84210. // Add to pipeline
  84211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  84212. // Create down sample luminance
  84213. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  84214. var size = Math.pow(3, i);
  84215. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  84216. if (i === 0) {
  84217. defines += "#define FINAL_DOWN_SAMPLER";
  84218. }
  84219. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  84220. this.luminanceDownSamplePostProcesses.push(postProcess);
  84221. }
  84222. // Create callbacks and add effects
  84223. var lastLuminance = this.luminancePostProcess;
  84224. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  84225. var downSampleOffsets = new Array(18);
  84226. pp.onApply = function (effect) {
  84227. if (!lastLuminance) {
  84228. return;
  84229. }
  84230. var id = 0;
  84231. for (var x = -1; x < 2; x++) {
  84232. for (var y = -1; y < 2; y++) {
  84233. downSampleOffsets[id] = x / lastLuminance.width;
  84234. downSampleOffsets[id + 1] = y / lastLuminance.height;
  84235. id += 2;
  84236. }
  84237. }
  84238. effect.setArray2("dsOffsets", downSampleOffsets);
  84239. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  84240. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  84241. lastLuminance = _this.luminancePostProcess;
  84242. }
  84243. else {
  84244. lastLuminance = pp;
  84245. }
  84246. };
  84247. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  84248. pp.onAfterRender = function (effect) {
  84249. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  84250. 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);
  84251. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  84252. };
  84253. }
  84254. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  84255. });
  84256. };
  84257. // Create HDR post-process
  84258. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  84259. var _this = this;
  84260. 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);
  84261. var outputLiminance = 1;
  84262. var time = 0;
  84263. var lastTime = 0;
  84264. this.hdrPostProcess.onApply = function (effect) {
  84265. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  84266. time += scene.getEngine().getDeltaTime();
  84267. if (outputLiminance < 0) {
  84268. outputLiminance = _this._hdrCurrentLuminance;
  84269. }
  84270. else {
  84271. var dt = (lastTime - time) / 1000.0;
  84272. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  84273. outputLiminance += _this.hdrDecreaseRate * dt;
  84274. }
  84275. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  84276. outputLiminance -= _this.hdrIncreaseRate * dt;
  84277. }
  84278. else {
  84279. outputLiminance = _this._hdrCurrentLuminance;
  84280. }
  84281. }
  84282. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  84283. effect.setFloat("averageLuminance", outputLiminance);
  84284. lastTime = time;
  84285. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  84286. };
  84287. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  84288. };
  84289. // Create lens flare post-process
  84290. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  84291. var _this = this;
  84292. 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);
  84293. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  84294. this._createBlurPostProcesses(scene, ratio / 4, 2);
  84295. 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);
  84296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  84297. var resolution = new BABYLON.Vector2(0, 0);
  84298. // Lens flare
  84299. this.lensFlarePostProcess.onApply = function (effect) {
  84300. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  84301. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  84302. effect.setFloat("strength", _this.lensFlareStrength);
  84303. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  84304. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  84305. // Shift
  84306. resolution.x = _this.lensFlarePostProcess.width;
  84307. resolution.y = _this.lensFlarePostProcess.height;
  84308. effect.setVector2("resolution", resolution);
  84309. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  84310. };
  84311. // Compose
  84312. 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);
  84313. 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);
  84314. this.lensFlareComposePostProcess.onApply = function (effect) {
  84315. if (!_this._scene.activeCamera) {
  84316. return;
  84317. }
  84318. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  84319. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  84320. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  84321. // Lens start rotation matrix
  84322. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  84323. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  84324. 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));
  84325. camRot *= 4.0;
  84326. 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);
  84327. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  84328. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  84329. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  84330. };
  84331. };
  84332. // Create depth-of-field post-process
  84333. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  84334. var _this = this;
  84335. 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);
  84336. this.depthOfFieldPostProcess.onApply = function (effect) {
  84337. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  84338. effect.setTexture("depthSampler", _this._getDepthTexture());
  84339. effect.setFloat("distance", _this.depthOfFieldDistance);
  84340. };
  84341. // Add to pipeline
  84342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  84343. };
  84344. // Create motion blur post-process
  84345. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  84346. var _this = this;
  84347. 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);
  84348. var motionScale = 0;
  84349. var prevViewProjection = BABYLON.Matrix.Identity();
  84350. var invViewProjection = BABYLON.Matrix.Identity();
  84351. var viewProjection = BABYLON.Matrix.Identity();
  84352. var screenSize = BABYLON.Vector2.Zero();
  84353. this.motionBlurPostProcess.onApply = function (effect) {
  84354. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  84355. viewProjection.invertToRef(invViewProjection);
  84356. effect.setMatrix("inverseViewProjection", invViewProjection);
  84357. effect.setMatrix("prevViewProjection", prevViewProjection);
  84358. prevViewProjection = viewProjection;
  84359. screenSize.x = _this.motionBlurPostProcess.width;
  84360. screenSize.y = _this.motionBlurPostProcess.height;
  84361. effect.setVector2("screenSize", screenSize);
  84362. motionScale = scene.getEngine().getFps() / 60.0;
  84363. effect.setFloat("motionScale", motionScale);
  84364. effect.setFloat("motionStrength", _this.motionStrength);
  84365. effect.setTexture("depthSampler", _this._getDepthTexture());
  84366. };
  84367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  84368. };
  84369. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  84370. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  84371. var renderer = this._scene.enableGeometryBufferRenderer();
  84372. return renderer.getGBuffer().textures[0];
  84373. }
  84374. return this._scene.enableDepthRenderer().getDepthMap();
  84375. };
  84376. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  84377. for (var i = 0; i < this._cameras.length; i++) {
  84378. var camera = this._cameras[i];
  84379. if (this.originalPostProcess) {
  84380. this.originalPostProcess.dispose(camera);
  84381. }
  84382. if (this.downSampleX4PostProcess) {
  84383. this.downSampleX4PostProcess.dispose(camera);
  84384. }
  84385. if (this.brightPassPostProcess) {
  84386. this.brightPassPostProcess.dispose(camera);
  84387. }
  84388. if (this.textureAdderPostProcess) {
  84389. this.textureAdderPostProcess.dispose(camera);
  84390. }
  84391. if (this.textureAdderFinalPostProcess) {
  84392. this.textureAdderFinalPostProcess.dispose(camera);
  84393. }
  84394. if (this.volumetricLightPostProcess) {
  84395. this.volumetricLightPostProcess.dispose(camera);
  84396. }
  84397. if (this.volumetricLightSmoothXPostProcess) {
  84398. this.volumetricLightSmoothXPostProcess.dispose(camera);
  84399. }
  84400. if (this.volumetricLightSmoothYPostProcess) {
  84401. this.volumetricLightSmoothYPostProcess.dispose(camera);
  84402. }
  84403. if (this.volumetricLightMergePostProces) {
  84404. this.volumetricLightMergePostProces.dispose(camera);
  84405. }
  84406. if (this.volumetricLightFinalPostProcess) {
  84407. this.volumetricLightFinalPostProcess.dispose(camera);
  84408. }
  84409. if (this.lensFlarePostProcess) {
  84410. this.lensFlarePostProcess.dispose(camera);
  84411. }
  84412. if (this.lensFlareComposePostProcess) {
  84413. this.lensFlareComposePostProcess.dispose(camera);
  84414. }
  84415. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  84416. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  84417. }
  84418. if (this.luminancePostProcess) {
  84419. this.luminancePostProcess.dispose(camera);
  84420. }
  84421. if (this.hdrPostProcess) {
  84422. this.hdrPostProcess.dispose(camera);
  84423. }
  84424. if (this.hdrFinalPostProcess) {
  84425. this.hdrFinalPostProcess.dispose(camera);
  84426. }
  84427. if (this.depthOfFieldPostProcess) {
  84428. this.depthOfFieldPostProcess.dispose(camera);
  84429. }
  84430. if (this.motionBlurPostProcess) {
  84431. this.motionBlurPostProcess.dispose(camera);
  84432. }
  84433. if (this.fxaaPostProcess) {
  84434. this.fxaaPostProcess.dispose(camera);
  84435. }
  84436. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  84437. this.blurHPostProcesses[j].dispose(camera);
  84438. }
  84439. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  84440. this.blurVPostProcesses[j].dispose(camera);
  84441. }
  84442. }
  84443. this.originalPostProcess = null;
  84444. this.downSampleX4PostProcess = null;
  84445. this.brightPassPostProcess = null;
  84446. this.textureAdderPostProcess = null;
  84447. this.textureAdderFinalPostProcess = null;
  84448. this.volumetricLightPostProcess = null;
  84449. this.volumetricLightSmoothXPostProcess = null;
  84450. this.volumetricLightSmoothYPostProcess = null;
  84451. this.volumetricLightMergePostProces = null;
  84452. this.volumetricLightFinalPostProcess = null;
  84453. this.lensFlarePostProcess = null;
  84454. this.lensFlareComposePostProcess = null;
  84455. this.luminancePostProcess = null;
  84456. this.hdrPostProcess = null;
  84457. this.hdrFinalPostProcess = null;
  84458. this.depthOfFieldPostProcess = null;
  84459. this.motionBlurPostProcess = null;
  84460. this.fxaaPostProcess = null;
  84461. this.luminanceDownSamplePostProcesses = [];
  84462. this.blurHPostProcesses = [];
  84463. this.blurVPostProcesses = [];
  84464. };
  84465. /**
  84466. * Dispose of the pipeline and stop all post processes
  84467. */
  84468. StandardRenderingPipeline.prototype.dispose = function () {
  84469. this._disposePostProcesses();
  84470. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84471. _super.prototype.dispose.call(this);
  84472. };
  84473. /**
  84474. * Serialize the rendering pipeline (Used when exporting)
  84475. * @returns the serialized object
  84476. */
  84477. StandardRenderingPipeline.prototype.serialize = function () {
  84478. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84479. if (this.sourceLight) {
  84480. serializationObject.sourceLightId = this.sourceLight.id;
  84481. }
  84482. serializationObject.customType = "StandardRenderingPipeline";
  84483. return serializationObject;
  84484. };
  84485. /**
  84486. * Parse the serialized pipeline
  84487. * @param source Source pipeline.
  84488. * @param scene The scene to load the pipeline to.
  84489. * @param rootUrl The URL of the serialized pipeline.
  84490. * @returns An instantiated pipeline from the serialized object.
  84491. */
  84492. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84493. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84494. if (source.sourceLightId) {
  84495. p.sourceLight = scene.getLightByID(source.sourceLightId);
  84496. }
  84497. return p;
  84498. };
  84499. // Luminance steps
  84500. StandardRenderingPipeline.LuminanceSteps = 6;
  84501. __decorate([
  84502. BABYLON.serialize()
  84503. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  84504. __decorate([
  84505. BABYLON.serialize()
  84506. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  84507. __decorate([
  84508. BABYLON.serialize()
  84509. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  84510. __decorate([
  84511. BABYLON.serialize()
  84512. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  84513. __decorate([
  84514. BABYLON.serializeAsTexture("lensTexture")
  84515. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  84516. __decorate([
  84517. BABYLON.serialize()
  84518. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  84519. __decorate([
  84520. BABYLON.serialize()
  84521. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  84522. __decorate([
  84523. BABYLON.serialize()
  84524. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  84525. __decorate([
  84526. BABYLON.serialize()
  84527. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  84528. __decorate([
  84529. BABYLON.serialize()
  84530. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  84531. __decorate([
  84532. BABYLON.serialize()
  84533. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  84534. __decorate([
  84535. BABYLON.serializeAsTexture("lensColorTexture")
  84536. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  84537. __decorate([
  84538. BABYLON.serialize()
  84539. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  84540. __decorate([
  84541. BABYLON.serialize()
  84542. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  84543. __decorate([
  84544. BABYLON.serialize()
  84545. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  84546. __decorate([
  84547. BABYLON.serialize()
  84548. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  84549. __decorate([
  84550. BABYLON.serializeAsTexture("lensStarTexture")
  84551. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  84552. __decorate([
  84553. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  84554. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  84555. __decorate([
  84556. BABYLON.serialize()
  84557. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  84558. __decorate([
  84559. BABYLON.serialize()
  84560. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  84561. __decorate([
  84562. BABYLON.serialize()
  84563. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  84564. __decorate([
  84565. BABYLON.serialize()
  84566. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  84567. __decorate([
  84568. BABYLON.serialize()
  84569. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  84570. __decorate([
  84571. BABYLON.serialize()
  84572. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  84573. __decorate([
  84574. BABYLON.serialize()
  84575. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  84576. __decorate([
  84577. BABYLON.serialize()
  84578. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  84579. __decorate([
  84580. BABYLON.serialize()
  84581. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  84582. __decorate([
  84583. BABYLON.serialize()
  84584. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  84585. __decorate([
  84586. BABYLON.serialize()
  84587. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  84588. __decorate([
  84589. BABYLON.serialize()
  84590. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  84591. __decorate([
  84592. BABYLON.serialize()
  84593. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  84594. __decorate([
  84595. BABYLON.serialize()
  84596. ], StandardRenderingPipeline.prototype, "samples", null);
  84597. return StandardRenderingPipeline;
  84598. }(BABYLON.PostProcessRenderPipeline));
  84599. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  84600. })(BABYLON || (BABYLON = {}));
  84601. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  84602. var BABYLON;
  84603. (function (BABYLON) {
  84604. var FxaaPostProcess = /** @class */ (function (_super) {
  84605. __extends(FxaaPostProcess, _super);
  84606. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  84607. if (camera === void 0) { camera = null; }
  84608. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84609. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  84610. var defines = _this._getDefines();
  84611. _this.updateEffect(defines);
  84612. _this.onApplyObservable.add(function (effect) {
  84613. var texelSize = _this.texelSize;
  84614. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  84615. });
  84616. return _this;
  84617. }
  84618. FxaaPostProcess.prototype._getDefines = function () {
  84619. var engine = this.getEngine();
  84620. if (!engine) {
  84621. return null;
  84622. }
  84623. var glInfo = engine.getGlInfo();
  84624. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  84625. return "#define MALI 1\n";
  84626. }
  84627. return null;
  84628. };
  84629. return FxaaPostProcess;
  84630. }(BABYLON.PostProcess));
  84631. BABYLON.FxaaPostProcess = FxaaPostProcess;
  84632. })(BABYLON || (BABYLON = {}));
  84633. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  84634. var BABYLON;
  84635. (function (BABYLON) {
  84636. /**
  84637. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  84638. */
  84639. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  84640. __extends(ChromaticAberrationPostProcess, _super);
  84641. /**
  84642. * Creates a new instance ChromaticAberrationPostProcess
  84643. * @param name The name of the effect.
  84644. * @param screenWidth The width of the screen to apply the effect on.
  84645. * @param screenHeight The height of the screen to apply the effect on.
  84646. * @param options The required width/height ratio to downsize to before computing the render pass.
  84647. * @param camera The camera to apply the render pass to.
  84648. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84649. * @param engine The engine which the post process will be applied. (default: current engine)
  84650. * @param reusable If the post process can be reused on the same frame. (default: false)
  84651. * @param textureType Type of textures used when performing the post process. (default: 0)
  84652. * @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)
  84653. */
  84654. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84655. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84656. if (blockCompilation === void 0) { blockCompilation = false; }
  84657. 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;
  84658. /**
  84659. * The amount of seperation of rgb channels (default: 30)
  84660. */
  84661. _this.aberrationAmount = 30;
  84662. /**
  84663. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  84664. */
  84665. _this.radialIntensity = 0;
  84666. /**
  84667. * 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))
  84668. */
  84669. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  84670. /**
  84671. * 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))
  84672. */
  84673. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  84674. _this.onApplyObservable.add(function (effect) {
  84675. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  84676. effect.setFloat('screen_width', screenWidth);
  84677. effect.setFloat('screen_height', screenHeight);
  84678. effect.setFloat('radialIntensity', _this.radialIntensity);
  84679. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  84680. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  84681. });
  84682. return _this;
  84683. }
  84684. return ChromaticAberrationPostProcess;
  84685. }(BABYLON.PostProcess));
  84686. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  84687. })(BABYLON || (BABYLON = {}));
  84688. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  84689. var BABYLON;
  84690. (function (BABYLON) {
  84691. /**
  84692. * The GrainPostProcess adds noise to the image at mid luminance levels
  84693. */
  84694. var GrainPostProcess = /** @class */ (function (_super) {
  84695. __extends(GrainPostProcess, _super);
  84696. /**
  84697. * Creates a new instance of @see GrainPostProcess
  84698. * @param name The name of the effect.
  84699. * @param options The required width/height ratio to downsize to before computing the render pass.
  84700. * @param camera The camera to apply the render pass to.
  84701. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84702. * @param engine The engine which the post process will be applied. (default: current engine)
  84703. * @param reusable If the post process can be reused on the same frame. (default: false)
  84704. * @param textureType Type of textures used when performing the post process. (default: 0)
  84705. * @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)
  84706. */
  84707. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84708. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84709. if (blockCompilation === void 0) { blockCompilation = false; }
  84710. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84711. /**
  84712. * The intensity of the grain added (default: 30)
  84713. */
  84714. _this.intensity = 30;
  84715. /**
  84716. * If the grain should be randomized on every frame
  84717. */
  84718. _this.animated = false;
  84719. _this.onApplyObservable.add(function (effect) {
  84720. effect.setFloat('intensity', _this.intensity);
  84721. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  84722. });
  84723. return _this;
  84724. }
  84725. return GrainPostProcess;
  84726. }(BABYLON.PostProcess));
  84727. BABYLON.GrainPostProcess = GrainPostProcess;
  84728. })(BABYLON || (BABYLON = {}));
  84729. //# sourceMappingURL=babylon.grainPostProcess.js.map
  84730. var BABYLON;
  84731. (function (BABYLON) {
  84732. /**
  84733. * The SharpenPostProcess applies a sharpen kernel to every pixel
  84734. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  84735. */
  84736. var SharpenPostProcess = /** @class */ (function (_super) {
  84737. __extends(SharpenPostProcess, _super);
  84738. /**
  84739. * Creates a new instance ConvolutionPostProcess
  84740. * @param name The name of the effect.
  84741. * @param options The required width/height ratio to downsize to before computing the render pass.
  84742. * @param camera The camera to apply the render pass to.
  84743. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84744. * @param engine The engine which the post process will be applied. (default: current engine)
  84745. * @param reusable If the post process can be reused on the same frame. (default: false)
  84746. * @param textureType Type of textures used when performing the post process. (default: 0)
  84747. * @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)
  84748. */
  84749. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84750. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84751. if (blockCompilation === void 0) { blockCompilation = false; }
  84752. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84753. /**
  84754. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  84755. */
  84756. _this.colorAmount = 1.0;
  84757. /**
  84758. * How much sharpness should be applied (default: 0.3)
  84759. */
  84760. _this.edgeAmount = 0.3;
  84761. _this.onApply = function (effect) {
  84762. effect.setFloat2("screenSize", _this.width, _this.height);
  84763. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  84764. };
  84765. return _this;
  84766. }
  84767. return SharpenPostProcess;
  84768. }(BABYLON.PostProcess));
  84769. BABYLON.SharpenPostProcess = SharpenPostProcess;
  84770. })(BABYLON || (BABYLON = {}));
  84771. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  84772. var BABYLON;
  84773. (function (BABYLON) {
  84774. /**
  84775. * The Blur Post Process which blurs an image based on a kernel and direction.
  84776. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  84777. */
  84778. var BlurPostProcess = /** @class */ (function (_super) {
  84779. __extends(BlurPostProcess, _super);
  84780. /**
  84781. * Creates a new instance BlurPostProcess
  84782. * @param name The name of the effect.
  84783. * @param direction The direction in which to blur the image.
  84784. * @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.
  84785. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  84786. * @param camera The camera to apply the render pass to.
  84787. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84788. * @param engine The engine which the post process will be applied. (default: current engine)
  84789. * @param reusable If the post process can be reused on the same frame. (default: false)
  84790. * @param textureType Type of textures used when performing the post process. (default: 0)
  84791. * @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)
  84792. */
  84793. function BlurPostProcess(name,
  84794. /** The direction in which to blur the image. */
  84795. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  84796. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84797. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84798. if (defines === void 0) { defines = ""; }
  84799. if (blockCompilation === void 0) { blockCompilation = false; }
  84800. 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;
  84801. _this.direction = direction;
  84802. _this.blockCompilation = blockCompilation;
  84803. _this._packedFloat = false;
  84804. _this._staticDefines = "";
  84805. _this._staticDefines = defines;
  84806. _this.onApplyObservable.add(function (effect) {
  84807. if (_this._outputTexture) {
  84808. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  84809. }
  84810. else {
  84811. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  84812. }
  84813. });
  84814. _this.kernel = kernel;
  84815. return _this;
  84816. }
  84817. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  84818. /**
  84819. * Gets the length in pixels of the blur sample region
  84820. */
  84821. get: function () {
  84822. return this._idealKernel;
  84823. },
  84824. /**
  84825. * Sets the length in pixels of the blur sample region
  84826. */
  84827. set: function (v) {
  84828. if (this._idealKernel === v) {
  84829. return;
  84830. }
  84831. v = Math.max(v, 1);
  84832. this._idealKernel = v;
  84833. this._kernel = this._nearestBestKernel(v);
  84834. if (!this.blockCompilation) {
  84835. this._updateParameters();
  84836. }
  84837. },
  84838. enumerable: true,
  84839. configurable: true
  84840. });
  84841. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  84842. /**
  84843. * Gets wether or not the blur is unpacking/repacking floats
  84844. */
  84845. get: function () {
  84846. return this._packedFloat;
  84847. },
  84848. /**
  84849. * Sets wether or not the blur needs to unpack/repack floats
  84850. */
  84851. set: function (v) {
  84852. if (this._packedFloat === v) {
  84853. return;
  84854. }
  84855. this._packedFloat = v;
  84856. if (!this.blockCompilation) {
  84857. this._updateParameters();
  84858. }
  84859. },
  84860. enumerable: true,
  84861. configurable: true
  84862. });
  84863. /**
  84864. * Updates the effect with the current post process compile time values and recompiles the shader.
  84865. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  84866. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  84867. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  84868. * @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
  84869. * @param onCompiled Called when the shader has been compiled.
  84870. * @param onError Called if there is an error when compiling a shader.
  84871. */
  84872. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  84873. if (defines === void 0) { defines = null; }
  84874. if (uniforms === void 0) { uniforms = null; }
  84875. if (samplers === void 0) { samplers = null; }
  84876. this._updateParameters(onCompiled, onError);
  84877. };
  84878. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  84879. // Generate sampling offsets and weights
  84880. var N = this._kernel;
  84881. var centerIndex = (N - 1) / 2;
  84882. // Generate Gaussian sampling weights over kernel
  84883. var offsets = [];
  84884. var weights = [];
  84885. var totalWeight = 0;
  84886. for (var i = 0; i < N; i++) {
  84887. var u = i / (N - 1);
  84888. var w = this._gaussianWeight(u * 2.0 - 1);
  84889. offsets[i] = (i - centerIndex);
  84890. weights[i] = w;
  84891. totalWeight += w;
  84892. }
  84893. // Normalize weights
  84894. for (var i = 0; i < weights.length; i++) {
  84895. weights[i] /= totalWeight;
  84896. }
  84897. // Optimize: combine samples to take advantage of hardware linear sampling
  84898. // Walk from left to center, combining pairs (symmetrically)
  84899. var linearSamplingWeights = [];
  84900. var linearSamplingOffsets = [];
  84901. var linearSamplingMap = [];
  84902. for (var i = 0; i <= centerIndex; i += 2) {
  84903. var j = Math.min(i + 1, Math.floor(centerIndex));
  84904. var singleCenterSample = i === j;
  84905. if (singleCenterSample) {
  84906. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84907. }
  84908. else {
  84909. var sharedCell = j === centerIndex;
  84910. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  84911. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  84912. if (offsetLinear === 0) {
  84913. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84914. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  84915. }
  84916. else {
  84917. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  84918. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  84919. }
  84920. }
  84921. }
  84922. for (var i = 0; i < linearSamplingMap.length; i++) {
  84923. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  84924. linearSamplingWeights[i] = linearSamplingMap[i].w;
  84925. }
  84926. // Replace with optimized
  84927. offsets = linearSamplingOffsets;
  84928. weights = linearSamplingWeights;
  84929. // Generate shaders
  84930. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  84931. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  84932. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  84933. var defines = "";
  84934. defines += this._staticDefines;
  84935. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  84936. if (this._staticDefines.indexOf("DOF") != -1) {
  84937. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  84938. varyingCount--;
  84939. }
  84940. for (var i = 0; i < varyingCount; i++) {
  84941. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  84942. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  84943. }
  84944. var depCount = 0;
  84945. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  84946. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  84947. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  84948. depCount++;
  84949. }
  84950. if (this.packedFloat) {
  84951. defines += "#define PACKEDFLOAT 1";
  84952. }
  84953. this.blockCompilation = false;
  84954. _super.prototype.updateEffect.call(this, defines, null, null, {
  84955. varyingCount: varyingCount,
  84956. depCount: depCount
  84957. }, onCompiled, onError);
  84958. };
  84959. /**
  84960. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  84961. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  84962. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  84963. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  84964. * The gaps between physical kernels are compensated for in the weighting of the samples
  84965. * @param idealKernel Ideal blur kernel.
  84966. * @return Nearest best kernel.
  84967. */
  84968. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  84969. var v = Math.round(idealKernel);
  84970. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  84971. var k = _a[_i];
  84972. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  84973. return Math.max(k, 3);
  84974. }
  84975. }
  84976. return Math.max(v, 3);
  84977. };
  84978. /**
  84979. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  84980. * @param x The point on the Gaussian distribution to sample.
  84981. * @return the value of the Gaussian function at x.
  84982. */
  84983. BlurPostProcess.prototype._gaussianWeight = function (x) {
  84984. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  84985. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  84986. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  84987. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  84988. // truncated at around 1.3% of peak strength.
  84989. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  84990. var sigma = (1 / 3);
  84991. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  84992. var exponent = -((x * x) / (2.0 * sigma * sigma));
  84993. var weight = (1.0 / denominator) * Math.exp(exponent);
  84994. return weight;
  84995. };
  84996. /**
  84997. * Generates a string that can be used as a floating point number in GLSL.
  84998. * @param x Value to print.
  84999. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  85000. * @return GLSL float string.
  85001. */
  85002. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  85003. if (decimalFigures === void 0) { decimalFigures = 8; }
  85004. return x.toFixed(decimalFigures).replace(/0+$/, '');
  85005. };
  85006. return BlurPostProcess;
  85007. }(BABYLON.PostProcess));
  85008. BABYLON.BlurPostProcess = BlurPostProcess;
  85009. })(BABYLON || (BABYLON = {}));
  85010. //# sourceMappingURL=babylon.blurPostProcess.js.map
  85011. var BABYLON;
  85012. (function (BABYLON) {
  85013. /**
  85014. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  85015. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  85016. * based on samples that have a large difference in distance than the center pixel.
  85017. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  85018. */
  85019. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  85020. __extends(DepthOfFieldBlurPostProcess, _super);
  85021. /**
  85022. * Creates a new instance CircleOfConfusionPostProcess
  85023. * @param name The name of the effect.
  85024. * @param scene The scene the effect belongs to.
  85025. * @param direction The direction the blur should be applied.
  85026. * @param kernel The size of the kernel used to blur.
  85027. * @param options The required width/height ratio to downsize to before computing the render pass.
  85028. * @param camera The camera to apply the render pass to.
  85029. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  85030. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  85031. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85032. * @param engine The engine which the post process will be applied. (default: current engine)
  85033. * @param reusable If the post process can be reused on the same frame. (default: false)
  85034. * @param textureType Type of textures used when performing the post process. (default: 0)
  85035. * @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)
  85036. */
  85037. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  85038. if (imageToBlur === void 0) { imageToBlur = null; }
  85039. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85040. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85041. if (blockCompilation === void 0) { blockCompilation = false; }
  85042. 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;
  85043. _this.direction = direction;
  85044. _this.onApplyObservable.add(function (effect) {
  85045. if (imageToBlur != null) {
  85046. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  85047. }
  85048. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  85049. if (scene.activeCamera) {
  85050. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85051. }
  85052. });
  85053. return _this;
  85054. }
  85055. return DepthOfFieldBlurPostProcess;
  85056. }(BABYLON.BlurPostProcess));
  85057. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  85058. })(BABYLON || (BABYLON = {}));
  85059. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  85060. var BABYLON;
  85061. (function (BABYLON) {
  85062. /**
  85063. * Options to be set when merging outputs from the default pipeline.
  85064. */
  85065. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  85066. function DepthOfFieldMergePostProcessOptions() {
  85067. }
  85068. return DepthOfFieldMergePostProcessOptions;
  85069. }());
  85070. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  85071. /**
  85072. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  85073. */
  85074. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  85075. __extends(DepthOfFieldMergePostProcess, _super);
  85076. /**
  85077. * Creates a new instance of DepthOfFieldMergePostProcess
  85078. * @param name The name of the effect.
  85079. * @param originalFromInput Post process which's input will be used for the merge.
  85080. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  85081. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  85082. * @param options The required width/height ratio to downsize to before computing the render pass.
  85083. * @param camera The camera to apply the render pass to.
  85084. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85085. * @param engine The engine which the post process will be applied. (default: current engine)
  85086. * @param reusable If the post process can be reused on the same frame. (default: false)
  85087. * @param textureType Type of textures used when performing the post process. (default: 0)
  85088. * @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)
  85089. */
  85090. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85091. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85092. if (blockCompilation === void 0) { blockCompilation = false; }
  85093. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  85094. _this.blurSteps = blurSteps;
  85095. _this.onApplyObservable.add(function (effect) {
  85096. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  85097. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  85098. blurSteps.forEach(function (step, index) {
  85099. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  85100. });
  85101. });
  85102. if (!blockCompilation) {
  85103. _this.updateEffect();
  85104. }
  85105. return _this;
  85106. }
  85107. /**
  85108. * Updates the effect with the current post process compile time values and recompiles the shader.
  85109. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  85110. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  85111. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  85112. * @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
  85113. * @param onCompiled Called when the shader has been compiled.
  85114. * @param onError Called if there is an error when compiling a shader.
  85115. */
  85116. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  85117. if (defines === void 0) { defines = null; }
  85118. if (uniforms === void 0) { uniforms = null; }
  85119. if (samplers === void 0) { samplers = null; }
  85120. if (!defines) {
  85121. defines = "";
  85122. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  85123. }
  85124. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  85125. };
  85126. return DepthOfFieldMergePostProcess;
  85127. }(BABYLON.PostProcess));
  85128. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  85129. })(BABYLON || (BABYLON = {}));
  85130. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  85131. var BABYLON;
  85132. (function (BABYLON) {
  85133. /**
  85134. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  85135. */
  85136. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  85137. __extends(CircleOfConfusionPostProcess, _super);
  85138. /**
  85139. * Creates a new instance CircleOfConfusionPostProcess
  85140. * @param name The name of the effect.
  85141. * @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.
  85142. * @param options The required width/height ratio to downsize to before computing the render pass.
  85143. * @param camera The camera to apply the render pass to.
  85144. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85145. * @param engine The engine which the post process will be applied. (default: current engine)
  85146. * @param reusable If the post process can be reused on the same frame. (default: false)
  85147. * @param textureType Type of textures used when performing the post process. (default: 0)
  85148. * @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)
  85149. */
  85150. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85151. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85152. if (blockCompilation === void 0) { blockCompilation = false; }
  85153. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85154. /**
  85155. * 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.
  85156. */
  85157. _this.lensSize = 50;
  85158. /**
  85159. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  85160. */
  85161. _this.fStop = 1.4;
  85162. /**
  85163. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  85164. */
  85165. _this.focusDistance = 2000;
  85166. /**
  85167. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  85168. */
  85169. _this.focalLength = 50;
  85170. _this._depthTexture = null;
  85171. _this._depthTexture = depthTexture;
  85172. _this.onApplyObservable.add(function (effect) {
  85173. if (!_this._depthTexture) {
  85174. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  85175. return;
  85176. }
  85177. effect.setTexture("depthSampler", _this._depthTexture);
  85178. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  85179. var aperture = _this.lensSize / _this.fStop;
  85180. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  85181. effect.setFloat('focusDistance', _this.focusDistance);
  85182. effect.setFloat('cocPrecalculation', cocPrecalculation);
  85183. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  85184. });
  85185. return _this;
  85186. }
  85187. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  85188. /**
  85189. * 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.
  85190. */
  85191. set: function (value) {
  85192. this._depthTexture = value;
  85193. },
  85194. enumerable: true,
  85195. configurable: true
  85196. });
  85197. return CircleOfConfusionPostProcess;
  85198. }(BABYLON.PostProcess));
  85199. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  85200. })(BABYLON || (BABYLON = {}));
  85201. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  85202. var BABYLON;
  85203. (function (BABYLON) {
  85204. /**
  85205. * Specifies the level of max blur that should be applied when using the depth of field effect
  85206. */
  85207. var DepthOfFieldEffectBlurLevel;
  85208. (function (DepthOfFieldEffectBlurLevel) {
  85209. /**
  85210. * Subtle blur
  85211. */
  85212. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  85213. /**
  85214. * Medium blur
  85215. */
  85216. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  85217. /**
  85218. * Large blur
  85219. */
  85220. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  85221. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  85222. ;
  85223. /**
  85224. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  85225. */
  85226. var DepthOfFieldEffect = /** @class */ (function (_super) {
  85227. __extends(DepthOfFieldEffect, _super);
  85228. /**
  85229. * Creates a new instance DepthOfFieldEffect
  85230. * @param scene The scene the effect belongs to.
  85231. * @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.
  85232. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  85233. * @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)
  85234. */
  85235. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  85236. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  85237. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  85238. if (blockCompilation === void 0) { blockCompilation = false; }
  85239. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  85240. return _this._effects;
  85241. }, true) || this;
  85242. /**
  85243. * @hidden Internal post processes in depth of field effect
  85244. */
  85245. _this._effects = [];
  85246. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  85247. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85248. // 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)
  85249. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  85250. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  85251. _this._depthOfFieldBlurY = [];
  85252. _this._depthOfFieldBlurX = [];
  85253. var blurCount = 1;
  85254. var kernelSize = 15;
  85255. switch (blurLevel) {
  85256. case DepthOfFieldEffectBlurLevel.High: {
  85257. blurCount = 3;
  85258. kernelSize = 51;
  85259. break;
  85260. }
  85261. case DepthOfFieldEffectBlurLevel.Medium: {
  85262. blurCount = 2;
  85263. kernelSize = 31;
  85264. break;
  85265. }
  85266. default: {
  85267. kernelSize = 15;
  85268. blurCount = 1;
  85269. break;
  85270. }
  85271. }
  85272. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  85273. var ratio = 1.0;
  85274. for (var i = 0; i < blurCount; i++) {
  85275. 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);
  85276. blurY.autoClear = false;
  85277. ratio = 0.75 / Math.pow(2, i);
  85278. 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);
  85279. blurX.autoClear = false;
  85280. _this._depthOfFieldBlurY.push(blurY);
  85281. _this._depthOfFieldBlurX.push(blurX);
  85282. }
  85283. // Set all post processes on the effect.
  85284. _this._effects = [_this._circleOfConfusion];
  85285. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  85286. _this._effects.push(_this._depthOfFieldBlurY[i]);
  85287. _this._effects.push(_this._depthOfFieldBlurX[i]);
  85288. }
  85289. // Merge blurred images with original image based on circleOfConfusion
  85290. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85291. _this._dofMerge.autoClear = false;
  85292. _this._effects.push(_this._dofMerge);
  85293. return _this;
  85294. }
  85295. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  85296. get: function () {
  85297. return this._circleOfConfusion.focalLength;
  85298. },
  85299. /**
  85300. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  85301. */
  85302. set: function (value) {
  85303. this._circleOfConfusion.focalLength = value;
  85304. },
  85305. enumerable: true,
  85306. configurable: true
  85307. });
  85308. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  85309. get: function () {
  85310. return this._circleOfConfusion.fStop;
  85311. },
  85312. /**
  85313. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  85314. */
  85315. set: function (value) {
  85316. this._circleOfConfusion.fStop = value;
  85317. },
  85318. enumerable: true,
  85319. configurable: true
  85320. });
  85321. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  85322. get: function () {
  85323. return this._circleOfConfusion.focusDistance;
  85324. },
  85325. /**
  85326. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  85327. */
  85328. set: function (value) {
  85329. this._circleOfConfusion.focusDistance = value;
  85330. },
  85331. enumerable: true,
  85332. configurable: true
  85333. });
  85334. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  85335. get: function () {
  85336. return this._circleOfConfusion.lensSize;
  85337. },
  85338. /**
  85339. * 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.
  85340. */
  85341. set: function (value) {
  85342. this._circleOfConfusion.lensSize = value;
  85343. },
  85344. enumerable: true,
  85345. configurable: true
  85346. });
  85347. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  85348. /**
  85349. * 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.
  85350. */
  85351. set: function (value) {
  85352. this._circleOfConfusion.depthTexture = value;
  85353. },
  85354. enumerable: true,
  85355. configurable: true
  85356. });
  85357. /**
  85358. * Disposes each of the internal effects for a given camera.
  85359. * @param camera The camera to dispose the effect on.
  85360. */
  85361. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  85362. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85363. this._effects[effectIndex].dispose(camera);
  85364. }
  85365. };
  85366. /**
  85367. * @hidden Internal
  85368. */
  85369. DepthOfFieldEffect.prototype._updateEffects = function () {
  85370. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85371. this._effects[effectIndex].updateEffect();
  85372. }
  85373. };
  85374. /**
  85375. * Internal
  85376. * @returns if all the contained post processes are ready.
  85377. * @hidden
  85378. */
  85379. DepthOfFieldEffect.prototype._isReady = function () {
  85380. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85381. if (!this._effects[effectIndex].isReady()) {
  85382. return false;
  85383. }
  85384. }
  85385. return true;
  85386. };
  85387. return DepthOfFieldEffect;
  85388. }(BABYLON.PostProcessRenderEffect));
  85389. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  85390. })(BABYLON || (BABYLON = {}));
  85391. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  85392. var BABYLON;
  85393. (function (BABYLON) {
  85394. /**
  85395. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  85396. */
  85397. var BloomMergePostProcess = /** @class */ (function (_super) {
  85398. __extends(BloomMergePostProcess, _super);
  85399. /**
  85400. * Creates a new instance of @see BloomMergePostProcess
  85401. * @param name The name of the effect.
  85402. * @param originalFromInput Post process which's input will be used for the merge.
  85403. * @param blurred Blurred highlights post process which's output will be used.
  85404. * @param weight Weight of the bloom to be added to the original input.
  85405. * @param options The required width/height ratio to downsize to before computing the render pass.
  85406. * @param camera The camera to apply the render pass to.
  85407. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85408. * @param engine The engine which the post process will be applied. (default: current engine)
  85409. * @param reusable If the post process can be reused on the same frame. (default: false)
  85410. * @param textureType Type of textures used when performing the post process. (default: 0)
  85411. * @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)
  85412. */
  85413. function BloomMergePostProcess(name, originalFromInput, blurred,
  85414. /** Weight of the bloom to be added to the original input. */
  85415. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85417. if (blockCompilation === void 0) { blockCompilation = false; }
  85418. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  85419. _this.weight = weight;
  85420. _this.onApplyObservable.add(function (effect) {
  85421. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  85422. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  85423. effect.setFloat("bloomWeight", _this.weight);
  85424. });
  85425. if (!blockCompilation) {
  85426. _this.updateEffect();
  85427. }
  85428. return _this;
  85429. }
  85430. return BloomMergePostProcess;
  85431. }(BABYLON.PostProcess));
  85432. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  85433. })(BABYLON || (BABYLON = {}));
  85434. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  85435. var BABYLON;
  85436. (function (BABYLON) {
  85437. /**
  85438. * 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.
  85439. */
  85440. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  85441. __extends(ExtractHighlightsPostProcess, _super);
  85442. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85443. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85444. if (blockCompilation === void 0) { blockCompilation = false; }
  85445. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85446. /**
  85447. * The luminance threshold, pixels below this value will be set to black.
  85448. */
  85449. _this.threshold = 0.9;
  85450. /** @hidden */
  85451. _this._exposure = 1;
  85452. /**
  85453. * Post process which has the input texture to be used when performing highlight extraction
  85454. * @hidden
  85455. */
  85456. _this._inputPostProcess = null;
  85457. _this.onApplyObservable.add(function (effect) {
  85458. if (_this._inputPostProcess) {
  85459. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  85460. }
  85461. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  85462. effect.setFloat('exposure', _this._exposure);
  85463. });
  85464. return _this;
  85465. }
  85466. return ExtractHighlightsPostProcess;
  85467. }(BABYLON.PostProcess));
  85468. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  85469. })(BABYLON || (BABYLON = {}));
  85470. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  85471. var BABYLON;
  85472. (function (BABYLON) {
  85473. /**
  85474. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  85475. */
  85476. var BloomEffect = /** @class */ (function (_super) {
  85477. __extends(BloomEffect, _super);
  85478. /**
  85479. * Creates a new instance of @see BloomEffect
  85480. * @param scene The scene the effect belongs to.
  85481. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  85482. * @param bloomKernel The size of the kernel to be used when applying the blur.
  85483. * @param bloomWeight The the strength of bloom.
  85484. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  85485. * @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)
  85486. */
  85487. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  85488. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  85489. if (blockCompilation === void 0) { blockCompilation = false; }
  85490. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  85491. return _this._effects;
  85492. }, true) || this;
  85493. _this.bloomScale = bloomScale;
  85494. /**
  85495. * @hidden Internal
  85496. */
  85497. _this._effects = [];
  85498. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85499. _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);
  85500. _this._blurX.alwaysForcePOT = true;
  85501. _this._blurX.autoClear = false;
  85502. _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);
  85503. _this._blurY.alwaysForcePOT = true;
  85504. _this._blurY.autoClear = false;
  85505. _this.kernel = bloomKernel;
  85506. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  85507. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85508. _this._merge.autoClear = false;
  85509. _this._effects.push(_this._merge);
  85510. return _this;
  85511. }
  85512. Object.defineProperty(BloomEffect.prototype, "threshold", {
  85513. /**
  85514. * The luminance threshold to find bright areas of the image to bloom.
  85515. */
  85516. get: function () {
  85517. return this._downscale.threshold;
  85518. },
  85519. set: function (value) {
  85520. this._downscale.threshold = value;
  85521. },
  85522. enumerable: true,
  85523. configurable: true
  85524. });
  85525. Object.defineProperty(BloomEffect.prototype, "weight", {
  85526. /**
  85527. * The strength of the bloom.
  85528. */
  85529. get: function () {
  85530. return this._merge.weight;
  85531. },
  85532. set: function (value) {
  85533. this._merge.weight = value;
  85534. },
  85535. enumerable: true,
  85536. configurable: true
  85537. });
  85538. Object.defineProperty(BloomEffect.prototype, "kernel", {
  85539. /**
  85540. * Specifies the size of the bloom blur kernel, relative to the final output size
  85541. */
  85542. get: function () {
  85543. return this._blurX.kernel / this.bloomScale;
  85544. },
  85545. set: function (value) {
  85546. this._blurX.kernel = value * this.bloomScale;
  85547. this._blurY.kernel = value * this.bloomScale;
  85548. },
  85549. enumerable: true,
  85550. configurable: true
  85551. });
  85552. /**
  85553. * Disposes each of the internal effects for a given camera.
  85554. * @param camera The camera to dispose the effect on.
  85555. */
  85556. BloomEffect.prototype.disposeEffects = function (camera) {
  85557. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85558. this._effects[effectIndex].dispose(camera);
  85559. }
  85560. };
  85561. /**
  85562. * @hidden Internal
  85563. */
  85564. BloomEffect.prototype._updateEffects = function () {
  85565. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85566. this._effects[effectIndex].updateEffect();
  85567. }
  85568. };
  85569. /**
  85570. * Internal
  85571. * @returns if all the contained post processes are ready.
  85572. * @hidden
  85573. */
  85574. BloomEffect.prototype._isReady = function () {
  85575. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85576. if (!this._effects[effectIndex].isReady()) {
  85577. return false;
  85578. }
  85579. }
  85580. return true;
  85581. };
  85582. return BloomEffect;
  85583. }(BABYLON.PostProcessRenderEffect));
  85584. BABYLON.BloomEffect = BloomEffect;
  85585. })(BABYLON || (BABYLON = {}));
  85586. //# sourceMappingURL=babylon.bloomEffect.js.map
  85587. var BABYLON;
  85588. (function (BABYLON) {
  85589. /**
  85590. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  85591. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  85592. */
  85593. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  85594. __extends(DefaultRenderingPipeline, _super);
  85595. /**
  85596. * @constructor
  85597. * @param {string} name - The rendering pipeline name (default: "")
  85598. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  85599. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  85600. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  85601. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  85602. */
  85603. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  85604. if (name === void 0) { name = ""; }
  85605. if (hdr === void 0) { hdr = true; }
  85606. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  85607. if (automaticBuild === void 0) { automaticBuild = true; }
  85608. var _this = _super.call(this, scene.getEngine(), name) || this;
  85609. _this._camerasToBeAttached = [];
  85610. /**
  85611. * ID of the sharpen post process,
  85612. */
  85613. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  85614. /**
  85615. * @ignore
  85616. * ID of the image processing post process;
  85617. */
  85618. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  85619. /**
  85620. * @ignore
  85621. * ID of the Fast Approximate Anti-Aliasing post process;
  85622. */
  85623. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  85624. /**
  85625. * ID of the chromatic aberration post process,
  85626. */
  85627. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  85628. /**
  85629. * ID of the grain post process
  85630. */
  85631. _this.GrainPostProcessId = "GrainPostProcessEffect";
  85632. /**
  85633. * Glow post process which adds a glow to emmisive areas of the image
  85634. */
  85635. _this._glowLayer = null;
  85636. /**
  85637. * Animations which can be used to tweak settings over a period of time
  85638. */
  85639. _this.animations = [];
  85640. _this._imageProcessingConfigurationObserver = null;
  85641. // Values
  85642. _this._sharpenEnabled = false;
  85643. _this._bloomEnabled = false;
  85644. _this._depthOfFieldEnabled = false;
  85645. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  85646. _this._fxaaEnabled = false;
  85647. _this._imageProcessingEnabled = true;
  85648. _this._bloomScale = 0.5;
  85649. _this._chromaticAberrationEnabled = false;
  85650. _this._grainEnabled = false;
  85651. _this._buildAllowed = true;
  85652. _this._resizeObserver = null;
  85653. _this._hardwareScaleLevel = 1.0;
  85654. _this._bloomKernel = 64;
  85655. /**
  85656. * Specifies the weight of the bloom in the final rendering
  85657. */
  85658. _this._bloomWeight = 0.15;
  85659. /**
  85660. * Specifies the luma threshold for the area that will be blurred by the bloom
  85661. */
  85662. _this._bloomThreshold = 0.9;
  85663. _this._samples = 1;
  85664. _this._hasCleared = false;
  85665. _this._prevPostProcess = null;
  85666. _this._prevPrevPostProcess = null;
  85667. _this._depthOfFieldSceneObserver = null;
  85668. _this._cameras = cameras || scene.cameras;
  85669. _this._cameras = _this._cameras.slice();
  85670. _this._camerasToBeAttached = _this._cameras.slice();
  85671. _this._buildAllowed = automaticBuild;
  85672. // Initialize
  85673. _this._scene = scene;
  85674. var caps = _this._scene.getEngine().getCaps();
  85675. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  85676. // Misc
  85677. if (_this._hdr) {
  85678. if (caps.textureHalfFloatRender) {
  85679. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85680. }
  85681. else if (caps.textureFloatRender) {
  85682. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85683. }
  85684. }
  85685. else {
  85686. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85687. }
  85688. // Attach
  85689. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85690. var engine = _this._scene.getEngine();
  85691. // Create post processes before hand so they can be modified before enabled.
  85692. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  85693. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85694. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  85695. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  85696. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  85697. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85698. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  85699. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85700. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  85701. _this._resizeObserver = engine.onResizeObservable.add(function () {
  85702. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  85703. _this.bloomKernel = _this.bloomKernel;
  85704. });
  85705. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  85706. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  85707. });
  85708. _this._buildPipeline();
  85709. return _this;
  85710. }
  85711. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  85712. get: function () {
  85713. return this._sharpenEnabled;
  85714. },
  85715. /**
  85716. * Enable or disable the sharpen process from the pipeline
  85717. */
  85718. set: function (enabled) {
  85719. if (this._sharpenEnabled === enabled) {
  85720. return;
  85721. }
  85722. this._sharpenEnabled = enabled;
  85723. this._buildPipeline();
  85724. },
  85725. enumerable: true,
  85726. configurable: true
  85727. });
  85728. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  85729. /**
  85730. * Specifies the size of the bloom blur kernel, relative to the final output size
  85731. */
  85732. get: function () {
  85733. return this._bloomKernel;
  85734. },
  85735. set: function (value) {
  85736. this._bloomKernel = value;
  85737. this.bloom.kernel = value / this._hardwareScaleLevel;
  85738. },
  85739. enumerable: true,
  85740. configurable: true
  85741. });
  85742. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  85743. get: function () {
  85744. return this._bloomWeight;
  85745. },
  85746. /**
  85747. * The strength of the bloom.
  85748. */
  85749. set: function (value) {
  85750. if (this._bloomWeight === value) {
  85751. return;
  85752. }
  85753. this.bloom.weight = value;
  85754. this._bloomWeight = value;
  85755. },
  85756. enumerable: true,
  85757. configurable: true
  85758. });
  85759. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  85760. get: function () {
  85761. return this._bloomThreshold;
  85762. },
  85763. /**
  85764. * The strength of the bloom.
  85765. */
  85766. set: function (value) {
  85767. if (this._bloomThreshold === value) {
  85768. return;
  85769. }
  85770. this.bloom.threshold = value;
  85771. this._bloomThreshold = value;
  85772. },
  85773. enumerable: true,
  85774. configurable: true
  85775. });
  85776. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  85777. get: function () {
  85778. return this._bloomScale;
  85779. },
  85780. /**
  85781. * The scale of the bloom, lower value will provide better performance.
  85782. */
  85783. set: function (value) {
  85784. if (this._bloomScale === value) {
  85785. return;
  85786. }
  85787. this._bloomScale = value;
  85788. // recreate bloom and dispose old as this setting is not dynamic
  85789. this._rebuildBloom();
  85790. this._buildPipeline();
  85791. },
  85792. enumerable: true,
  85793. configurable: true
  85794. });
  85795. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  85796. get: function () {
  85797. return this._bloomEnabled;
  85798. },
  85799. /**
  85800. * Enable or disable the bloom from the pipeline
  85801. */
  85802. set: function (enabled) {
  85803. if (this._bloomEnabled === enabled) {
  85804. return;
  85805. }
  85806. this._bloomEnabled = enabled;
  85807. this._buildPipeline();
  85808. },
  85809. enumerable: true,
  85810. configurable: true
  85811. });
  85812. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  85813. // recreate bloom and dispose old as this setting is not dynamic
  85814. var oldBloom = this.bloom;
  85815. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  85816. this.bloom.threshold = oldBloom.threshold;
  85817. for (var i = 0; i < this._cameras.length; i++) {
  85818. oldBloom.disposeEffects(this._cameras[i]);
  85819. }
  85820. };
  85821. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  85822. /**
  85823. * If the depth of field is enabled.
  85824. */
  85825. get: function () {
  85826. return this._depthOfFieldEnabled;
  85827. },
  85828. set: function (enabled) {
  85829. if (this._depthOfFieldEnabled === enabled) {
  85830. return;
  85831. }
  85832. this._depthOfFieldEnabled = enabled;
  85833. this._buildPipeline();
  85834. },
  85835. enumerable: true,
  85836. configurable: true
  85837. });
  85838. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  85839. /**
  85840. * Blur level of the depth of field effect. (Higher blur will effect performance)
  85841. */
  85842. get: function () {
  85843. return this._depthOfFieldBlurLevel;
  85844. },
  85845. set: function (value) {
  85846. if (this._depthOfFieldBlurLevel === value) {
  85847. return;
  85848. }
  85849. this._depthOfFieldBlurLevel = value;
  85850. // recreate dof and dispose old as this setting is not dynamic
  85851. var oldDof = this.depthOfField;
  85852. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  85853. this.depthOfField.focalLength = oldDof.focalLength;
  85854. this.depthOfField.focusDistance = oldDof.focusDistance;
  85855. this.depthOfField.fStop = oldDof.fStop;
  85856. this.depthOfField.lensSize = oldDof.lensSize;
  85857. for (var i = 0; i < this._cameras.length; i++) {
  85858. oldDof.disposeEffects(this._cameras[i]);
  85859. }
  85860. this._buildPipeline();
  85861. },
  85862. enumerable: true,
  85863. configurable: true
  85864. });
  85865. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  85866. get: function () {
  85867. return this._fxaaEnabled;
  85868. },
  85869. /**
  85870. * If the anti aliasing is enabled.
  85871. */
  85872. set: function (enabled) {
  85873. if (this._fxaaEnabled === enabled) {
  85874. return;
  85875. }
  85876. this._fxaaEnabled = enabled;
  85877. this._buildPipeline();
  85878. },
  85879. enumerable: true,
  85880. configurable: true
  85881. });
  85882. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  85883. get: function () {
  85884. return this._samples;
  85885. },
  85886. /**
  85887. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85888. */
  85889. set: function (sampleCount) {
  85890. if (this._samples === sampleCount) {
  85891. return;
  85892. }
  85893. this._samples = sampleCount;
  85894. this._buildPipeline();
  85895. },
  85896. enumerable: true,
  85897. configurable: true
  85898. });
  85899. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  85900. get: function () {
  85901. return this._imageProcessingEnabled;
  85902. },
  85903. /**
  85904. * If image processing is enabled.
  85905. */
  85906. set: function (enabled) {
  85907. if (this._imageProcessingEnabled === enabled) {
  85908. return;
  85909. }
  85910. this._imageProcessingEnabled = enabled;
  85911. this._buildPipeline();
  85912. },
  85913. enumerable: true,
  85914. configurable: true
  85915. });
  85916. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  85917. get: function () {
  85918. return this._glowLayer == null;
  85919. },
  85920. /**
  85921. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  85922. */
  85923. set: function (enabled) {
  85924. if (enabled && !this._glowLayer) {
  85925. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  85926. }
  85927. else if (!enabled && this._glowLayer) {
  85928. this._glowLayer.dispose();
  85929. this._glowLayer = null;
  85930. }
  85931. },
  85932. enumerable: true,
  85933. configurable: true
  85934. });
  85935. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  85936. get: function () {
  85937. return this._chromaticAberrationEnabled;
  85938. },
  85939. /**
  85940. * Enable or disable the chromaticAberration process from the pipeline
  85941. */
  85942. set: function (enabled) {
  85943. if (this._chromaticAberrationEnabled === enabled) {
  85944. return;
  85945. }
  85946. this._chromaticAberrationEnabled = enabled;
  85947. this._buildPipeline();
  85948. },
  85949. enumerable: true,
  85950. configurable: true
  85951. });
  85952. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  85953. get: function () {
  85954. return this._grainEnabled;
  85955. },
  85956. /**
  85957. * Enable or disable the grain process from the pipeline
  85958. */
  85959. set: function (enabled) {
  85960. if (this._grainEnabled === enabled) {
  85961. return;
  85962. }
  85963. this._grainEnabled = enabled;
  85964. this._buildPipeline();
  85965. },
  85966. enumerable: true,
  85967. configurable: true
  85968. });
  85969. /**
  85970. * Force the compilation of the entire pipeline.
  85971. */
  85972. DefaultRenderingPipeline.prototype.prepare = function () {
  85973. var previousState = this._buildAllowed;
  85974. this._buildAllowed = true;
  85975. this._buildPipeline();
  85976. this._buildAllowed = previousState;
  85977. };
  85978. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  85979. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  85980. if (this._hasCleared) {
  85981. postProcess.autoClear = false;
  85982. }
  85983. else {
  85984. postProcess.autoClear = true;
  85985. this._scene.autoClear = false;
  85986. this._hasCleared = true;
  85987. }
  85988. if (!skipTextureSharing) {
  85989. if (this._prevPrevPostProcess) {
  85990. postProcess.shareOutputWith(this._prevPrevPostProcess);
  85991. }
  85992. else {
  85993. postProcess.useOwnOutput();
  85994. }
  85995. if (this._prevPostProcess) {
  85996. this._prevPrevPostProcess = this._prevPostProcess;
  85997. }
  85998. this._prevPostProcess = postProcess;
  85999. }
  86000. };
  86001. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  86002. var _this = this;
  86003. if (!this._buildAllowed) {
  86004. return;
  86005. }
  86006. this._scene.autoClear = true;
  86007. var engine = this._scene.getEngine();
  86008. this._disposePostProcesses();
  86009. if (this._cameras !== null) {
  86010. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86011. // get back cameras to be used to reattach pipeline
  86012. this._cameras = this._camerasToBeAttached.slice();
  86013. }
  86014. this._reset();
  86015. this._prevPostProcess = null;
  86016. this._prevPrevPostProcess = null;
  86017. this._hasCleared = false;
  86018. if (this.depthOfFieldEnabled) {
  86019. // Multi camera suport
  86020. if (this._cameras.length > 1) {
  86021. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  86022. var camera = _a[_i];
  86023. var depthRenderer = this._scene.enableDepthRenderer(camera);
  86024. depthRenderer.useOnlyInActiveCamera = true;
  86025. }
  86026. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  86027. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  86028. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  86029. }
  86030. });
  86031. }
  86032. else {
  86033. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86034. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  86035. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  86036. }
  86037. if (!this.depthOfField._isReady()) {
  86038. this.depthOfField._updateEffects();
  86039. }
  86040. this.addEffect(this.depthOfField);
  86041. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  86042. }
  86043. else {
  86044. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86045. }
  86046. if (this.bloomEnabled) {
  86047. if (!this.bloom._isReady()) {
  86048. this.bloom._updateEffects();
  86049. }
  86050. this.addEffect(this.bloom);
  86051. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  86052. }
  86053. if (this._imageProcessingEnabled) {
  86054. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  86055. if (this._hdr) {
  86056. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  86057. this._setAutoClearAndTextureSharing(this.imageProcessing);
  86058. }
  86059. else {
  86060. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  86061. }
  86062. }
  86063. if (this.sharpenEnabled) {
  86064. if (!this.sharpen.isReady()) {
  86065. this.sharpen.updateEffect();
  86066. }
  86067. this.addEffect(this._sharpenEffect);
  86068. this._setAutoClearAndTextureSharing(this.sharpen);
  86069. }
  86070. if (this.grainEnabled) {
  86071. if (!this.grain.isReady()) {
  86072. this.grain.updateEffect();
  86073. }
  86074. this.addEffect(this._grainEffect);
  86075. this._setAutoClearAndTextureSharing(this.grain);
  86076. }
  86077. if (this.chromaticAberrationEnabled) {
  86078. if (!this.chromaticAberration.isReady()) {
  86079. this.chromaticAberration.updateEffect();
  86080. }
  86081. this.addEffect(this._chromaticAberrationEffect);
  86082. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  86083. }
  86084. if (this.fxaaEnabled) {
  86085. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  86086. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  86087. this._setAutoClearAndTextureSharing(this.fxaa, true);
  86088. }
  86089. if (this._cameras !== null) {
  86090. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86091. }
  86092. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  86093. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86094. }
  86095. };
  86096. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  86097. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  86098. for (var i = 0; i < this._cameras.length; i++) {
  86099. var camera = this._cameras[i];
  86100. if (this.imageProcessing) {
  86101. this.imageProcessing.dispose(camera);
  86102. }
  86103. if (this.fxaa) {
  86104. this.fxaa.dispose(camera);
  86105. }
  86106. // These are created in the constructor and should not be disposed on every pipeline change
  86107. if (disposeNonRecreated) {
  86108. if (this.sharpen) {
  86109. this.sharpen.dispose(camera);
  86110. }
  86111. if (this.depthOfField) {
  86112. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86113. this.depthOfField.disposeEffects(camera);
  86114. }
  86115. if (this.bloom) {
  86116. this.bloom.disposeEffects(camera);
  86117. }
  86118. if (this.chromaticAberration) {
  86119. this.chromaticAberration.dispose(camera);
  86120. }
  86121. if (this.grain) {
  86122. this.grain.dispose(camera);
  86123. }
  86124. if (this._glowLayer) {
  86125. this._glowLayer.dispose();
  86126. }
  86127. }
  86128. }
  86129. this.imageProcessing = null;
  86130. this.fxaa = null;
  86131. if (disposeNonRecreated) {
  86132. this.sharpen = null;
  86133. this._sharpenEffect = null;
  86134. this.depthOfField = null;
  86135. this.bloom = null;
  86136. this.chromaticAberration = null;
  86137. this._chromaticAberrationEffect = null;
  86138. this.grain = null;
  86139. this._grainEffect = null;
  86140. this._glowLayer = null;
  86141. }
  86142. };
  86143. /**
  86144. * Adds a camera to the pipeline
  86145. * @param camera the camera to be added
  86146. */
  86147. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  86148. this._camerasToBeAttached.push(camera);
  86149. this._buildPipeline();
  86150. };
  86151. /**
  86152. * Removes a camera from the pipeline
  86153. * @param camera the camera to remove
  86154. */
  86155. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  86156. var index = this._camerasToBeAttached.indexOf(camera);
  86157. this._camerasToBeAttached.splice(index, 1);
  86158. this._buildPipeline();
  86159. };
  86160. /**
  86161. * Dispose of the pipeline and stop all post processes
  86162. */
  86163. DefaultRenderingPipeline.prototype.dispose = function () {
  86164. this._disposePostProcesses(true);
  86165. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86166. this._scene.autoClear = true;
  86167. if (this._resizeObserver) {
  86168. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  86169. this._resizeObserver = null;
  86170. }
  86171. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  86172. _super.prototype.dispose.call(this);
  86173. };
  86174. /**
  86175. * Serialize the rendering pipeline (Used when exporting)
  86176. * @returns the serialized object
  86177. */
  86178. DefaultRenderingPipeline.prototype.serialize = function () {
  86179. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86180. serializationObject.customType = "DefaultRenderingPipeline";
  86181. return serializationObject;
  86182. };
  86183. /**
  86184. * Parse the serialized pipeline
  86185. * @param source Source pipeline.
  86186. * @param scene The scene to load the pipeline to.
  86187. * @param rootUrl The URL of the serialized pipeline.
  86188. * @returns An instantiated pipeline from the serialized object.
  86189. */
  86190. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  86191. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  86192. };
  86193. __decorate([
  86194. BABYLON.serialize()
  86195. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  86196. __decorate([
  86197. BABYLON.serialize()
  86198. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  86199. __decorate([
  86200. BABYLON.serialize()
  86201. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  86202. __decorate([
  86203. BABYLON.serialize()
  86204. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  86205. __decorate([
  86206. BABYLON.serialize()
  86207. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  86208. __decorate([
  86209. BABYLON.serialize()
  86210. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  86211. __decorate([
  86212. BABYLON.serialize()
  86213. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  86214. __decorate([
  86215. BABYLON.serialize()
  86216. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  86217. __decorate([
  86218. BABYLON.serialize()
  86219. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  86220. __decorate([
  86221. BABYLON.serialize()
  86222. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  86223. __decorate([
  86224. BABYLON.serialize()
  86225. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  86226. __decorate([
  86227. BABYLON.serialize()
  86228. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  86229. __decorate([
  86230. BABYLON.serialize()
  86231. ], DefaultRenderingPipeline.prototype, "samples", null);
  86232. __decorate([
  86233. BABYLON.serialize()
  86234. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  86235. __decorate([
  86236. BABYLON.serialize()
  86237. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  86238. __decorate([
  86239. BABYLON.serialize()
  86240. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  86241. __decorate([
  86242. BABYLON.serialize()
  86243. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  86244. return DefaultRenderingPipeline;
  86245. }(BABYLON.PostProcessRenderPipeline));
  86246. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  86247. })(BABYLON || (BABYLON = {}));
  86248. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  86249. var BABYLON;
  86250. (function (BABYLON) {
  86251. /**
  86252. * @hidden
  86253. */
  86254. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  86255. __extends(ImageProcessingConfigurationDefines, _super);
  86256. function ImageProcessingConfigurationDefines() {
  86257. var _this = _super.call(this) || this;
  86258. _this.IMAGEPROCESSING = false;
  86259. _this.VIGNETTE = false;
  86260. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86261. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86262. _this.TONEMAPPING = false;
  86263. _this.TONEMAPPING_ACES = false;
  86264. _this.CONTRAST = false;
  86265. _this.COLORCURVES = false;
  86266. _this.COLORGRADING = false;
  86267. _this.COLORGRADING3D = false;
  86268. _this.SAMPLER3DGREENDEPTH = false;
  86269. _this.SAMPLER3DBGRMAP = false;
  86270. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86271. _this.EXPOSURE = false;
  86272. _this.rebuild();
  86273. return _this;
  86274. }
  86275. return ImageProcessingConfigurationDefines;
  86276. }(BABYLON.MaterialDefines));
  86277. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  86278. /**
  86279. * This groups together the common properties used for image processing either in direct forward pass
  86280. * or through post processing effect depending on the use of the image processing pipeline in your scene
  86281. * or not.
  86282. */
  86283. var ImageProcessingConfiguration = /** @class */ (function () {
  86284. function ImageProcessingConfiguration() {
  86285. /**
  86286. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  86287. */
  86288. this.colorCurves = new BABYLON.ColorCurves();
  86289. this._colorCurvesEnabled = false;
  86290. this._colorGradingEnabled = false;
  86291. this._colorGradingWithGreenDepth = true;
  86292. this._colorGradingBGR = true;
  86293. /** @hidden */
  86294. this._exposure = 1.0;
  86295. this._toneMappingEnabled = false;
  86296. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  86297. this._contrast = 1.0;
  86298. /**
  86299. * Vignette stretch size.
  86300. */
  86301. this.vignetteStretch = 0;
  86302. /**
  86303. * Vignette centre X Offset.
  86304. */
  86305. this.vignetteCentreX = 0;
  86306. /**
  86307. * Vignette centre Y Offset.
  86308. */
  86309. this.vignetteCentreY = 0;
  86310. /**
  86311. * Vignette weight or intensity of the vignette effect.
  86312. */
  86313. this.vignetteWeight = 1.5;
  86314. /**
  86315. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86316. * if vignetteEnabled is set to true.
  86317. */
  86318. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86319. /**
  86320. * Camera field of view used by the Vignette effect.
  86321. */
  86322. this.vignetteCameraFov = 0.5;
  86323. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  86324. this._vignetteEnabled = false;
  86325. this._applyByPostProcess = false;
  86326. this._isEnabled = true;
  86327. /**
  86328. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  86329. */
  86330. this.onUpdateParameters = new BABYLON.Observable();
  86331. }
  86332. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  86333. /**
  86334. * Gets wether the color curves effect is enabled.
  86335. */
  86336. get: function () {
  86337. return this._colorCurvesEnabled;
  86338. },
  86339. /**
  86340. * Sets wether the color curves effect is enabled.
  86341. */
  86342. set: function (value) {
  86343. if (this._colorCurvesEnabled === value) {
  86344. return;
  86345. }
  86346. this._colorCurvesEnabled = value;
  86347. this._updateParameters();
  86348. },
  86349. enumerable: true,
  86350. configurable: true
  86351. });
  86352. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  86353. /**
  86354. * Gets wether the color grading effect is enabled.
  86355. */
  86356. get: function () {
  86357. return this._colorGradingEnabled;
  86358. },
  86359. /**
  86360. * Sets wether the color grading effect is enabled.
  86361. */
  86362. set: function (value) {
  86363. if (this._colorGradingEnabled === value) {
  86364. return;
  86365. }
  86366. this._colorGradingEnabled = value;
  86367. this._updateParameters();
  86368. },
  86369. enumerable: true,
  86370. configurable: true
  86371. });
  86372. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  86373. /**
  86374. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  86375. */
  86376. get: function () {
  86377. return this._colorGradingWithGreenDepth;
  86378. },
  86379. /**
  86380. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  86381. */
  86382. set: function (value) {
  86383. if (this._colorGradingWithGreenDepth === value) {
  86384. return;
  86385. }
  86386. this._colorGradingWithGreenDepth = value;
  86387. this._updateParameters();
  86388. },
  86389. enumerable: true,
  86390. configurable: true
  86391. });
  86392. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  86393. /**
  86394. * Gets wether the color grading texture contains BGR values.
  86395. */
  86396. get: function () {
  86397. return this._colorGradingBGR;
  86398. },
  86399. /**
  86400. * Sets wether the color grading texture contains BGR values.
  86401. */
  86402. set: function (value) {
  86403. if (this._colorGradingBGR === value) {
  86404. return;
  86405. }
  86406. this._colorGradingBGR = value;
  86407. this._updateParameters();
  86408. },
  86409. enumerable: true,
  86410. configurable: true
  86411. });
  86412. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  86413. /**
  86414. * Gets the Exposure used in the effect.
  86415. */
  86416. get: function () {
  86417. return this._exposure;
  86418. },
  86419. /**
  86420. * Sets the Exposure used in the effect.
  86421. */
  86422. set: function (value) {
  86423. if (this._exposure === value) {
  86424. return;
  86425. }
  86426. this._exposure = value;
  86427. this._updateParameters();
  86428. },
  86429. enumerable: true,
  86430. configurable: true
  86431. });
  86432. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  86433. /**
  86434. * Gets wether the tone mapping effect is enabled.
  86435. */
  86436. get: function () {
  86437. return this._toneMappingEnabled;
  86438. },
  86439. /**
  86440. * Sets wether the tone mapping effect is enabled.
  86441. */
  86442. set: function (value) {
  86443. if (this._toneMappingEnabled === value) {
  86444. return;
  86445. }
  86446. this._toneMappingEnabled = value;
  86447. this._updateParameters();
  86448. },
  86449. enumerable: true,
  86450. configurable: true
  86451. });
  86452. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  86453. /**
  86454. * Gets the type of tone mapping effect.
  86455. */
  86456. get: function () {
  86457. return this._toneMappingType;
  86458. },
  86459. /**
  86460. * Sets the type of tone mapping effect used in BabylonJS.
  86461. */
  86462. set: function (value) {
  86463. if (this._toneMappingType === value) {
  86464. return;
  86465. }
  86466. this._toneMappingType = value;
  86467. this._updateParameters();
  86468. },
  86469. enumerable: true,
  86470. configurable: true
  86471. });
  86472. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  86473. /**
  86474. * Gets the contrast used in the effect.
  86475. */
  86476. get: function () {
  86477. return this._contrast;
  86478. },
  86479. /**
  86480. * Sets the contrast used in the effect.
  86481. */
  86482. set: function (value) {
  86483. if (this._contrast === value) {
  86484. return;
  86485. }
  86486. this._contrast = value;
  86487. this._updateParameters();
  86488. },
  86489. enumerable: true,
  86490. configurable: true
  86491. });
  86492. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  86493. /**
  86494. * Gets the vignette blend mode allowing different kind of effect.
  86495. */
  86496. get: function () {
  86497. return this._vignetteBlendMode;
  86498. },
  86499. /**
  86500. * Sets the vignette blend mode allowing different kind of effect.
  86501. */
  86502. set: function (value) {
  86503. if (this._vignetteBlendMode === value) {
  86504. return;
  86505. }
  86506. this._vignetteBlendMode = value;
  86507. this._updateParameters();
  86508. },
  86509. enumerable: true,
  86510. configurable: true
  86511. });
  86512. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  86513. /**
  86514. * Gets wether the vignette effect is enabled.
  86515. */
  86516. get: function () {
  86517. return this._vignetteEnabled;
  86518. },
  86519. /**
  86520. * Sets wether the vignette effect is enabled.
  86521. */
  86522. set: function (value) {
  86523. if (this._vignetteEnabled === value) {
  86524. return;
  86525. }
  86526. this._vignetteEnabled = value;
  86527. this._updateParameters();
  86528. },
  86529. enumerable: true,
  86530. configurable: true
  86531. });
  86532. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  86533. /**
  86534. * Gets wether the image processing is applied through a post process or not.
  86535. */
  86536. get: function () {
  86537. return this._applyByPostProcess;
  86538. },
  86539. /**
  86540. * Sets wether the image processing is applied through a post process or not.
  86541. */
  86542. set: function (value) {
  86543. if (this._applyByPostProcess === value) {
  86544. return;
  86545. }
  86546. this._applyByPostProcess = value;
  86547. this._updateParameters();
  86548. },
  86549. enumerable: true,
  86550. configurable: true
  86551. });
  86552. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  86553. /**
  86554. * Gets wether the image processing is enabled or not.
  86555. */
  86556. get: function () {
  86557. return this._isEnabled;
  86558. },
  86559. /**
  86560. * Sets wether the image processing is enabled or not.
  86561. */
  86562. set: function (value) {
  86563. if (this._isEnabled === value) {
  86564. return;
  86565. }
  86566. this._isEnabled = value;
  86567. this._updateParameters();
  86568. },
  86569. enumerable: true,
  86570. configurable: true
  86571. });
  86572. /**
  86573. * Method called each time the image processing information changes requires to recompile the effect.
  86574. */
  86575. ImageProcessingConfiguration.prototype._updateParameters = function () {
  86576. this.onUpdateParameters.notifyObservers(this);
  86577. };
  86578. /**
  86579. * Gets the current class name.
  86580. * @return "ImageProcessingConfiguration"
  86581. */
  86582. ImageProcessingConfiguration.prototype.getClassName = function () {
  86583. return "ImageProcessingConfiguration";
  86584. };
  86585. /**
  86586. * Prepare the list of uniforms associated with the Image Processing effects.
  86587. * @param uniforms The list of uniforms used in the effect
  86588. * @param defines the list of defines currently in use
  86589. */
  86590. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  86591. if (defines.EXPOSURE) {
  86592. uniforms.push("exposureLinear");
  86593. }
  86594. if (defines.CONTRAST) {
  86595. uniforms.push("contrast");
  86596. }
  86597. if (defines.COLORGRADING) {
  86598. uniforms.push("colorTransformSettings");
  86599. }
  86600. if (defines.VIGNETTE) {
  86601. uniforms.push("vInverseScreenSize");
  86602. uniforms.push("vignetteSettings1");
  86603. uniforms.push("vignetteSettings2");
  86604. }
  86605. if (defines.COLORCURVES) {
  86606. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  86607. }
  86608. };
  86609. /**
  86610. * Prepare the list of samplers associated with the Image Processing effects.
  86611. * @param samplersList The list of uniforms used in the effect
  86612. * @param defines the list of defines currently in use
  86613. */
  86614. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  86615. if (defines.COLORGRADING) {
  86616. samplersList.push("txColorTransform");
  86617. }
  86618. };
  86619. /**
  86620. * Prepare the list of defines associated to the shader.
  86621. * @param defines the list of defines to complete
  86622. * @param forPostProcess Define if we are currently in post process mode or not
  86623. */
  86624. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  86625. if (forPostProcess === void 0) { forPostProcess = false; }
  86626. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  86627. defines.VIGNETTE = false;
  86628. defines.TONEMAPPING = false;
  86629. defines.TONEMAPPING_ACES = false;
  86630. defines.CONTRAST = false;
  86631. defines.EXPOSURE = false;
  86632. defines.COLORCURVES = false;
  86633. defines.COLORGRADING = false;
  86634. defines.COLORGRADING3D = false;
  86635. defines.IMAGEPROCESSING = false;
  86636. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  86637. return;
  86638. }
  86639. defines.VIGNETTE = this.vignetteEnabled;
  86640. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  86641. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  86642. defines.TONEMAPPING = this.toneMappingEnabled;
  86643. switch (this._toneMappingType) {
  86644. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  86645. defines.TONEMAPPING_ACES = true;
  86646. break;
  86647. }
  86648. defines.CONTRAST = (this.contrast !== 1.0);
  86649. defines.EXPOSURE = (this.exposure !== 1.0);
  86650. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  86651. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  86652. if (defines.COLORGRADING) {
  86653. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  86654. }
  86655. else {
  86656. defines.COLORGRADING3D = false;
  86657. }
  86658. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  86659. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  86660. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  86661. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  86662. };
  86663. /**
  86664. * Returns true if all the image processing information are ready.
  86665. * @returns True if ready, otherwise, false
  86666. */
  86667. ImageProcessingConfiguration.prototype.isReady = function () {
  86668. // Color Grading texure can not be none blocking.
  86669. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  86670. };
  86671. /**
  86672. * Binds the image processing to the shader.
  86673. * @param effect The effect to bind to
  86674. * @param aspectRatio Define the current aspect ratio of the effect
  86675. */
  86676. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  86677. if (aspectRatio === void 0) { aspectRatio = 1; }
  86678. // Color Curves
  86679. if (this._colorCurvesEnabled && this.colorCurves) {
  86680. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  86681. }
  86682. // Vignette
  86683. if (this._vignetteEnabled) {
  86684. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  86685. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  86686. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  86687. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  86688. var vignetteScaleX = vignetteScaleY * aspectRatio;
  86689. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  86690. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  86691. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  86692. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  86693. var vignettePower = -2.0 * this.vignetteWeight;
  86694. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  86695. }
  86696. // Exposure
  86697. effect.setFloat("exposureLinear", this.exposure);
  86698. // Contrast
  86699. effect.setFloat("contrast", this.contrast);
  86700. // Color transform settings
  86701. if (this.colorGradingTexture) {
  86702. effect.setTexture("txColorTransform", this.colorGradingTexture);
  86703. var textureSize = this.colorGradingTexture.getSize().height;
  86704. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  86705. 0.5 / textureSize, // textureOffset
  86706. textureSize, // textureSize
  86707. this.colorGradingTexture.level // weight
  86708. );
  86709. }
  86710. };
  86711. /**
  86712. * Clones the current image processing instance.
  86713. * @return The cloned image processing
  86714. */
  86715. ImageProcessingConfiguration.prototype.clone = function () {
  86716. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  86717. };
  86718. /**
  86719. * Serializes the current image processing instance to a json representation.
  86720. * @return a JSON representation
  86721. */
  86722. ImageProcessingConfiguration.prototype.serialize = function () {
  86723. return BABYLON.SerializationHelper.Serialize(this);
  86724. };
  86725. /**
  86726. * Parses the image processing from a json representation.
  86727. * @param source the JSON source to parse
  86728. * @return The parsed image processing
  86729. */
  86730. ImageProcessingConfiguration.Parse = function (source) {
  86731. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  86732. };
  86733. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  86734. /**
  86735. * Used to apply the vignette as a mix with the pixel color.
  86736. */
  86737. get: function () {
  86738. return this._VIGNETTEMODE_MULTIPLY;
  86739. },
  86740. enumerable: true,
  86741. configurable: true
  86742. });
  86743. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  86744. /**
  86745. * Used to apply the vignette as a replacement of the pixel color.
  86746. */
  86747. get: function () {
  86748. return this._VIGNETTEMODE_OPAQUE;
  86749. },
  86750. enumerable: true,
  86751. configurable: true
  86752. });
  86753. /**
  86754. * Default tone mapping applied in BabylonJS.
  86755. */
  86756. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  86757. /**
  86758. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  86759. * to other engines rendering to increase portability.
  86760. */
  86761. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  86762. // Static constants associated to the image processing.
  86763. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  86764. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  86765. __decorate([
  86766. BABYLON.serializeAsColorCurves()
  86767. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  86768. __decorate([
  86769. BABYLON.serialize()
  86770. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  86771. __decorate([
  86772. BABYLON.serializeAsTexture()
  86773. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  86774. __decorate([
  86775. BABYLON.serialize()
  86776. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  86777. __decorate([
  86778. BABYLON.serialize()
  86779. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  86780. __decorate([
  86781. BABYLON.serialize()
  86782. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  86783. __decorate([
  86784. BABYLON.serialize()
  86785. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  86786. __decorate([
  86787. BABYLON.serialize()
  86788. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  86789. __decorate([
  86790. BABYLON.serialize()
  86791. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  86792. __decorate([
  86793. BABYLON.serialize()
  86794. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  86795. __decorate([
  86796. BABYLON.serialize()
  86797. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  86798. __decorate([
  86799. BABYLON.serialize()
  86800. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  86801. __decorate([
  86802. BABYLON.serialize()
  86803. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  86804. __decorate([
  86805. BABYLON.serialize()
  86806. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  86807. __decorate([
  86808. BABYLON.serializeAsColor4()
  86809. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  86810. __decorate([
  86811. BABYLON.serialize()
  86812. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  86813. __decorate([
  86814. BABYLON.serialize()
  86815. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  86816. __decorate([
  86817. BABYLON.serialize()
  86818. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  86819. __decorate([
  86820. BABYLON.serialize()
  86821. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  86822. __decorate([
  86823. BABYLON.serialize()
  86824. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  86825. return ImageProcessingConfiguration;
  86826. }());
  86827. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  86828. })(BABYLON || (BABYLON = {}));
  86829. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  86830. var BABYLON;
  86831. (function (BABYLON) {
  86832. /**
  86833. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  86834. * It can help converting any input color in a desired output one. This can then be used to create effects
  86835. * from sepia, black and white to sixties or futuristic rendering...
  86836. *
  86837. * The only supported format is currently 3dl.
  86838. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  86839. */
  86840. var ColorGradingTexture = /** @class */ (function (_super) {
  86841. __extends(ColorGradingTexture, _super);
  86842. /**
  86843. * Instantiates a ColorGradingTexture from the following parameters.
  86844. *
  86845. * @param url The location of the color gradind data (currently only supporting 3dl)
  86846. * @param scene The scene the texture will be used in
  86847. */
  86848. function ColorGradingTexture(url, scene) {
  86849. var _this = _super.call(this, scene) || this;
  86850. if (!url) {
  86851. return _this;
  86852. }
  86853. _this._engine = scene.getEngine();
  86854. _this._textureMatrix = BABYLON.Matrix.Identity();
  86855. _this.name = url;
  86856. _this.url = url;
  86857. _this.hasAlpha = false;
  86858. _this.isCube = false;
  86859. _this.is3D = _this._engine.webGLVersion > 1;
  86860. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86861. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86862. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86863. _this.anisotropicFilteringLevel = 1;
  86864. _this._texture = _this._getFromCache(url, true);
  86865. if (!_this._texture) {
  86866. if (!scene.useDelayedTextureLoading) {
  86867. _this.loadTexture();
  86868. }
  86869. else {
  86870. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86871. }
  86872. }
  86873. return _this;
  86874. }
  86875. /**
  86876. * Returns the texture matrix used in most of the material.
  86877. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  86878. */
  86879. ColorGradingTexture.prototype.getTextureMatrix = function () {
  86880. return this._textureMatrix;
  86881. };
  86882. /**
  86883. * Occurs when the file being loaded is a .3dl LUT file.
  86884. */
  86885. ColorGradingTexture.prototype.load3dlTexture = function () {
  86886. var engine = this._engine;
  86887. var texture;
  86888. if (engine.webGLVersion === 1) {
  86889. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86890. }
  86891. else {
  86892. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86893. }
  86894. this._texture = texture;
  86895. var callback = function (text) {
  86896. if (typeof text !== "string") {
  86897. return;
  86898. }
  86899. var data = null;
  86900. var tempData = null;
  86901. var line;
  86902. var lines = text.split('\n');
  86903. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  86904. var maxColor = 0;
  86905. for (var i = 0; i < lines.length; i++) {
  86906. line = lines[i];
  86907. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  86908. continue;
  86909. if (line.indexOf('#') === 0)
  86910. continue;
  86911. var words = line.split(" ");
  86912. if (size === 0) {
  86913. // Number of space + one
  86914. size = words.length;
  86915. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  86916. tempData = new Float32Array(size * size * size * 4);
  86917. continue;
  86918. }
  86919. if (size != 0) {
  86920. var r = Math.max(parseInt(words[0]), 0);
  86921. var g = Math.max(parseInt(words[1]), 0);
  86922. var b = Math.max(parseInt(words[2]), 0);
  86923. maxColor = Math.max(r, maxColor);
  86924. maxColor = Math.max(g, maxColor);
  86925. maxColor = Math.max(b, maxColor);
  86926. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  86927. if (tempData) {
  86928. tempData[pixelStorageIndex + 0] = r;
  86929. tempData[pixelStorageIndex + 1] = g;
  86930. tempData[pixelStorageIndex + 2] = b;
  86931. }
  86932. pixelIndexSlice++;
  86933. if (pixelIndexSlice % size == 0) {
  86934. pixelIndexH++;
  86935. pixelIndexSlice = 0;
  86936. if (pixelIndexH % size == 0) {
  86937. pixelIndexW++;
  86938. pixelIndexH = 0;
  86939. }
  86940. }
  86941. }
  86942. }
  86943. if (tempData && data) {
  86944. for (var i = 0; i < tempData.length; i++) {
  86945. if (i > 0 && (i + 1) % 4 === 0) {
  86946. data[i] = 255;
  86947. }
  86948. else {
  86949. var value = tempData[i];
  86950. data[i] = (value / maxColor * 255);
  86951. }
  86952. }
  86953. }
  86954. if (texture.is3D) {
  86955. texture.updateSize(size, size, size);
  86956. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86957. }
  86958. else {
  86959. texture.updateSize(size * size, size);
  86960. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86961. }
  86962. };
  86963. var scene = this.getScene();
  86964. if (scene) {
  86965. scene._loadFile(this.url, callback);
  86966. }
  86967. else {
  86968. this._engine._loadFile(this.url, callback);
  86969. }
  86970. return this._texture;
  86971. };
  86972. /**
  86973. * Starts the loading process of the texture.
  86974. */
  86975. ColorGradingTexture.prototype.loadTexture = function () {
  86976. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  86977. this.load3dlTexture();
  86978. }
  86979. };
  86980. /**
  86981. * Clones the color gradind texture.
  86982. */
  86983. ColorGradingTexture.prototype.clone = function () {
  86984. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  86985. // Base texture
  86986. newTexture.level = this.level;
  86987. return newTexture;
  86988. };
  86989. /**
  86990. * Called during delayed load for textures.
  86991. */
  86992. ColorGradingTexture.prototype.delayLoad = function () {
  86993. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86994. return;
  86995. }
  86996. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86997. this._texture = this._getFromCache(this.url, true);
  86998. if (!this._texture) {
  86999. this.loadTexture();
  87000. }
  87001. };
  87002. /**
  87003. * Parses a color grading texture serialized by Babylon.
  87004. * @param parsedTexture The texture information being parsedTexture
  87005. * @param scene The scene to load the texture in
  87006. * @param rootUrl The root url of the data assets to load
  87007. * @return A color gradind texture
  87008. */
  87009. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  87010. var texture = null;
  87011. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  87012. texture = new ColorGradingTexture(parsedTexture.name, scene);
  87013. texture.name = parsedTexture.name;
  87014. texture.level = parsedTexture.level;
  87015. }
  87016. return texture;
  87017. };
  87018. /**
  87019. * Serializes the LUT texture to json format.
  87020. */
  87021. ColorGradingTexture.prototype.serialize = function () {
  87022. if (!this.name) {
  87023. return null;
  87024. }
  87025. var serializationObject = {};
  87026. serializationObject.name = this.name;
  87027. serializationObject.level = this.level;
  87028. serializationObject.customType = "BABYLON.ColorGradingTexture";
  87029. return serializationObject;
  87030. };
  87031. /**
  87032. * Empty line regex stored for GC.
  87033. */
  87034. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  87035. return ColorGradingTexture;
  87036. }(BABYLON.BaseTexture));
  87037. BABYLON.ColorGradingTexture = ColorGradingTexture;
  87038. })(BABYLON || (BABYLON = {}));
  87039. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  87040. var BABYLON;
  87041. (function (BABYLON) {
  87042. /**
  87043. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87044. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87045. * 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;
  87046. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87047. */
  87048. var ColorCurves = /** @class */ (function () {
  87049. function ColorCurves() {
  87050. this._dirty = true;
  87051. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  87052. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  87053. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  87054. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  87055. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  87056. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  87057. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  87058. this._globalHue = 30;
  87059. this._globalDensity = 0;
  87060. this._globalSaturation = 0;
  87061. this._globalExposure = 0;
  87062. this._highlightsHue = 30;
  87063. this._highlightsDensity = 0;
  87064. this._highlightsSaturation = 0;
  87065. this._highlightsExposure = 0;
  87066. this._midtonesHue = 30;
  87067. this._midtonesDensity = 0;
  87068. this._midtonesSaturation = 0;
  87069. this._midtonesExposure = 0;
  87070. this._shadowsHue = 30;
  87071. this._shadowsDensity = 0;
  87072. this._shadowsSaturation = 0;
  87073. this._shadowsExposure = 0;
  87074. }
  87075. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  87076. /**
  87077. * Gets the global Hue value.
  87078. * 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).
  87079. */
  87080. get: function () {
  87081. return this._globalHue;
  87082. },
  87083. /**
  87084. * Sets the global Hue value.
  87085. * 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).
  87086. */
  87087. set: function (value) {
  87088. this._globalHue = value;
  87089. this._dirty = true;
  87090. },
  87091. enumerable: true,
  87092. configurable: true
  87093. });
  87094. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  87095. /**
  87096. * Gets the global Density value.
  87097. * 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.
  87098. * Values less than zero provide a filter of opposite hue.
  87099. */
  87100. get: function () {
  87101. return this._globalDensity;
  87102. },
  87103. /**
  87104. * Sets the global Density value.
  87105. * 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.
  87106. * Values less than zero provide a filter of opposite hue.
  87107. */
  87108. set: function (value) {
  87109. this._globalDensity = value;
  87110. this._dirty = true;
  87111. },
  87112. enumerable: true,
  87113. configurable: true
  87114. });
  87115. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  87116. /**
  87117. * Gets the global Saturation value.
  87118. * 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.
  87119. */
  87120. get: function () {
  87121. return this._globalSaturation;
  87122. },
  87123. /**
  87124. * Sets the global Saturation value.
  87125. * 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.
  87126. */
  87127. set: function (value) {
  87128. this._globalSaturation = value;
  87129. this._dirty = true;
  87130. },
  87131. enumerable: true,
  87132. configurable: true
  87133. });
  87134. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  87135. /**
  87136. * Gets the global Exposure value.
  87137. * 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.
  87138. */
  87139. get: function () {
  87140. return this._globalExposure;
  87141. },
  87142. /**
  87143. * Sets the global Exposure value.
  87144. * 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.
  87145. */
  87146. set: function (value) {
  87147. this._globalExposure = value;
  87148. this._dirty = true;
  87149. },
  87150. enumerable: true,
  87151. configurable: true
  87152. });
  87153. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  87154. /**
  87155. * Gets the highlights Hue value.
  87156. * 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).
  87157. */
  87158. get: function () {
  87159. return this._highlightsHue;
  87160. },
  87161. /**
  87162. * Sets the highlights Hue value.
  87163. * 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).
  87164. */
  87165. set: function (value) {
  87166. this._highlightsHue = value;
  87167. this._dirty = true;
  87168. },
  87169. enumerable: true,
  87170. configurable: true
  87171. });
  87172. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  87173. /**
  87174. * Gets the highlights Density value.
  87175. * 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.
  87176. * Values less than zero provide a filter of opposite hue.
  87177. */
  87178. get: function () {
  87179. return this._highlightsDensity;
  87180. },
  87181. /**
  87182. * Sets the highlights Density value.
  87183. * 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.
  87184. * Values less than zero provide a filter of opposite hue.
  87185. */
  87186. set: function (value) {
  87187. this._highlightsDensity = value;
  87188. this._dirty = true;
  87189. },
  87190. enumerable: true,
  87191. configurable: true
  87192. });
  87193. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  87194. /**
  87195. * Gets the highlights Saturation value.
  87196. * 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.
  87197. */
  87198. get: function () {
  87199. return this._highlightsSaturation;
  87200. },
  87201. /**
  87202. * Sets the highlights Saturation value.
  87203. * 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.
  87204. */
  87205. set: function (value) {
  87206. this._highlightsSaturation = value;
  87207. this._dirty = true;
  87208. },
  87209. enumerable: true,
  87210. configurable: true
  87211. });
  87212. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  87213. /**
  87214. * Gets the highlights Exposure value.
  87215. * 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.
  87216. */
  87217. get: function () {
  87218. return this._highlightsExposure;
  87219. },
  87220. /**
  87221. * Sets the highlights Exposure value.
  87222. * 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.
  87223. */
  87224. set: function (value) {
  87225. this._highlightsExposure = value;
  87226. this._dirty = true;
  87227. },
  87228. enumerable: true,
  87229. configurable: true
  87230. });
  87231. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  87232. /**
  87233. * Gets the midtones Hue value.
  87234. * 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).
  87235. */
  87236. get: function () {
  87237. return this._midtonesHue;
  87238. },
  87239. /**
  87240. * Sets the midtones Hue value.
  87241. * 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).
  87242. */
  87243. set: function (value) {
  87244. this._midtonesHue = value;
  87245. this._dirty = true;
  87246. },
  87247. enumerable: true,
  87248. configurable: true
  87249. });
  87250. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  87251. /**
  87252. * Gets the midtones Density value.
  87253. * 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.
  87254. * Values less than zero provide a filter of opposite hue.
  87255. */
  87256. get: function () {
  87257. return this._midtonesDensity;
  87258. },
  87259. /**
  87260. * Sets the midtones Density value.
  87261. * 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.
  87262. * Values less than zero provide a filter of opposite hue.
  87263. */
  87264. set: function (value) {
  87265. this._midtonesDensity = value;
  87266. this._dirty = true;
  87267. },
  87268. enumerable: true,
  87269. configurable: true
  87270. });
  87271. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  87272. /**
  87273. * Gets the midtones Saturation value.
  87274. * 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.
  87275. */
  87276. get: function () {
  87277. return this._midtonesSaturation;
  87278. },
  87279. /**
  87280. * Sets the midtones Saturation value.
  87281. * 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.
  87282. */
  87283. set: function (value) {
  87284. this._midtonesSaturation = value;
  87285. this._dirty = true;
  87286. },
  87287. enumerable: true,
  87288. configurable: true
  87289. });
  87290. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  87291. /**
  87292. * Gets the midtones Exposure value.
  87293. * 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.
  87294. */
  87295. get: function () {
  87296. return this._midtonesExposure;
  87297. },
  87298. /**
  87299. * Sets the midtones Exposure value.
  87300. * 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.
  87301. */
  87302. set: function (value) {
  87303. this._midtonesExposure = value;
  87304. this._dirty = true;
  87305. },
  87306. enumerable: true,
  87307. configurable: true
  87308. });
  87309. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  87310. /**
  87311. * Gets the shadows Hue value.
  87312. * 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).
  87313. */
  87314. get: function () {
  87315. return this._shadowsHue;
  87316. },
  87317. /**
  87318. * Sets the shadows Hue value.
  87319. * 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).
  87320. */
  87321. set: function (value) {
  87322. this._shadowsHue = value;
  87323. this._dirty = true;
  87324. },
  87325. enumerable: true,
  87326. configurable: true
  87327. });
  87328. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  87329. /**
  87330. * Gets the shadows Density value.
  87331. * 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.
  87332. * Values less than zero provide a filter of opposite hue.
  87333. */
  87334. get: function () {
  87335. return this._shadowsDensity;
  87336. },
  87337. /**
  87338. * Sets the shadows Density value.
  87339. * 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.
  87340. * Values less than zero provide a filter of opposite hue.
  87341. */
  87342. set: function (value) {
  87343. this._shadowsDensity = value;
  87344. this._dirty = true;
  87345. },
  87346. enumerable: true,
  87347. configurable: true
  87348. });
  87349. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  87350. /**
  87351. * Gets the shadows Saturation value.
  87352. * 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.
  87353. */
  87354. get: function () {
  87355. return this._shadowsSaturation;
  87356. },
  87357. /**
  87358. * Sets the shadows Saturation value.
  87359. * 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.
  87360. */
  87361. set: function (value) {
  87362. this._shadowsSaturation = value;
  87363. this._dirty = true;
  87364. },
  87365. enumerable: true,
  87366. configurable: true
  87367. });
  87368. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  87369. /**
  87370. * Gets the shadows Exposure value.
  87371. * 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.
  87372. */
  87373. get: function () {
  87374. return this._shadowsExposure;
  87375. },
  87376. /**
  87377. * Sets the shadows Exposure value.
  87378. * 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.
  87379. */
  87380. set: function (value) {
  87381. this._shadowsExposure = value;
  87382. this._dirty = true;
  87383. },
  87384. enumerable: true,
  87385. configurable: true
  87386. });
  87387. /**
  87388. * Returns the class name
  87389. * @returns The class name
  87390. */
  87391. ColorCurves.prototype.getClassName = function () {
  87392. return "ColorCurves";
  87393. };
  87394. /**
  87395. * Binds the color curves to the shader.
  87396. * @param colorCurves The color curve to bind
  87397. * @param effect The effect to bind to
  87398. * @param positiveUniform The positive uniform shader parameter
  87399. * @param neutralUniform The neutral uniform shader parameter
  87400. * @param negativeUniform The negative uniform shader parameter
  87401. */
  87402. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  87403. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  87404. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  87405. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  87406. if (colorCurves._dirty) {
  87407. colorCurves._dirty = false;
  87408. // Fill in global info.
  87409. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  87410. // Compute highlights info.
  87411. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  87412. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  87413. // Compute midtones info.
  87414. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  87415. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  87416. // Compute shadows info.
  87417. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  87418. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  87419. // Compute deltas (neutral is midtones).
  87420. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  87421. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  87422. }
  87423. if (effect) {
  87424. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  87425. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  87426. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  87427. }
  87428. };
  87429. /**
  87430. * Prepare the list of uniforms associated with the ColorCurves effects.
  87431. * @param uniformsList The list of uniforms used in the effect
  87432. */
  87433. ColorCurves.PrepareUniforms = function (uniformsList) {
  87434. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  87435. };
  87436. /**
  87437. * Returns color grading data based on a hue, density, saturation and exposure value.
  87438. * @param filterHue The hue of the color filter.
  87439. * @param filterDensity The density of the color filter.
  87440. * @param saturation The saturation.
  87441. * @param exposure The exposure.
  87442. * @param result The result data container.
  87443. */
  87444. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  87445. if (hue == null) {
  87446. return;
  87447. }
  87448. hue = ColorCurves.clamp(hue, 0, 360);
  87449. density = ColorCurves.clamp(density, -100, 100);
  87450. saturation = ColorCurves.clamp(saturation, -100, 100);
  87451. exposure = ColorCurves.clamp(exposure, -100, 100);
  87452. // Remap the slider/config filter density with non-linear mapping and also scale by half
  87453. // so that the maximum filter density is only 50% control. This provides fine control
  87454. // for small values and reasonable range.
  87455. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  87456. density *= 0.5;
  87457. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  87458. if (density < 0) {
  87459. density *= -1;
  87460. hue = (hue + 180) % 360;
  87461. }
  87462. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  87463. result.scaleToRef(2, result);
  87464. result.a = 1 + 0.01 * saturation;
  87465. };
  87466. /**
  87467. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  87468. * @param value The input slider value in range [-100,100].
  87469. * @returns Adjusted value.
  87470. */
  87471. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  87472. value /= 100;
  87473. var x = Math.abs(value);
  87474. x = Math.pow(x, 2);
  87475. if (value < 0) {
  87476. x *= -1;
  87477. }
  87478. x *= 100;
  87479. return x;
  87480. };
  87481. /**
  87482. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  87483. * @param hue The hue (H) input.
  87484. * @param saturation The saturation (S) input.
  87485. * @param brightness The brightness (B) input.
  87486. * @result An RGBA color represented as Vector4.
  87487. */
  87488. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  87489. var h = ColorCurves.clamp(hue, 0, 360);
  87490. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  87491. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  87492. if (s === 0) {
  87493. result.r = v;
  87494. result.g = v;
  87495. result.b = v;
  87496. }
  87497. else {
  87498. // sector 0 to 5
  87499. h /= 60;
  87500. var i = Math.floor(h);
  87501. // fractional part of h
  87502. var f = h - i;
  87503. var p = v * (1 - s);
  87504. var q = v * (1 - s * f);
  87505. var t = v * (1 - s * (1 - f));
  87506. switch (i) {
  87507. case 0:
  87508. result.r = v;
  87509. result.g = t;
  87510. result.b = p;
  87511. break;
  87512. case 1:
  87513. result.r = q;
  87514. result.g = v;
  87515. result.b = p;
  87516. break;
  87517. case 2:
  87518. result.r = p;
  87519. result.g = v;
  87520. result.b = t;
  87521. break;
  87522. case 3:
  87523. result.r = p;
  87524. result.g = q;
  87525. result.b = v;
  87526. break;
  87527. case 4:
  87528. result.r = t;
  87529. result.g = p;
  87530. result.b = v;
  87531. break;
  87532. default: // case 5:
  87533. result.r = v;
  87534. result.g = p;
  87535. result.b = q;
  87536. break;
  87537. }
  87538. }
  87539. result.a = 1;
  87540. };
  87541. /**
  87542. * Returns a value clamped between min and max
  87543. * @param value The value to clamp
  87544. * @param min The minimum of value
  87545. * @param max The maximum of value
  87546. * @returns The clamped value.
  87547. */
  87548. ColorCurves.clamp = function (value, min, max) {
  87549. return Math.min(Math.max(value, min), max);
  87550. };
  87551. /**
  87552. * Clones the current color curve instance.
  87553. * @return The cloned curves
  87554. */
  87555. ColorCurves.prototype.clone = function () {
  87556. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  87557. };
  87558. /**
  87559. * Serializes the current color curve instance to a json representation.
  87560. * @return a JSON representation
  87561. */
  87562. ColorCurves.prototype.serialize = function () {
  87563. return BABYLON.SerializationHelper.Serialize(this);
  87564. };
  87565. /**
  87566. * Parses the color curve from a json representation.
  87567. * @param source the JSON source to parse
  87568. * @return The parsed curves
  87569. */
  87570. ColorCurves.Parse = function (source) {
  87571. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  87572. };
  87573. __decorate([
  87574. BABYLON.serialize()
  87575. ], ColorCurves.prototype, "_globalHue", void 0);
  87576. __decorate([
  87577. BABYLON.serialize()
  87578. ], ColorCurves.prototype, "_globalDensity", void 0);
  87579. __decorate([
  87580. BABYLON.serialize()
  87581. ], ColorCurves.prototype, "_globalSaturation", void 0);
  87582. __decorate([
  87583. BABYLON.serialize()
  87584. ], ColorCurves.prototype, "_globalExposure", void 0);
  87585. __decorate([
  87586. BABYLON.serialize()
  87587. ], ColorCurves.prototype, "_highlightsHue", void 0);
  87588. __decorate([
  87589. BABYLON.serialize()
  87590. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  87591. __decorate([
  87592. BABYLON.serialize()
  87593. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  87594. __decorate([
  87595. BABYLON.serialize()
  87596. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  87597. __decorate([
  87598. BABYLON.serialize()
  87599. ], ColorCurves.prototype, "_midtonesHue", void 0);
  87600. __decorate([
  87601. BABYLON.serialize()
  87602. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  87603. __decorate([
  87604. BABYLON.serialize()
  87605. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  87606. __decorate([
  87607. BABYLON.serialize()
  87608. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  87609. return ColorCurves;
  87610. }());
  87611. BABYLON.ColorCurves = ColorCurves;
  87612. })(BABYLON || (BABYLON = {}));
  87613. //# sourceMappingURL=babylon.colorCurves.js.map
  87614. var BABYLON;
  87615. (function (BABYLON) {
  87616. /**
  87617. * Post process which applies a refractin texture
  87618. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  87619. */
  87620. var RefractionPostProcess = /** @class */ (function (_super) {
  87621. __extends(RefractionPostProcess, _super);
  87622. /**
  87623. * Initializes the RefractionPostProcess
  87624. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  87625. * @param name The name of the effect.
  87626. * @param refractionTextureUrl Url of the refraction texture to use
  87627. * @param color the base color of the refraction (used to taint the rendering)
  87628. * @param depth simulated refraction depth
  87629. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  87630. * @param camera The camera to apply the render pass to.
  87631. * @param options The required width/height ratio to downsize to before computing the render pass.
  87632. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87633. * @param engine The engine which the post process will be applied. (default: current engine)
  87634. * @param reusable If the post process can be reused on the same frame. (default: false)
  87635. */
  87636. function RefractionPostProcess(name, refractionTextureUrl,
  87637. /** the base color of the refraction (used to taint the rendering) */
  87638. color,
  87639. /** simulated refraction depth */
  87640. depth,
  87641. /** the coefficient of the base color (0 to remove base color tainting) */
  87642. colorLevel, options, camera, samplingMode, engine, reusable) {
  87643. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  87644. _this.color = color;
  87645. _this.depth = depth;
  87646. _this.colorLevel = colorLevel;
  87647. _this._ownRefractionTexture = true;
  87648. _this.onActivateObservable.add(function (cam) {
  87649. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  87650. });
  87651. _this.onApplyObservable.add(function (effect) {
  87652. effect.setColor3("baseColor", _this.color);
  87653. effect.setFloat("depth", _this.depth);
  87654. effect.setFloat("colorLevel", _this.colorLevel);
  87655. effect.setTexture("refractionSampler", _this._refTexture);
  87656. });
  87657. return _this;
  87658. }
  87659. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  87660. /**
  87661. * Gets or sets the refraction texture
  87662. * Please note that you are responsible for disposing the texture if you set it manually
  87663. */
  87664. get: function () {
  87665. return this._refTexture;
  87666. },
  87667. set: function (value) {
  87668. if (this._refTexture && this._ownRefractionTexture) {
  87669. this._refTexture.dispose();
  87670. }
  87671. this._refTexture = value;
  87672. this._ownRefractionTexture = false;
  87673. },
  87674. enumerable: true,
  87675. configurable: true
  87676. });
  87677. // Methods
  87678. /**
  87679. * Disposes of the post process
  87680. * @param camera Camera to dispose post process on
  87681. */
  87682. RefractionPostProcess.prototype.dispose = function (camera) {
  87683. if (this._refTexture && this._ownRefractionTexture) {
  87684. this._refTexture.dispose();
  87685. this._refTexture = null;
  87686. }
  87687. _super.prototype.dispose.call(this, camera);
  87688. };
  87689. return RefractionPostProcess;
  87690. }(BABYLON.PostProcess));
  87691. BABYLON.RefractionPostProcess = RefractionPostProcess;
  87692. })(BABYLON || (BABYLON = {}));
  87693. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  87694. var BABYLON;
  87695. (function (BABYLON) {
  87696. /**
  87697. * Post process used to render in black and white
  87698. */
  87699. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  87700. __extends(BlackAndWhitePostProcess, _super);
  87701. /**
  87702. * Creates a black and white post process
  87703. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  87704. * @param name The name of the effect.
  87705. * @param options The required width/height ratio to downsize to before computing the render pass.
  87706. * @param camera The camera to apply the render pass to.
  87707. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87708. * @param engine The engine which the post process will be applied. (default: current engine)
  87709. * @param reusable If the post process can be reused on the same frame. (default: false)
  87710. */
  87711. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  87712. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  87713. /**
  87714. * Linear about to convert he result to black and white (default: 1)
  87715. */
  87716. _this.degree = 1;
  87717. _this.onApplyObservable.add(function (effect) {
  87718. effect.setFloat("degree", _this.degree);
  87719. });
  87720. return _this;
  87721. }
  87722. return BlackAndWhitePostProcess;
  87723. }(BABYLON.PostProcess));
  87724. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  87725. })(BABYLON || (BABYLON = {}));
  87726. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  87727. var BABYLON;
  87728. (function (BABYLON) {
  87729. /**
  87730. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  87731. * input texture to perform effects such as edge detection or sharpening
  87732. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87733. */
  87734. var ConvolutionPostProcess = /** @class */ (function (_super) {
  87735. __extends(ConvolutionPostProcess, _super);
  87736. /**
  87737. * Creates a new instance ConvolutionPostProcess
  87738. * @param name The name of the effect.
  87739. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  87740. * @param options The required width/height ratio to downsize to before computing the render pass.
  87741. * @param camera The camera to apply the render pass to.
  87742. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87743. * @param engine The engine which the post process will be applied. (default: current engine)
  87744. * @param reusable If the post process can be reused on the same frame. (default: false)
  87745. * @param textureType Type of textures used when performing the post process. (default: 0)
  87746. */
  87747. function ConvolutionPostProcess(name,
  87748. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  87749. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  87750. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87751. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  87752. _this.kernel = kernel;
  87753. _this.onApply = function (effect) {
  87754. effect.setFloat2("screenSize", _this.width, _this.height);
  87755. effect.setArray("kernel", _this.kernel);
  87756. };
  87757. return _this;
  87758. }
  87759. // Statics
  87760. /**
  87761. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87762. */
  87763. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  87764. /**
  87765. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87766. */
  87767. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  87768. /**
  87769. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87770. */
  87771. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  87772. /**
  87773. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87774. */
  87775. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  87776. /**
  87777. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87778. */
  87779. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  87780. /**
  87781. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87782. */
  87783. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  87784. return ConvolutionPostProcess;
  87785. }(BABYLON.PostProcess));
  87786. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  87787. })(BABYLON || (BABYLON = {}));
  87788. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  87789. var BABYLON;
  87790. (function (BABYLON) {
  87791. /**
  87792. * Applies a kernel filter to the image
  87793. */
  87794. var FilterPostProcess = /** @class */ (function (_super) {
  87795. __extends(FilterPostProcess, _super);
  87796. /**
  87797. *
  87798. * @param name The name of the effect.
  87799. * @param kernelMatrix The matrix to be applied to the image
  87800. * @param options The required width/height ratio to downsize to before computing the render pass.
  87801. * @param camera The camera to apply the render pass to.
  87802. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87803. * @param engine The engine which the post process will be applied. (default: current engine)
  87804. * @param reusable If the post process can be reused on the same frame. (default: false)
  87805. */
  87806. function FilterPostProcess(name,
  87807. /** The matrix to be applied to the image */
  87808. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  87809. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  87810. _this.kernelMatrix = kernelMatrix;
  87811. _this.onApply = function (effect) {
  87812. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  87813. };
  87814. return _this;
  87815. }
  87816. return FilterPostProcess;
  87817. }(BABYLON.PostProcess));
  87818. BABYLON.FilterPostProcess = FilterPostProcess;
  87819. })(BABYLON || (BABYLON = {}));
  87820. //# sourceMappingURL=babylon.filterPostProcess.js.map
  87821. var BABYLON;
  87822. (function (BABYLON) {
  87823. /**
  87824. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  87825. */
  87826. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  87827. __extends(VolumetricLightScatteringPostProcess, _super);
  87828. /**
  87829. * @constructor
  87830. * @param {string} name - The post-process name
  87831. * @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)
  87832. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  87833. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  87834. * @param {number} samples - The post-process quality, default 100
  87835. * @param {number} samplingMode - The post-process filtering mode
  87836. * @param {BABYLON.Engine} engine - The babylon engine
  87837. * @param {boolean} reusable - If the post-process is reusable
  87838. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  87839. */
  87840. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  87841. if (samples === void 0) { samples = 100; }
  87842. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87843. 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;
  87844. _this._screenCoordinates = BABYLON.Vector2.Zero();
  87845. /**
  87846. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  87847. */
  87848. _this.customMeshPosition = BABYLON.Vector3.Zero();
  87849. /**
  87850. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  87851. */
  87852. _this.useCustomMeshPosition = false;
  87853. /**
  87854. * If the post-process should inverse the light scattering direction
  87855. */
  87856. _this.invert = true;
  87857. /**
  87858. * Array containing the excluded meshes not rendered in the internal pass
  87859. */
  87860. _this.excludedMeshes = new Array();
  87861. /**
  87862. * Controls the overall intensity of the post-process
  87863. */
  87864. _this.exposure = 0.3;
  87865. /**
  87866. * Dissipates each sample's contribution in range [0, 1]
  87867. */
  87868. _this.decay = 0.96815;
  87869. /**
  87870. * Controls the overall intensity of each sample
  87871. */
  87872. _this.weight = 0.58767;
  87873. /**
  87874. * Controls the density of each sample
  87875. */
  87876. _this.density = 0.926;
  87877. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  87878. engine = scene.getEngine();
  87879. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  87880. // Configure mesh
  87881. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  87882. // Configure
  87883. _this._createPass(scene, ratio.passRatio || ratio);
  87884. _this.onActivate = function (camera) {
  87885. if (!_this.isSupported) {
  87886. _this.dispose(camera);
  87887. }
  87888. _this.onActivate = null;
  87889. };
  87890. _this.onApplyObservable.add(function (effect) {
  87891. _this._updateMeshScreenCoordinates(scene);
  87892. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  87893. effect.setFloat("exposure", _this.exposure);
  87894. effect.setFloat("decay", _this.decay);
  87895. effect.setFloat("weight", _this.weight);
  87896. effect.setFloat("density", _this.density);
  87897. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  87898. });
  87899. return _this;
  87900. }
  87901. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  87902. /**
  87903. * @hidden
  87904. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  87905. */
  87906. get: function () {
  87907. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87908. return false;
  87909. },
  87910. set: function (useDiffuseColor) {
  87911. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87912. },
  87913. enumerable: true,
  87914. configurable: true
  87915. });
  87916. /**
  87917. * Returns the string "VolumetricLightScatteringPostProcess"
  87918. * @returns "VolumetricLightScatteringPostProcess"
  87919. */
  87920. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  87921. return "VolumetricLightScatteringPostProcess";
  87922. };
  87923. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  87924. var mesh = subMesh.getMesh();
  87925. // Render this.mesh as default
  87926. if (mesh === this.mesh && mesh.material) {
  87927. return mesh.material.isReady(mesh);
  87928. }
  87929. var defines = [];
  87930. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87931. var material = subMesh.getMaterial();
  87932. // Alpha test
  87933. if (material) {
  87934. if (material.needAlphaTesting()) {
  87935. defines.push("#define ALPHATEST");
  87936. }
  87937. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87938. attribs.push(BABYLON.VertexBuffer.UVKind);
  87939. defines.push("#define UV1");
  87940. }
  87941. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  87942. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87943. defines.push("#define UV2");
  87944. }
  87945. }
  87946. // Bones
  87947. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  87948. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  87949. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  87950. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  87951. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  87952. }
  87953. else {
  87954. defines.push("#define NUM_BONE_INFLUENCERS 0");
  87955. }
  87956. // Instances
  87957. if (useInstances) {
  87958. defines.push("#define INSTANCES");
  87959. attribs.push("world0");
  87960. attribs.push("world1");
  87961. attribs.push("world2");
  87962. attribs.push("world3");
  87963. }
  87964. // Get correct effect
  87965. var join = defines.join("\n");
  87966. if (this._cachedDefines !== join) {
  87967. this._cachedDefines = join;
  87968. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  87969. }
  87970. return this._volumetricLightScatteringPass.isReady();
  87971. };
  87972. /**
  87973. * Sets the new light position for light scattering effect
  87974. * @param position The new custom light position
  87975. */
  87976. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  87977. this.customMeshPosition = position;
  87978. };
  87979. /**
  87980. * Returns the light position for light scattering effect
  87981. * @return {BABYLON.Vector3} The custom light position
  87982. */
  87983. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  87984. return this.customMeshPosition;
  87985. };
  87986. /**
  87987. * Disposes the internal assets and detaches the post-process from the camera
  87988. */
  87989. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  87990. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  87991. if (rttIndex !== -1) {
  87992. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  87993. }
  87994. this._volumetricLightScatteringRTT.dispose();
  87995. _super.prototype.dispose.call(this, camera);
  87996. };
  87997. /**
  87998. * Returns the render target texture used by the post-process
  87999. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  88000. */
  88001. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  88002. return this._volumetricLightScatteringRTT;
  88003. };
  88004. // Private methods
  88005. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  88006. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  88007. return true;
  88008. }
  88009. return false;
  88010. };
  88011. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  88012. var _this = this;
  88013. var engine = scene.getEngine();
  88014. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88015. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88016. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88017. this._volumetricLightScatteringRTT.renderList = null;
  88018. this._volumetricLightScatteringRTT.renderParticles = false;
  88019. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  88020. var camera = this.getCamera();
  88021. if (camera) {
  88022. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  88023. }
  88024. else {
  88025. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  88026. }
  88027. // Custom render function for submeshes
  88028. var renderSubMesh = function (subMesh) {
  88029. var mesh = subMesh.getRenderingMesh();
  88030. if (_this._meshExcluded(mesh)) {
  88031. return;
  88032. }
  88033. var material = subMesh.getMaterial();
  88034. if (!material) {
  88035. return;
  88036. }
  88037. var scene = mesh.getScene();
  88038. var engine = scene.getEngine();
  88039. // Culling
  88040. engine.setState(material.backFaceCulling);
  88041. // Managing instances
  88042. var batch = mesh._getInstancesRenderList(subMesh._id);
  88043. if (batch.mustReturn) {
  88044. return;
  88045. }
  88046. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  88047. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  88048. var effect = _this._volumetricLightScatteringPass;
  88049. if (mesh === _this.mesh) {
  88050. if (subMesh.effect) {
  88051. effect = subMesh.effect;
  88052. }
  88053. else {
  88054. effect = material.getEffect();
  88055. }
  88056. }
  88057. engine.enableEffect(effect);
  88058. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  88059. if (mesh === _this.mesh) {
  88060. material.bind(mesh.getWorldMatrix(), mesh);
  88061. }
  88062. else {
  88063. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  88064. // Alpha test
  88065. if (material && material.needAlphaTesting()) {
  88066. var alphaTexture = material.getAlphaTestTexture();
  88067. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  88068. if (alphaTexture) {
  88069. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88070. }
  88071. }
  88072. // Bones
  88073. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88074. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88075. }
  88076. }
  88077. // Draw
  88078. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  88079. }
  88080. };
  88081. // Render target texture callbacks
  88082. var savedSceneClearColor;
  88083. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  88084. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  88085. savedSceneClearColor = scene.clearColor;
  88086. scene.clearColor = sceneClearColor;
  88087. });
  88088. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  88089. scene.clearColor = savedSceneClearColor;
  88090. });
  88091. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  88092. var engine = scene.getEngine();
  88093. var index;
  88094. if (depthOnlySubMeshes.length) {
  88095. engine.setColorWrite(false);
  88096. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  88097. renderSubMesh(depthOnlySubMeshes.data[index]);
  88098. }
  88099. engine.setColorWrite(true);
  88100. }
  88101. for (index = 0; index < opaqueSubMeshes.length; index++) {
  88102. renderSubMesh(opaqueSubMeshes.data[index]);
  88103. }
  88104. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  88105. renderSubMesh(alphaTestSubMeshes.data[index]);
  88106. }
  88107. if (transparentSubMeshes.length) {
  88108. // Sort sub meshes
  88109. for (index = 0; index < transparentSubMeshes.length; index++) {
  88110. var submesh = transparentSubMeshes.data[index];
  88111. var boundingInfo = submesh.getBoundingInfo();
  88112. if (boundingInfo && scene.activeCamera) {
  88113. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  88114. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  88115. }
  88116. }
  88117. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  88118. sortedArray.sort(function (a, b) {
  88119. // Alpha index first
  88120. if (a._alphaIndex > b._alphaIndex) {
  88121. return 1;
  88122. }
  88123. if (a._alphaIndex < b._alphaIndex) {
  88124. return -1;
  88125. }
  88126. // Then distance to camera
  88127. if (a._distanceToCamera < b._distanceToCamera) {
  88128. return 1;
  88129. }
  88130. if (a._distanceToCamera > b._distanceToCamera) {
  88131. return -1;
  88132. }
  88133. return 0;
  88134. });
  88135. // Render sub meshes
  88136. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  88137. for (index = 0; index < sortedArray.length; index++) {
  88138. renderSubMesh(sortedArray[index]);
  88139. }
  88140. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88141. }
  88142. };
  88143. };
  88144. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  88145. var transform = scene.getTransformMatrix();
  88146. var meshPosition;
  88147. if (this.useCustomMeshPosition) {
  88148. meshPosition = this.customMeshPosition;
  88149. }
  88150. else if (this.attachedNode) {
  88151. meshPosition = this.attachedNode.position;
  88152. }
  88153. else {
  88154. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  88155. }
  88156. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  88157. this._screenCoordinates.x = pos.x / this._viewPort.width;
  88158. this._screenCoordinates.y = pos.y / this._viewPort.height;
  88159. if (this.invert)
  88160. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  88161. };
  88162. // Static methods
  88163. /**
  88164. * Creates a default mesh for the Volumeric Light Scattering post-process
  88165. * @param name The mesh name
  88166. * @param scene The scene where to create the mesh
  88167. * @return {BABYLON.Mesh} the default mesh
  88168. */
  88169. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  88170. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  88171. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  88172. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  88173. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  88174. mesh.material = material;
  88175. return mesh;
  88176. };
  88177. __decorate([
  88178. BABYLON.serializeAsVector3()
  88179. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  88180. __decorate([
  88181. BABYLON.serialize()
  88182. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  88183. __decorate([
  88184. BABYLON.serialize()
  88185. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  88186. __decorate([
  88187. BABYLON.serializeAsMeshReference()
  88188. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  88189. __decorate([
  88190. BABYLON.serialize()
  88191. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  88192. __decorate([
  88193. BABYLON.serialize()
  88194. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  88195. __decorate([
  88196. BABYLON.serialize()
  88197. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  88198. __decorate([
  88199. BABYLON.serialize()
  88200. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  88201. __decorate([
  88202. BABYLON.serialize()
  88203. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  88204. return VolumetricLightScatteringPostProcess;
  88205. }(BABYLON.PostProcess));
  88206. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  88207. })(BABYLON || (BABYLON = {}));
  88208. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  88209. var BABYLON;
  88210. (function (BABYLON) {
  88211. /**
  88212. *
  88213. * This post-process allows the modification of rendered colors by using
  88214. * a 'look-up table' (LUT). This effect is also called Color Grading.
  88215. *
  88216. * The object needs to be provided an url to a texture containing the color
  88217. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  88218. * Use an image editing software to tweak the LUT to match your needs.
  88219. *
  88220. * For an example of a color LUT, see here:
  88221. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  88222. * For explanations on color grading, see here:
  88223. * @see http://udn.epicgames.com/Three/ColorGrading.html
  88224. *
  88225. */
  88226. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  88227. __extends(ColorCorrectionPostProcess, _super);
  88228. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  88229. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  88230. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  88231. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  88232. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88233. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88234. _this.onApply = function (effect) {
  88235. effect.setTexture("colorTable", _this._colorTableTexture);
  88236. };
  88237. return _this;
  88238. }
  88239. return ColorCorrectionPostProcess;
  88240. }(BABYLON.PostProcess));
  88241. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  88242. })(BABYLON || (BABYLON = {}));
  88243. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  88244. var BABYLON;
  88245. (function (BABYLON) {
  88246. /** Defines operator used for tonemapping */
  88247. var TonemappingOperator;
  88248. (function (TonemappingOperator) {
  88249. /** Hable */
  88250. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  88251. /** Reinhard */
  88252. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  88253. /** HejiDawson */
  88254. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  88255. /** Photographic */
  88256. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  88257. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  88258. ;
  88259. /**
  88260. * Defines a post process to apply tone mapping
  88261. */
  88262. var TonemapPostProcess = /** @class */ (function (_super) {
  88263. __extends(TonemapPostProcess, _super);
  88264. /**
  88265. * Creates a new TonemapPostProcess
  88266. * @param name defines the name of the postprocess
  88267. * @param _operator defines the operator to use
  88268. * @param exposureAdjustment defines the required exposure adjustement
  88269. * @param camera defines the camera to use (can be null)
  88270. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  88271. * @param engine defines the hosting engine (can be ignore if camera is set)
  88272. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  88273. */
  88274. function TonemapPostProcess(name, _operator,
  88275. /** Defines the required exposure adjustement */
  88276. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  88277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88278. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88279. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  88280. _this._operator = _operator;
  88281. _this.exposureAdjustment = exposureAdjustment;
  88282. var defines = "#define ";
  88283. if (_this._operator === TonemappingOperator.Hable)
  88284. defines += "HABLE_TONEMAPPING";
  88285. else if (_this._operator === TonemappingOperator.Reinhard)
  88286. defines += "REINHARD_TONEMAPPING";
  88287. else if (_this._operator === TonemappingOperator.HejiDawson)
  88288. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  88289. else if (_this._operator === TonemappingOperator.Photographic)
  88290. defines += "PHOTOGRAPHIC_TONEMAPPING";
  88291. //sadly a second call to create the effect.
  88292. _this.updateEffect(defines);
  88293. _this.onApply = function (effect) {
  88294. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  88295. };
  88296. return _this;
  88297. }
  88298. return TonemapPostProcess;
  88299. }(BABYLON.PostProcess));
  88300. BABYLON.TonemapPostProcess = TonemapPostProcess;
  88301. })(BABYLON || (BABYLON = {}));
  88302. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  88303. var BABYLON;
  88304. (function (BABYLON) {
  88305. /**
  88306. * DisplayPassPostProcess which produces an output the same as it's input
  88307. */
  88308. var DisplayPassPostProcess = /** @class */ (function (_super) {
  88309. __extends(DisplayPassPostProcess, _super);
  88310. /**
  88311. * Creates the DisplayPassPostProcess
  88312. * @param name The name of the effect.
  88313. * @param options The required width/height ratio to downsize to before computing the render pass.
  88314. * @param camera The camera to apply the render pass to.
  88315. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88316. * @param engine The engine which the post process will be applied. (default: current engine)
  88317. * @param reusable If the post process can be reused on the same frame. (default: false)
  88318. */
  88319. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  88320. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  88321. }
  88322. return DisplayPassPostProcess;
  88323. }(BABYLON.PostProcess));
  88324. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  88325. })(BABYLON || (BABYLON = {}));
  88326. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  88327. var BABYLON;
  88328. (function (BABYLON) {
  88329. /**
  88330. * Extracts highlights from the image
  88331. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  88332. */
  88333. var HighlightsPostProcess = /** @class */ (function (_super) {
  88334. __extends(HighlightsPostProcess, _super);
  88335. /**
  88336. * Extracts highlights from the image
  88337. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  88338. * @param name The name of the effect.
  88339. * @param options The required width/height ratio to downsize to before computing the render pass.
  88340. * @param camera The camera to apply the render pass to.
  88341. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88342. * @param engine The engine which the post process will be applied. (default: current engine)
  88343. * @param reusable If the post process can be reused on the same frame. (default: false)
  88344. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  88345. */
  88346. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  88347. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88348. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  88349. }
  88350. return HighlightsPostProcess;
  88351. }(BABYLON.PostProcess));
  88352. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  88353. })(BABYLON || (BABYLON = {}));
  88354. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  88355. var BABYLON;
  88356. (function (BABYLON) {
  88357. /**
  88358. * ImageProcessingPostProcess
  88359. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  88360. */
  88361. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  88362. __extends(ImageProcessingPostProcess, _super);
  88363. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  88364. if (camera === void 0) { camera = null; }
  88365. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88366. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  88367. _this._fromLinearSpace = true;
  88368. /**
  88369. * Defines cache preventing GC.
  88370. */
  88371. _this._defines = {
  88372. IMAGEPROCESSING: false,
  88373. VIGNETTE: false,
  88374. VIGNETTEBLENDMODEMULTIPLY: false,
  88375. VIGNETTEBLENDMODEOPAQUE: false,
  88376. TONEMAPPING: false,
  88377. TONEMAPPING_ACES: false,
  88378. CONTRAST: false,
  88379. COLORCURVES: false,
  88380. COLORGRADING: false,
  88381. COLORGRADING3D: false,
  88382. FROMLINEARSPACE: false,
  88383. SAMPLER3DGREENDEPTH: false,
  88384. SAMPLER3DBGRMAP: false,
  88385. IMAGEPROCESSINGPOSTPROCESS: false,
  88386. EXPOSURE: false,
  88387. };
  88388. // Setup the configuration as forced by the constructor. This would then not force the
  88389. // scene materials output in linear space and let untouched the default forward pass.
  88390. if (imageProcessingConfiguration) {
  88391. imageProcessingConfiguration.applyByPostProcess = true;
  88392. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  88393. // This will cause the shader to be compiled
  88394. _this.fromLinearSpace = false;
  88395. }
  88396. // Setup the default processing configuration to the scene.
  88397. else {
  88398. _this._attachImageProcessingConfiguration(null, true);
  88399. _this.imageProcessingConfiguration.applyByPostProcess = true;
  88400. }
  88401. _this.onApply = function (effect) {
  88402. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  88403. };
  88404. return _this;
  88405. }
  88406. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  88407. /**
  88408. * Gets the image processing configuration used either in this material.
  88409. */
  88410. get: function () {
  88411. return this._imageProcessingConfiguration;
  88412. },
  88413. /**
  88414. * Sets the Default image processing configuration used either in the this material.
  88415. *
  88416. * If sets to null, the scene one is in use.
  88417. */
  88418. set: function (value) {
  88419. this._attachImageProcessingConfiguration(value);
  88420. },
  88421. enumerable: true,
  88422. configurable: true
  88423. });
  88424. /**
  88425. * Attaches a new image processing configuration to the PBR Material.
  88426. * @param configuration
  88427. */
  88428. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  88429. var _this = this;
  88430. if (doNotBuild === void 0) { doNotBuild = false; }
  88431. if (configuration === this._imageProcessingConfiguration) {
  88432. return;
  88433. }
  88434. // Detaches observer.
  88435. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88436. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88437. }
  88438. // Pick the scene configuration if needed.
  88439. if (!configuration) {
  88440. var scene = null;
  88441. var engine = this.getEngine();
  88442. var camera = this.getCamera();
  88443. if (camera) {
  88444. scene = camera.getScene();
  88445. }
  88446. else if (engine && engine.scenes) {
  88447. var scenes = engine.scenes;
  88448. scene = scenes[scenes.length - 1];
  88449. }
  88450. else {
  88451. scene = BABYLON.Engine.LastCreatedScene;
  88452. }
  88453. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  88454. }
  88455. else {
  88456. this._imageProcessingConfiguration = configuration;
  88457. }
  88458. // Attaches observer.
  88459. if (this._imageProcessingConfiguration) {
  88460. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88461. _this._updateParameters();
  88462. });
  88463. }
  88464. // Ensure the effect will be rebuilt.
  88465. if (!doNotBuild) {
  88466. this._updateParameters();
  88467. }
  88468. };
  88469. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  88470. /**
  88471. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  88472. */
  88473. get: function () {
  88474. return this.imageProcessingConfiguration.colorCurves;
  88475. },
  88476. /**
  88477. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  88478. */
  88479. set: function (value) {
  88480. this.imageProcessingConfiguration.colorCurves = value;
  88481. },
  88482. enumerable: true,
  88483. configurable: true
  88484. });
  88485. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  88486. /**
  88487. * Gets wether the color curves effect is enabled.
  88488. */
  88489. get: function () {
  88490. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88491. },
  88492. /**
  88493. * Sets wether the color curves effect is enabled.
  88494. */
  88495. set: function (value) {
  88496. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88497. },
  88498. enumerable: true,
  88499. configurable: true
  88500. });
  88501. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  88502. /**
  88503. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  88504. */
  88505. get: function () {
  88506. return this.imageProcessingConfiguration.colorGradingTexture;
  88507. },
  88508. /**
  88509. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  88510. */
  88511. set: function (value) {
  88512. this.imageProcessingConfiguration.colorGradingTexture = value;
  88513. },
  88514. enumerable: true,
  88515. configurable: true
  88516. });
  88517. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  88518. /**
  88519. * Gets wether the color grading effect is enabled.
  88520. */
  88521. get: function () {
  88522. return this.imageProcessingConfiguration.colorGradingEnabled;
  88523. },
  88524. /**
  88525. * Gets wether the color grading effect is enabled.
  88526. */
  88527. set: function (value) {
  88528. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88529. },
  88530. enumerable: true,
  88531. configurable: true
  88532. });
  88533. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  88534. /**
  88535. * Gets exposure used in the effect.
  88536. */
  88537. get: function () {
  88538. return this.imageProcessingConfiguration.exposure;
  88539. },
  88540. /**
  88541. * Sets exposure used in the effect.
  88542. */
  88543. set: function (value) {
  88544. this.imageProcessingConfiguration.exposure = value;
  88545. },
  88546. enumerable: true,
  88547. configurable: true
  88548. });
  88549. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  88550. /**
  88551. * Gets wether tonemapping is enabled or not.
  88552. */
  88553. get: function () {
  88554. return this._imageProcessingConfiguration.toneMappingEnabled;
  88555. },
  88556. /**
  88557. * Sets wether tonemapping is enabled or not
  88558. */
  88559. set: function (value) {
  88560. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88561. },
  88562. enumerable: true,
  88563. configurable: true
  88564. });
  88565. ;
  88566. ;
  88567. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  88568. /**
  88569. * Gets contrast used in the effect.
  88570. */
  88571. get: function () {
  88572. return this.imageProcessingConfiguration.contrast;
  88573. },
  88574. /**
  88575. * Sets contrast used in the effect.
  88576. */
  88577. set: function (value) {
  88578. this.imageProcessingConfiguration.contrast = value;
  88579. },
  88580. enumerable: true,
  88581. configurable: true
  88582. });
  88583. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  88584. /**
  88585. * Gets Vignette stretch size.
  88586. */
  88587. get: function () {
  88588. return this.imageProcessingConfiguration.vignetteStretch;
  88589. },
  88590. /**
  88591. * Sets Vignette stretch size.
  88592. */
  88593. set: function (value) {
  88594. this.imageProcessingConfiguration.vignetteStretch = value;
  88595. },
  88596. enumerable: true,
  88597. configurable: true
  88598. });
  88599. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  88600. /**
  88601. * Gets Vignette centre X Offset.
  88602. */
  88603. get: function () {
  88604. return this.imageProcessingConfiguration.vignetteCentreX;
  88605. },
  88606. /**
  88607. * Sets Vignette centre X Offset.
  88608. */
  88609. set: function (value) {
  88610. this.imageProcessingConfiguration.vignetteCentreX = value;
  88611. },
  88612. enumerable: true,
  88613. configurable: true
  88614. });
  88615. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  88616. /**
  88617. * Gets Vignette centre Y Offset.
  88618. */
  88619. get: function () {
  88620. return this.imageProcessingConfiguration.vignetteCentreY;
  88621. },
  88622. /**
  88623. * Sets Vignette centre Y Offset.
  88624. */
  88625. set: function (value) {
  88626. this.imageProcessingConfiguration.vignetteCentreY = value;
  88627. },
  88628. enumerable: true,
  88629. configurable: true
  88630. });
  88631. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  88632. /**
  88633. * Gets Vignette weight or intensity of the vignette effect.
  88634. */
  88635. get: function () {
  88636. return this.imageProcessingConfiguration.vignetteWeight;
  88637. },
  88638. /**
  88639. * Sets Vignette weight or intensity of the vignette effect.
  88640. */
  88641. set: function (value) {
  88642. this.imageProcessingConfiguration.vignetteWeight = value;
  88643. },
  88644. enumerable: true,
  88645. configurable: true
  88646. });
  88647. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  88648. /**
  88649. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88650. * if vignetteEnabled is set to true.
  88651. */
  88652. get: function () {
  88653. return this.imageProcessingConfiguration.vignetteColor;
  88654. },
  88655. /**
  88656. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88657. * if vignetteEnabled is set to true.
  88658. */
  88659. set: function (value) {
  88660. this.imageProcessingConfiguration.vignetteColor = value;
  88661. },
  88662. enumerable: true,
  88663. configurable: true
  88664. });
  88665. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  88666. /**
  88667. * Gets Camera field of view used by the Vignette effect.
  88668. */
  88669. get: function () {
  88670. return this.imageProcessingConfiguration.vignetteCameraFov;
  88671. },
  88672. /**
  88673. * Sets Camera field of view used by the Vignette effect.
  88674. */
  88675. set: function (value) {
  88676. this.imageProcessingConfiguration.vignetteCameraFov = value;
  88677. },
  88678. enumerable: true,
  88679. configurable: true
  88680. });
  88681. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  88682. /**
  88683. * Gets the vignette blend mode allowing different kind of effect.
  88684. */
  88685. get: function () {
  88686. return this.imageProcessingConfiguration.vignetteBlendMode;
  88687. },
  88688. /**
  88689. * Sets the vignette blend mode allowing different kind of effect.
  88690. */
  88691. set: function (value) {
  88692. this.imageProcessingConfiguration.vignetteBlendMode = value;
  88693. },
  88694. enumerable: true,
  88695. configurable: true
  88696. });
  88697. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  88698. /**
  88699. * Gets wether the vignette effect is enabled.
  88700. */
  88701. get: function () {
  88702. return this.imageProcessingConfiguration.vignetteEnabled;
  88703. },
  88704. /**
  88705. * Sets wether the vignette effect is enabled.
  88706. */
  88707. set: function (value) {
  88708. this.imageProcessingConfiguration.vignetteEnabled = value;
  88709. },
  88710. enumerable: true,
  88711. configurable: true
  88712. });
  88713. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  88714. /**
  88715. * Gets wether the input of the processing is in Gamma or Linear Space.
  88716. */
  88717. get: function () {
  88718. return this._fromLinearSpace;
  88719. },
  88720. /**
  88721. * Sets wether the input of the processing is in Gamma or Linear Space.
  88722. */
  88723. set: function (value) {
  88724. if (this._fromLinearSpace === value) {
  88725. return;
  88726. }
  88727. this._fromLinearSpace = value;
  88728. this._updateParameters();
  88729. },
  88730. enumerable: true,
  88731. configurable: true
  88732. });
  88733. /**
  88734. * "ImageProcessingPostProcess"
  88735. * @returns "ImageProcessingPostProcess"
  88736. */
  88737. ImageProcessingPostProcess.prototype.getClassName = function () {
  88738. return "ImageProcessingPostProcess";
  88739. };
  88740. ImageProcessingPostProcess.prototype._updateParameters = function () {
  88741. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  88742. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  88743. var defines = "";
  88744. for (var define in this._defines) {
  88745. if (this._defines[define]) {
  88746. defines += "#define " + define + ";\r\n";
  88747. }
  88748. }
  88749. var samplers = ["textureSampler"];
  88750. var uniforms = ["scale"];
  88751. if (BABYLON.ImageProcessingConfiguration) {
  88752. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  88753. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  88754. }
  88755. this.updateEffect(defines, uniforms, samplers);
  88756. };
  88757. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  88758. _super.prototype.dispose.call(this, camera);
  88759. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88760. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88761. }
  88762. if (this._imageProcessingConfiguration) {
  88763. this.imageProcessingConfiguration.applyByPostProcess = false;
  88764. }
  88765. };
  88766. __decorate([
  88767. BABYLON.serialize()
  88768. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  88769. return ImageProcessingPostProcess;
  88770. }(BABYLON.PostProcess));
  88771. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  88772. })(BABYLON || (BABYLON = {}));
  88773. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  88774. var BABYLON;
  88775. (function (BABYLON) {
  88776. /**
  88777. * Class used to store bone information
  88778. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88779. */
  88780. var Bone = /** @class */ (function (_super) {
  88781. __extends(Bone, _super);
  88782. /**
  88783. * Create a new bone
  88784. * @param name defines the bone name
  88785. * @param skeleton defines the parent skeleton
  88786. * @param parentBone defines the parent (can be null if the bone is the root)
  88787. * @param localMatrix defines the local matrix
  88788. * @param restPose defines the rest pose matrix
  88789. * @param baseMatrix defines the base matrix
  88790. * @param index defines index of the bone in the hiearchy
  88791. */
  88792. function Bone(
  88793. /**
  88794. * defines the bone name
  88795. */
  88796. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  88797. if (parentBone === void 0) { parentBone = null; }
  88798. if (localMatrix === void 0) { localMatrix = null; }
  88799. if (restPose === void 0) { restPose = null; }
  88800. if (baseMatrix === void 0) { baseMatrix = null; }
  88801. if (index === void 0) { index = null; }
  88802. var _this = _super.call(this, name, skeleton.getScene()) || this;
  88803. _this.name = name;
  88804. /**
  88805. * Gets the list of child bones
  88806. */
  88807. _this.children = new Array();
  88808. /** Gets the animations associated with this bone */
  88809. _this.animations = new Array();
  88810. /**
  88811. * @hidden Internal only
  88812. * Set this value to map this bone to a different index in the transform matrices
  88813. * Set this value to -1 to exclude the bone from the transform matrices
  88814. */
  88815. _this._index = null;
  88816. _this._absoluteTransform = new BABYLON.Matrix();
  88817. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  88818. _this._scalingDeterminant = 1;
  88819. _this._worldTransform = new BABYLON.Matrix();
  88820. _this._needToDecompose = true;
  88821. _this._needToCompose = false;
  88822. _this._skeleton = skeleton;
  88823. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  88824. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  88825. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  88826. _this._index = index;
  88827. skeleton.bones.push(_this);
  88828. _this.setParent(parentBone, false);
  88829. if (baseMatrix || localMatrix) {
  88830. _this._updateDifferenceMatrix();
  88831. }
  88832. return _this;
  88833. }
  88834. Object.defineProperty(Bone.prototype, "_matrix", {
  88835. /** @hidden */
  88836. get: function () {
  88837. this._compose();
  88838. return this._localMatrix;
  88839. },
  88840. /** @hidden */
  88841. set: function (value) {
  88842. this._localMatrix.copyFrom(value);
  88843. this._needToDecompose = true;
  88844. },
  88845. enumerable: true,
  88846. configurable: true
  88847. });
  88848. // Members
  88849. /**
  88850. * Gets the parent skeleton
  88851. * @returns a skeleton
  88852. */
  88853. Bone.prototype.getSkeleton = function () {
  88854. return this._skeleton;
  88855. };
  88856. /**
  88857. * Gets parent bone
  88858. * @returns a bone or null if the bone is the root of the bone hierarchy
  88859. */
  88860. Bone.prototype.getParent = function () {
  88861. return this._parent;
  88862. };
  88863. /**
  88864. * Sets the parent bone
  88865. * @param parent defines the parent (can be null if the bone is the root)
  88866. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88867. */
  88868. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  88869. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88870. if (this._parent === parent) {
  88871. return;
  88872. }
  88873. if (this._parent) {
  88874. var index = this._parent.children.indexOf(this);
  88875. if (index !== -1) {
  88876. this._parent.children.splice(index, 1);
  88877. }
  88878. }
  88879. this._parent = parent;
  88880. if (this._parent) {
  88881. this._parent.children.push(this);
  88882. }
  88883. if (updateDifferenceMatrix) {
  88884. this._updateDifferenceMatrix();
  88885. }
  88886. this.markAsDirty();
  88887. };
  88888. /**
  88889. * Gets the local matrix
  88890. * @returns a matrix
  88891. */
  88892. Bone.prototype.getLocalMatrix = function () {
  88893. this._compose();
  88894. return this._localMatrix;
  88895. };
  88896. /**
  88897. * Gets the base matrix (initial matrix which remains unchanged)
  88898. * @returns a matrix
  88899. */
  88900. Bone.prototype.getBaseMatrix = function () {
  88901. return this._baseMatrix;
  88902. };
  88903. /**
  88904. * Gets the rest pose matrix
  88905. * @returns a matrix
  88906. */
  88907. Bone.prototype.getRestPose = function () {
  88908. return this._restPose;
  88909. };
  88910. /**
  88911. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  88912. */
  88913. Bone.prototype.getWorldMatrix = function () {
  88914. return this._worldTransform;
  88915. };
  88916. /**
  88917. * Sets the local matrix to rest pose matrix
  88918. */
  88919. Bone.prototype.returnToRest = function () {
  88920. this.updateMatrix(this._restPose.clone());
  88921. };
  88922. /**
  88923. * Gets the inverse of the absolute transform matrix.
  88924. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  88925. * @returns a matrix
  88926. */
  88927. Bone.prototype.getInvertedAbsoluteTransform = function () {
  88928. return this._invertedAbsoluteTransform;
  88929. };
  88930. /**
  88931. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  88932. * @returns a matrix
  88933. */
  88934. Bone.prototype.getAbsoluteTransform = function () {
  88935. return this._absoluteTransform;
  88936. };
  88937. Object.defineProperty(Bone.prototype, "position", {
  88938. // Properties (matches AbstractMesh properties)
  88939. /** Gets or sets current position (in local space) */
  88940. get: function () {
  88941. this._decompose();
  88942. return this._localPosition;
  88943. },
  88944. set: function (newPosition) {
  88945. this._decompose();
  88946. this._localPosition.copyFrom(newPosition);
  88947. this._markAsDirtyAndCompose();
  88948. },
  88949. enumerable: true,
  88950. configurable: true
  88951. });
  88952. Object.defineProperty(Bone.prototype, "rotation", {
  88953. /** Gets or sets current rotation (in local space) */
  88954. get: function () {
  88955. return this.getRotation();
  88956. },
  88957. set: function (newRotation) {
  88958. this.setRotation(newRotation);
  88959. },
  88960. enumerable: true,
  88961. configurable: true
  88962. });
  88963. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  88964. /** Gets or sets current rotation quaternion (in local space) */
  88965. get: function () {
  88966. this._decompose();
  88967. return this._localRotation;
  88968. },
  88969. set: function (newRotation) {
  88970. this.setRotationQuaternion(newRotation);
  88971. },
  88972. enumerable: true,
  88973. configurable: true
  88974. });
  88975. Object.defineProperty(Bone.prototype, "scaling", {
  88976. /** Gets or sets current scaling (in local space) */
  88977. get: function () {
  88978. return this.getScale();
  88979. },
  88980. set: function (newScaling) {
  88981. this.setScale(newScaling);
  88982. },
  88983. enumerable: true,
  88984. configurable: true
  88985. });
  88986. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  88987. /**
  88988. * Gets the animation properties override
  88989. */
  88990. get: function () {
  88991. return this._skeleton.animationPropertiesOverride;
  88992. },
  88993. enumerable: true,
  88994. configurable: true
  88995. });
  88996. // Methods
  88997. Bone.prototype._decompose = function () {
  88998. if (!this._needToDecompose) {
  88999. return;
  89000. }
  89001. this._needToDecompose = false;
  89002. if (!this._localScaling) {
  89003. this._localScaling = BABYLON.Vector3.Zero();
  89004. this._localRotation = BABYLON.Quaternion.Zero();
  89005. this._localPosition = BABYLON.Vector3.Zero();
  89006. }
  89007. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  89008. };
  89009. Bone.prototype._compose = function () {
  89010. if (!this._needToCompose) {
  89011. return;
  89012. }
  89013. this._needToCompose = false;
  89014. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  89015. };
  89016. /**
  89017. * Update the base and local matrices
  89018. * @param matrix defines the new base or local matrix
  89019. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  89020. * @param updateLocalMatrix defines if the local matrix should be updated
  89021. */
  89022. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  89023. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  89024. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  89025. this._baseMatrix.copyFrom(matrix);
  89026. if (updateDifferenceMatrix) {
  89027. this._updateDifferenceMatrix();
  89028. }
  89029. if (updateLocalMatrix) {
  89030. this._localMatrix.copyFrom(matrix);
  89031. this._markAsDirtyAndDecompose();
  89032. }
  89033. else {
  89034. this.markAsDirty();
  89035. }
  89036. };
  89037. /** @hidden */
  89038. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  89039. if (updateChildren === void 0) { updateChildren = true; }
  89040. if (!rootMatrix) {
  89041. rootMatrix = this._baseMatrix;
  89042. }
  89043. if (this._parent) {
  89044. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  89045. }
  89046. else {
  89047. this._absoluteTransform.copyFrom(rootMatrix);
  89048. }
  89049. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  89050. if (updateChildren) {
  89051. for (var index = 0; index < this.children.length; index++) {
  89052. this.children[index]._updateDifferenceMatrix();
  89053. }
  89054. }
  89055. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  89056. };
  89057. /**
  89058. * Flag the bone as dirty (Forcing it to update everything)
  89059. */
  89060. Bone.prototype.markAsDirty = function () {
  89061. this._currentRenderId++;
  89062. this._childRenderId++;
  89063. this._skeleton._markAsDirty();
  89064. };
  89065. Bone.prototype._markAsDirtyAndCompose = function () {
  89066. this.markAsDirty();
  89067. this._needToCompose = true;
  89068. };
  89069. Bone.prototype._markAsDirtyAndDecompose = function () {
  89070. this.markAsDirty();
  89071. this._needToDecompose = true;
  89072. };
  89073. /**
  89074. * Copy an animation range from another bone
  89075. * @param source defines the source bone
  89076. * @param rangeName defines the range name to copy
  89077. * @param frameOffset defines the frame offset
  89078. * @param rescaleAsRequired defines if rescaling must be applied if required
  89079. * @param skelDimensionsRatio defines the scaling ratio
  89080. * @returns true if operation was successful
  89081. */
  89082. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  89083. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  89084. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  89085. // all animation may be coming from a library skeleton, so may need to create animation
  89086. if (this.animations.length === 0) {
  89087. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  89088. this.animations[0].setKeys([]);
  89089. }
  89090. // get animation info / verify there is such a range from the source bone
  89091. var sourceRange = source.animations[0].getRange(rangeName);
  89092. if (!sourceRange) {
  89093. return false;
  89094. }
  89095. var from = sourceRange.from;
  89096. var to = sourceRange.to;
  89097. var sourceKeys = source.animations[0].getKeys();
  89098. // rescaling prep
  89099. var sourceBoneLength = source.length;
  89100. var sourceParent = source.getParent();
  89101. var parent = this.getParent();
  89102. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  89103. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  89104. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  89105. var destKeys = this.animations[0].getKeys();
  89106. // loop vars declaration
  89107. var orig;
  89108. var origTranslation;
  89109. var mat;
  89110. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  89111. orig = sourceKeys[key];
  89112. if (orig.frame >= from && orig.frame <= to) {
  89113. if (rescaleAsRequired) {
  89114. mat = orig.value.clone();
  89115. // scale based on parent ratio, when bone has parent
  89116. if (parentScalingReqd) {
  89117. origTranslation = mat.getTranslation();
  89118. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  89119. // scale based on skeleton dimension ratio when root bone, and value is passed
  89120. }
  89121. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  89122. origTranslation = mat.getTranslation();
  89123. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  89124. // use original when root bone, and no data for skelDimensionsRatio
  89125. }
  89126. else {
  89127. mat = orig.value;
  89128. }
  89129. }
  89130. else {
  89131. mat = orig.value;
  89132. }
  89133. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  89134. }
  89135. }
  89136. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  89137. return true;
  89138. };
  89139. /**
  89140. * Translate the bone in local or world space
  89141. * @param vec The amount to translate the bone
  89142. * @param space The space that the translation is in
  89143. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89144. */
  89145. Bone.prototype.translate = function (vec, space, mesh) {
  89146. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89147. var lm = this.getLocalMatrix();
  89148. if (space == BABYLON.Space.LOCAL) {
  89149. lm.m[12] += vec.x;
  89150. lm.m[13] += vec.y;
  89151. lm.m[14] += vec.z;
  89152. }
  89153. else {
  89154. var wm = null;
  89155. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89156. if (mesh) {
  89157. wm = mesh.getWorldMatrix();
  89158. }
  89159. this._skeleton.computeAbsoluteTransforms();
  89160. var tmat = Bone._tmpMats[0];
  89161. var tvec = Bone._tmpVecs[0];
  89162. if (this._parent) {
  89163. if (mesh && wm) {
  89164. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89165. tmat.multiplyToRef(wm, tmat);
  89166. }
  89167. else {
  89168. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89169. }
  89170. }
  89171. tmat.m[12] = 0;
  89172. tmat.m[13] = 0;
  89173. tmat.m[14] = 0;
  89174. tmat.invert();
  89175. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  89176. lm.m[12] += tvec.x;
  89177. lm.m[13] += tvec.y;
  89178. lm.m[14] += tvec.z;
  89179. }
  89180. this._markAsDirtyAndDecompose();
  89181. };
  89182. /**
  89183. * Set the postion of the bone in local or world space
  89184. * @param position The position to set the bone
  89185. * @param space The space that the position is in
  89186. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89187. */
  89188. Bone.prototype.setPosition = function (position, space, mesh) {
  89189. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89190. var lm = this.getLocalMatrix();
  89191. if (space == BABYLON.Space.LOCAL) {
  89192. lm.m[12] = position.x;
  89193. lm.m[13] = position.y;
  89194. lm.m[14] = position.z;
  89195. }
  89196. else {
  89197. var wm = null;
  89198. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89199. if (mesh) {
  89200. wm = mesh.getWorldMatrix();
  89201. }
  89202. this._skeleton.computeAbsoluteTransforms();
  89203. var tmat = Bone._tmpMats[0];
  89204. var vec = Bone._tmpVecs[0];
  89205. if (this._parent) {
  89206. if (mesh && wm) {
  89207. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89208. tmat.multiplyToRef(wm, tmat);
  89209. }
  89210. else {
  89211. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89212. }
  89213. }
  89214. tmat.invert();
  89215. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  89216. lm.m[12] = vec.x;
  89217. lm.m[13] = vec.y;
  89218. lm.m[14] = vec.z;
  89219. }
  89220. this._markAsDirtyAndDecompose();
  89221. };
  89222. /**
  89223. * Set the absolute position of the bone (world space)
  89224. * @param position The position to set the bone
  89225. * @param mesh The mesh that this bone is attached to
  89226. */
  89227. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  89228. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  89229. };
  89230. /**
  89231. * Scale the bone on the x, y and z axes (in local space)
  89232. * @param x The amount to scale the bone on the x axis
  89233. * @param y The amount to scale the bone on the y axis
  89234. * @param z The amount to scale the bone on the z axis
  89235. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  89236. */
  89237. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  89238. if (scaleChildren === void 0) { scaleChildren = false; }
  89239. var locMat = this.getLocalMatrix();
  89240. // Apply new scaling on top of current local matrix
  89241. var scaleMat = Bone._tmpMats[0];
  89242. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  89243. scaleMat.multiplyToRef(locMat, locMat);
  89244. // Invert scaling matrix and apply the inverse to all children
  89245. scaleMat.invert();
  89246. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  89247. var child = _a[_i];
  89248. var cm = child.getLocalMatrix();
  89249. cm.multiplyToRef(scaleMat, cm);
  89250. cm.m[12] *= x;
  89251. cm.m[13] *= y;
  89252. cm.m[14] *= z;
  89253. child._markAsDirtyAndDecompose();
  89254. }
  89255. this._markAsDirtyAndDecompose();
  89256. if (scaleChildren) {
  89257. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  89258. var child = _c[_b];
  89259. child.scale(x, y, z, scaleChildren);
  89260. }
  89261. }
  89262. };
  89263. /**
  89264. * Set the bone scaling in local space
  89265. * @param scale defines the scaling vector
  89266. */
  89267. Bone.prototype.setScale = function (scale) {
  89268. this._decompose();
  89269. this._localScaling.copyFrom(scale);
  89270. this._markAsDirtyAndCompose();
  89271. };
  89272. /**
  89273. * Gets the current scaling in local space
  89274. * @returns the current scaling vector
  89275. */
  89276. Bone.prototype.getScale = function () {
  89277. this._decompose();
  89278. return this._localScaling;
  89279. };
  89280. /**
  89281. * Gets the current scaling in local space and stores it in a target vector
  89282. * @param result defines the target vector
  89283. */
  89284. Bone.prototype.getScaleToRef = function (result) {
  89285. this._decompose();
  89286. result.copyFrom(this._localScaling);
  89287. };
  89288. /**
  89289. * Set the yaw, pitch, and roll of the bone in local or world space
  89290. * @param yaw The rotation of the bone on the y axis
  89291. * @param pitch The rotation of the bone on the x axis
  89292. * @param roll The rotation of the bone on the z axis
  89293. * @param space The space that the axes of rotation are in
  89294. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89295. */
  89296. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  89297. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89298. if (space === BABYLON.Space.LOCAL) {
  89299. var quat = Bone._tmpQuat;
  89300. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  89301. this.setRotationQuaternion(quat, space, mesh);
  89302. return;
  89303. }
  89304. var rotMatInv = Bone._tmpMats[0];
  89305. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89306. return;
  89307. }
  89308. var rotMat = Bone._tmpMats[1];
  89309. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  89310. rotMatInv.multiplyToRef(rotMat, rotMat);
  89311. this._rotateWithMatrix(rotMat, space, mesh);
  89312. };
  89313. /**
  89314. * Add a rotation to the bone on an axis in local or world space
  89315. * @param axis The axis to rotate the bone on
  89316. * @param amount The amount to rotate the bone
  89317. * @param space The space that the axis is in
  89318. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89319. */
  89320. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  89321. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89322. var rmat = Bone._tmpMats[0];
  89323. rmat.m[12] = 0;
  89324. rmat.m[13] = 0;
  89325. rmat.m[14] = 0;
  89326. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  89327. this._rotateWithMatrix(rmat, space, mesh);
  89328. };
  89329. /**
  89330. * Set the rotation of the bone to a particular axis angle in local or world space
  89331. * @param axis The axis to rotate the bone on
  89332. * @param angle The angle that the bone should be rotated to
  89333. * @param space The space that the axis is in
  89334. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89335. */
  89336. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  89337. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89338. if (space === BABYLON.Space.LOCAL) {
  89339. var quat = Bone._tmpQuat;
  89340. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  89341. this.setRotationQuaternion(quat, space, mesh);
  89342. return;
  89343. }
  89344. var rotMatInv = Bone._tmpMats[0];
  89345. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89346. return;
  89347. }
  89348. var rotMat = Bone._tmpMats[1];
  89349. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  89350. rotMatInv.multiplyToRef(rotMat, rotMat);
  89351. this._rotateWithMatrix(rotMat, space, mesh);
  89352. };
  89353. /**
  89354. * Set the euler rotation of the bone in local of world space
  89355. * @param rotation The euler rotation that the bone should be set to
  89356. * @param space The space that the rotation is in
  89357. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89358. */
  89359. Bone.prototype.setRotation = function (rotation, space, mesh) {
  89360. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89361. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  89362. };
  89363. /**
  89364. * Set the quaternion rotation of the bone in local of world space
  89365. * @param quat The quaternion rotation that the bone should be set to
  89366. * @param space The space that the rotation is in
  89367. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89368. */
  89369. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  89370. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89371. if (space === BABYLON.Space.LOCAL) {
  89372. this._decompose();
  89373. this._localRotation.copyFrom(quat);
  89374. this._markAsDirtyAndCompose();
  89375. return;
  89376. }
  89377. var rotMatInv = Bone._tmpMats[0];
  89378. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89379. return;
  89380. }
  89381. var rotMat = Bone._tmpMats[1];
  89382. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  89383. rotMatInv.multiplyToRef(rotMat, rotMat);
  89384. this._rotateWithMatrix(rotMat, space, mesh);
  89385. };
  89386. /**
  89387. * Set the rotation matrix of the bone in local of world space
  89388. * @param rotMat The rotation matrix that the bone should be set to
  89389. * @param space The space that the rotation is in
  89390. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89391. */
  89392. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  89393. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89394. if (space === BABYLON.Space.LOCAL) {
  89395. var quat = Bone._tmpQuat;
  89396. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  89397. this.setRotationQuaternion(quat, space, mesh);
  89398. return;
  89399. }
  89400. var rotMatInv = Bone._tmpMats[0];
  89401. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89402. return;
  89403. }
  89404. var rotMat2 = Bone._tmpMats[1];
  89405. rotMat2.copyFrom(rotMat);
  89406. rotMatInv.multiplyToRef(rotMat, rotMat2);
  89407. this._rotateWithMatrix(rotMat2, space, mesh);
  89408. };
  89409. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  89410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89411. var lmat = this.getLocalMatrix();
  89412. var lx = lmat.m[12];
  89413. var ly = lmat.m[13];
  89414. var lz = lmat.m[14];
  89415. var parent = this.getParent();
  89416. var parentScale = Bone._tmpMats[3];
  89417. var parentScaleInv = Bone._tmpMats[4];
  89418. if (parent && space == BABYLON.Space.WORLD) {
  89419. if (mesh) {
  89420. parentScale.copyFrom(mesh.getWorldMatrix());
  89421. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  89422. }
  89423. else {
  89424. parentScale.copyFrom(parent.getAbsoluteTransform());
  89425. }
  89426. parentScaleInv.copyFrom(parentScale);
  89427. parentScaleInv.invert();
  89428. lmat.multiplyToRef(parentScale, lmat);
  89429. lmat.multiplyToRef(rmat, lmat);
  89430. lmat.multiplyToRef(parentScaleInv, lmat);
  89431. }
  89432. else {
  89433. if (space == BABYLON.Space.WORLD && mesh) {
  89434. parentScale.copyFrom(mesh.getWorldMatrix());
  89435. parentScaleInv.copyFrom(parentScale);
  89436. parentScaleInv.invert();
  89437. lmat.multiplyToRef(parentScale, lmat);
  89438. lmat.multiplyToRef(rmat, lmat);
  89439. lmat.multiplyToRef(parentScaleInv, lmat);
  89440. }
  89441. else {
  89442. lmat.multiplyToRef(rmat, lmat);
  89443. }
  89444. }
  89445. lmat.m[12] = lx;
  89446. lmat.m[13] = ly;
  89447. lmat.m[14] = lz;
  89448. this.computeAbsoluteTransforms();
  89449. this._markAsDirtyAndDecompose();
  89450. };
  89451. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  89452. var scaleMatrix = Bone._tmpMats[2];
  89453. rotMatInv.copyFrom(this.getAbsoluteTransform());
  89454. if (mesh) {
  89455. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  89456. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  89457. }
  89458. rotMatInv.invert();
  89459. if (isNaN(rotMatInv.m[0])) {
  89460. // Matrix failed to invert.
  89461. // This can happen if scale is zero for example.
  89462. return false;
  89463. }
  89464. scaleMatrix.m[0] *= this._scalingDeterminant;
  89465. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  89466. return true;
  89467. };
  89468. /**
  89469. * Get the position of the bone in local or world space
  89470. * @param space The space that the returned position is in
  89471. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89472. * @returns The position of the bone
  89473. */
  89474. Bone.prototype.getPosition = function (space, mesh) {
  89475. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89476. if (mesh === void 0) { mesh = null; }
  89477. var pos = BABYLON.Vector3.Zero();
  89478. this.getPositionToRef(space, mesh, pos);
  89479. return pos;
  89480. };
  89481. /**
  89482. * Copy the position of the bone to a vector3 in local or world space
  89483. * @param space The space that the returned position is in
  89484. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89485. * @param result The vector3 to copy the position to
  89486. */
  89487. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  89488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89489. if (space == BABYLON.Space.LOCAL) {
  89490. var lm = this.getLocalMatrix();
  89491. result.x = lm.m[12];
  89492. result.y = lm.m[13];
  89493. result.z = lm.m[14];
  89494. }
  89495. else {
  89496. var wm = null;
  89497. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89498. if (mesh) {
  89499. wm = mesh.getWorldMatrix();
  89500. }
  89501. this._skeleton.computeAbsoluteTransforms();
  89502. var tmat = Bone._tmpMats[0];
  89503. if (mesh && wm) {
  89504. tmat.copyFrom(this.getAbsoluteTransform());
  89505. tmat.multiplyToRef(wm, tmat);
  89506. }
  89507. else {
  89508. tmat = this.getAbsoluteTransform();
  89509. }
  89510. result.x = tmat.m[12];
  89511. result.y = tmat.m[13];
  89512. result.z = tmat.m[14];
  89513. }
  89514. };
  89515. /**
  89516. * Get the absolute position of the bone (world space)
  89517. * @param mesh The mesh that this bone is attached to
  89518. * @returns The absolute position of the bone
  89519. */
  89520. Bone.prototype.getAbsolutePosition = function (mesh) {
  89521. if (mesh === void 0) { mesh = null; }
  89522. var pos = BABYLON.Vector3.Zero();
  89523. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  89524. return pos;
  89525. };
  89526. /**
  89527. * Copy the absolute position of the bone (world space) to the result param
  89528. * @param mesh The mesh that this bone is attached to
  89529. * @param result The vector3 to copy the absolute position to
  89530. */
  89531. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  89532. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  89533. };
  89534. /**
  89535. * Compute the absolute transforms of this bone and its children
  89536. */
  89537. Bone.prototype.computeAbsoluteTransforms = function () {
  89538. this._compose();
  89539. if (this._parent) {
  89540. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  89541. }
  89542. else {
  89543. this._absoluteTransform.copyFrom(this._localMatrix);
  89544. var poseMatrix = this._skeleton.getPoseMatrix();
  89545. if (poseMatrix) {
  89546. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  89547. }
  89548. }
  89549. var children = this.children;
  89550. var len = children.length;
  89551. for (var i = 0; i < len; i++) {
  89552. children[i].computeAbsoluteTransforms();
  89553. }
  89554. };
  89555. /**
  89556. * Get the world direction from an axis that is in the local space of the bone
  89557. * @param localAxis The local direction that is used to compute the world direction
  89558. * @param mesh The mesh that this bone is attached to
  89559. * @returns The world direction
  89560. */
  89561. Bone.prototype.getDirection = function (localAxis, mesh) {
  89562. if (mesh === void 0) { mesh = null; }
  89563. var result = BABYLON.Vector3.Zero();
  89564. this.getDirectionToRef(localAxis, mesh, result);
  89565. return result;
  89566. };
  89567. /**
  89568. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  89569. * @param localAxis The local direction that is used to compute the world direction
  89570. * @param mesh The mesh that this bone is attached to
  89571. * @param result The vector3 that the world direction will be copied to
  89572. */
  89573. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  89574. if (mesh === void 0) { mesh = null; }
  89575. var wm = null;
  89576. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89577. if (mesh) {
  89578. wm = mesh.getWorldMatrix();
  89579. }
  89580. this._skeleton.computeAbsoluteTransforms();
  89581. var mat = Bone._tmpMats[0];
  89582. mat.copyFrom(this.getAbsoluteTransform());
  89583. if (mesh && wm) {
  89584. mat.multiplyToRef(wm, mat);
  89585. }
  89586. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  89587. result.normalize();
  89588. };
  89589. /**
  89590. * Get the euler rotation of the bone in local or world space
  89591. * @param space The space that the rotation should be in
  89592. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89593. * @returns The euler rotation
  89594. */
  89595. Bone.prototype.getRotation = function (space, mesh) {
  89596. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89597. if (mesh === void 0) { mesh = null; }
  89598. var result = BABYLON.Vector3.Zero();
  89599. this.getRotationToRef(space, mesh, result);
  89600. return result;
  89601. };
  89602. /**
  89603. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  89604. * @param space The space that the rotation should be in
  89605. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89606. * @param result The vector3 that the rotation should be copied to
  89607. */
  89608. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  89609. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89610. if (mesh === void 0) { mesh = null; }
  89611. var quat = Bone._tmpQuat;
  89612. this.getRotationQuaternionToRef(space, mesh, quat);
  89613. quat.toEulerAnglesToRef(result);
  89614. };
  89615. /**
  89616. * Get the quaternion rotation of the bone in either local or world space
  89617. * @param space The space that the rotation should be in
  89618. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89619. * @returns The quaternion rotation
  89620. */
  89621. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  89622. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89623. if (mesh === void 0) { mesh = null; }
  89624. var result = BABYLON.Quaternion.Identity();
  89625. this.getRotationQuaternionToRef(space, mesh, result);
  89626. return result;
  89627. };
  89628. /**
  89629. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  89630. * @param space The space that the rotation should be in
  89631. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89632. * @param result The quaternion that the rotation should be copied to
  89633. */
  89634. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  89635. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89636. if (mesh === void 0) { mesh = null; }
  89637. if (space == BABYLON.Space.LOCAL) {
  89638. this._decompose();
  89639. result.copyFrom(this._localRotation);
  89640. }
  89641. else {
  89642. var mat = Bone._tmpMats[0];
  89643. var amat = this.getAbsoluteTransform();
  89644. if (mesh) {
  89645. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  89646. }
  89647. else {
  89648. mat.copyFrom(amat);
  89649. }
  89650. mat.m[0] *= this._scalingDeterminant;
  89651. mat.m[1] *= this._scalingDeterminant;
  89652. mat.m[2] *= this._scalingDeterminant;
  89653. mat.decompose(undefined, result, undefined);
  89654. }
  89655. };
  89656. /**
  89657. * Get the rotation matrix of the bone in local or world space
  89658. * @param space The space that the rotation should be in
  89659. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89660. * @returns The rotation matrix
  89661. */
  89662. Bone.prototype.getRotationMatrix = function (space, mesh) {
  89663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89664. var result = BABYLON.Matrix.Identity();
  89665. this.getRotationMatrixToRef(space, mesh, result);
  89666. return result;
  89667. };
  89668. /**
  89669. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  89670. * @param space The space that the rotation should be in
  89671. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89672. * @param result The quaternion that the rotation should be copied to
  89673. */
  89674. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  89675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89676. if (space == BABYLON.Space.LOCAL) {
  89677. this.getLocalMatrix().getRotationMatrixToRef(result);
  89678. }
  89679. else {
  89680. var mat = Bone._tmpMats[0];
  89681. var amat = this.getAbsoluteTransform();
  89682. if (mesh) {
  89683. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  89684. }
  89685. else {
  89686. mat.copyFrom(amat);
  89687. }
  89688. mat.m[0] *= this._scalingDeterminant;
  89689. mat.m[1] *= this._scalingDeterminant;
  89690. mat.m[2] *= this._scalingDeterminant;
  89691. mat.getRotationMatrixToRef(result);
  89692. }
  89693. };
  89694. /**
  89695. * Get the world position of a point that is in the local space of the bone
  89696. * @param position The local position
  89697. * @param mesh The mesh that this bone is attached to
  89698. * @returns The world position
  89699. */
  89700. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  89701. if (mesh === void 0) { mesh = null; }
  89702. var result = BABYLON.Vector3.Zero();
  89703. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  89704. return result;
  89705. };
  89706. /**
  89707. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  89708. * @param position The local position
  89709. * @param mesh The mesh that this bone is attached to
  89710. * @param result The vector3 that the world position should be copied to
  89711. */
  89712. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  89713. if (mesh === void 0) { mesh = null; }
  89714. var wm = null;
  89715. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89716. if (mesh) {
  89717. wm = mesh.getWorldMatrix();
  89718. }
  89719. this._skeleton.computeAbsoluteTransforms();
  89720. var tmat = Bone._tmpMats[0];
  89721. if (mesh && wm) {
  89722. tmat.copyFrom(this.getAbsoluteTransform());
  89723. tmat.multiplyToRef(wm, tmat);
  89724. }
  89725. else {
  89726. tmat = this.getAbsoluteTransform();
  89727. }
  89728. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89729. };
  89730. /**
  89731. * Get the local position of a point that is in world space
  89732. * @param position The world position
  89733. * @param mesh The mesh that this bone is attached to
  89734. * @returns The local position
  89735. */
  89736. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  89737. if (mesh === void 0) { mesh = null; }
  89738. var result = BABYLON.Vector3.Zero();
  89739. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  89740. return result;
  89741. };
  89742. /**
  89743. * Get the local position of a point that is in world space and copy it to the result param
  89744. * @param position The world position
  89745. * @param mesh The mesh that this bone is attached to
  89746. * @param result The vector3 that the local position should be copied to
  89747. */
  89748. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  89749. if (mesh === void 0) { mesh = null; }
  89750. var wm = null;
  89751. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89752. if (mesh) {
  89753. wm = mesh.getWorldMatrix();
  89754. }
  89755. this._skeleton.computeAbsoluteTransforms();
  89756. var tmat = Bone._tmpMats[0];
  89757. tmat.copyFrom(this.getAbsoluteTransform());
  89758. if (mesh && wm) {
  89759. tmat.multiplyToRef(wm, tmat);
  89760. }
  89761. tmat.invert();
  89762. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89763. };
  89764. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89765. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  89766. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89767. return Bone;
  89768. }(BABYLON.Node));
  89769. BABYLON.Bone = Bone;
  89770. })(BABYLON || (BABYLON = {}));
  89771. //# sourceMappingURL=babylon.bone.js.map
  89772. var BABYLON;
  89773. (function (BABYLON) {
  89774. /**
  89775. * Class used to apply inverse kinematics to bones
  89776. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  89777. */
  89778. var BoneIKController = /** @class */ (function () {
  89779. /**
  89780. * Creates a new BoneIKController
  89781. * @param mesh defines the mesh to control
  89782. * @param bone defines the bone to control
  89783. * @param options defines options to set up the controller
  89784. */
  89785. function BoneIKController(mesh, bone, options) {
  89786. /**
  89787. * Gets or sets the target position
  89788. */
  89789. this.targetPosition = BABYLON.Vector3.Zero();
  89790. /**
  89791. * Gets or sets the pole target position
  89792. */
  89793. this.poleTargetPosition = BABYLON.Vector3.Zero();
  89794. /**
  89795. * Gets or sets the pole target local offset
  89796. */
  89797. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  89798. /**
  89799. * Gets or sets the pole angle
  89800. */
  89801. this.poleAngle = 0;
  89802. /**
  89803. * 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)
  89804. */
  89805. this.slerpAmount = 1;
  89806. this._bone1Quat = BABYLON.Quaternion.Identity();
  89807. this._bone1Mat = BABYLON.Matrix.Identity();
  89808. this._bone2Ang = Math.PI;
  89809. this._maxAngle = Math.PI;
  89810. this._rightHandedSystem = false;
  89811. this._bendAxis = BABYLON.Vector3.Right();
  89812. this._slerping = false;
  89813. this._adjustRoll = 0;
  89814. this._bone2 = bone;
  89815. this._bone1 = bone.getParent();
  89816. if (!this._bone1) {
  89817. return;
  89818. }
  89819. this.mesh = mesh;
  89820. var bonePos = bone.getPosition();
  89821. if (bone.getAbsoluteTransform().determinant() > 0) {
  89822. this._rightHandedSystem = true;
  89823. this._bendAxis.x = 0;
  89824. this._bendAxis.y = 0;
  89825. this._bendAxis.z = -1;
  89826. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  89827. this._adjustRoll = Math.PI * .5;
  89828. this._bendAxis.z = 1;
  89829. }
  89830. }
  89831. if (this._bone1.length) {
  89832. var boneScale1 = this._bone1.getScale();
  89833. var boneScale2 = this._bone2.getScale();
  89834. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  89835. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  89836. }
  89837. else if (this._bone1.children[0]) {
  89838. mesh.computeWorldMatrix(true);
  89839. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  89840. var pos2 = this._bone2.getAbsolutePosition(mesh);
  89841. var pos3 = this._bone1.getAbsolutePosition(mesh);
  89842. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  89843. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  89844. }
  89845. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  89846. this.maxAngle = Math.PI;
  89847. if (options) {
  89848. if (options.targetMesh) {
  89849. this.targetMesh = options.targetMesh;
  89850. this.targetMesh.computeWorldMatrix(true);
  89851. }
  89852. if (options.poleTargetMesh) {
  89853. this.poleTargetMesh = options.poleTargetMesh;
  89854. this.poleTargetMesh.computeWorldMatrix(true);
  89855. }
  89856. else if (options.poleTargetBone) {
  89857. this.poleTargetBone = options.poleTargetBone;
  89858. }
  89859. else if (this._bone1.getParent()) {
  89860. this.poleTargetBone = this._bone1.getParent();
  89861. }
  89862. if (options.poleTargetLocalOffset) {
  89863. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  89864. }
  89865. if (options.poleAngle) {
  89866. this.poleAngle = options.poleAngle;
  89867. }
  89868. if (options.bendAxis) {
  89869. this._bendAxis.copyFrom(options.bendAxis);
  89870. }
  89871. if (options.maxAngle) {
  89872. this.maxAngle = options.maxAngle;
  89873. }
  89874. if (options.slerpAmount) {
  89875. this.slerpAmount = options.slerpAmount;
  89876. }
  89877. }
  89878. }
  89879. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  89880. /**
  89881. * Gets or sets maximum allowed angle
  89882. */
  89883. get: function () {
  89884. return this._maxAngle;
  89885. },
  89886. set: function (value) {
  89887. this._setMaxAngle(value);
  89888. },
  89889. enumerable: true,
  89890. configurable: true
  89891. });
  89892. BoneIKController.prototype._setMaxAngle = function (ang) {
  89893. if (ang < 0) {
  89894. ang = 0;
  89895. }
  89896. if (ang > Math.PI || ang == undefined) {
  89897. ang = Math.PI;
  89898. }
  89899. this._maxAngle = ang;
  89900. var a = this._bone1Length;
  89901. var b = this._bone2Length;
  89902. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  89903. };
  89904. /**
  89905. * Force the controller to update the bones
  89906. */
  89907. BoneIKController.prototype.update = function () {
  89908. var bone1 = this._bone1;
  89909. if (!bone1) {
  89910. return;
  89911. }
  89912. var target = this.targetPosition;
  89913. var poleTarget = this.poleTargetPosition;
  89914. var mat1 = BoneIKController._tmpMats[0];
  89915. var mat2 = BoneIKController._tmpMats[1];
  89916. if (this.targetMesh) {
  89917. target.copyFrom(this.targetMesh.getAbsolutePosition());
  89918. }
  89919. if (this.poleTargetBone) {
  89920. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  89921. }
  89922. else if (this.poleTargetMesh) {
  89923. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  89924. }
  89925. var bonePos = BoneIKController._tmpVecs[0];
  89926. var zaxis = BoneIKController._tmpVecs[1];
  89927. var xaxis = BoneIKController._tmpVecs[2];
  89928. var yaxis = BoneIKController._tmpVecs[3];
  89929. var upAxis = BoneIKController._tmpVecs[4];
  89930. var _tmpQuat = BoneIKController._tmpQuat;
  89931. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  89932. poleTarget.subtractToRef(bonePos, upAxis);
  89933. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  89934. upAxis.y = 1;
  89935. }
  89936. else {
  89937. upAxis.normalize();
  89938. }
  89939. target.subtractToRef(bonePos, yaxis);
  89940. yaxis.normalize();
  89941. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  89942. zaxis.normalize();
  89943. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  89944. xaxis.normalize();
  89945. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  89946. var a = this._bone1Length;
  89947. var b = this._bone2Length;
  89948. var c = BABYLON.Vector3.Distance(bonePos, target);
  89949. if (this._maxReach > 0) {
  89950. c = Math.min(this._maxReach, c);
  89951. }
  89952. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  89953. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  89954. if (acosa > 1) {
  89955. acosa = 1;
  89956. }
  89957. if (acosb > 1) {
  89958. acosb = 1;
  89959. }
  89960. if (acosa < -1) {
  89961. acosa = -1;
  89962. }
  89963. if (acosb < -1) {
  89964. acosb = -1;
  89965. }
  89966. var angA = Math.acos(acosa);
  89967. var angB = Math.acos(acosb);
  89968. var angC = -angA - angB;
  89969. if (this._rightHandedSystem) {
  89970. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  89971. mat2.multiplyToRef(mat1, mat1);
  89972. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  89973. mat2.multiplyToRef(mat1, mat1);
  89974. }
  89975. else {
  89976. var _tmpVec = BoneIKController._tmpVecs[5];
  89977. _tmpVec.copyFrom(this._bendAxis);
  89978. _tmpVec.x *= -1;
  89979. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  89980. mat2.multiplyToRef(mat1, mat1);
  89981. }
  89982. if (this.poleAngle) {
  89983. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  89984. mat1.multiplyToRef(mat2, mat1);
  89985. }
  89986. if (this._bone1) {
  89987. if (this.slerpAmount < 1) {
  89988. if (!this._slerping) {
  89989. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  89990. }
  89991. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  89992. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  89993. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  89994. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  89995. this._slerping = true;
  89996. }
  89997. else {
  89998. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  89999. this._bone1Mat.copyFrom(mat1);
  90000. this._slerping = false;
  90001. }
  90002. }
  90003. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  90004. this._bone2Ang = angC;
  90005. };
  90006. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90007. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  90008. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90009. return BoneIKController;
  90010. }());
  90011. BABYLON.BoneIKController = BoneIKController;
  90012. })(BABYLON || (BABYLON = {}));
  90013. //# sourceMappingURL=babylon.boneIKController.js.map
  90014. var BABYLON;
  90015. (function (BABYLON) {
  90016. /**
  90017. * Class used to make a bone look toward a point in space
  90018. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  90019. */
  90020. var BoneLookController = /** @class */ (function () {
  90021. /**
  90022. * Create a BoneLookController
  90023. * @param mesh the mesh that the bone belongs to
  90024. * @param bone the bone that will be looking to the target
  90025. * @param target the target Vector3 to look at
  90026. * @param settings optional settings:
  90027. * * maxYaw: the maximum angle the bone will yaw to
  90028. * * minYaw: the minimum angle the bone will yaw to
  90029. * * maxPitch: the maximum angle the bone will pitch to
  90030. * * minPitch: the minimum angle the bone will yaw to
  90031. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  90032. * * upAxis: the up axis of the coordinate system
  90033. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  90034. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  90035. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  90036. * * adjustYaw: used to make an adjustment to the yaw of the bone
  90037. * * adjustPitch: used to make an adjustment to the pitch of the bone
  90038. * * adjustRoll: used to make an adjustment to the roll of the bone
  90039. **/
  90040. function BoneLookController(mesh, bone, target, options) {
  90041. /**
  90042. * The up axis of the coordinate system that is used when the bone is rotated
  90043. */
  90044. this.upAxis = BABYLON.Vector3.Up();
  90045. /**
  90046. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  90047. */
  90048. this.upAxisSpace = BABYLON.Space.LOCAL;
  90049. /**
  90050. * Used to make an adjustment to the yaw of the bone
  90051. */
  90052. this.adjustYaw = 0;
  90053. /**
  90054. * Used to make an adjustment to the pitch of the bone
  90055. */
  90056. this.adjustPitch = 0;
  90057. /**
  90058. * Used to make an adjustment to the roll of the bone
  90059. */
  90060. this.adjustRoll = 0;
  90061. /**
  90062. * 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)
  90063. */
  90064. this.slerpAmount = 1;
  90065. this._boneQuat = BABYLON.Quaternion.Identity();
  90066. this._slerping = false;
  90067. this._firstFrameSkipped = false;
  90068. this._fowardAxis = BABYLON.Vector3.Forward();
  90069. this.mesh = mesh;
  90070. this.bone = bone;
  90071. this.target = target;
  90072. if (options) {
  90073. if (options.adjustYaw) {
  90074. this.adjustYaw = options.adjustYaw;
  90075. }
  90076. if (options.adjustPitch) {
  90077. this.adjustPitch = options.adjustPitch;
  90078. }
  90079. if (options.adjustRoll) {
  90080. this.adjustRoll = options.adjustRoll;
  90081. }
  90082. if (options.maxYaw != null) {
  90083. this.maxYaw = options.maxYaw;
  90084. }
  90085. else {
  90086. this.maxYaw = Math.PI;
  90087. }
  90088. if (options.minYaw != null) {
  90089. this.minYaw = options.minYaw;
  90090. }
  90091. else {
  90092. this.minYaw = -Math.PI;
  90093. }
  90094. if (options.maxPitch != null) {
  90095. this.maxPitch = options.maxPitch;
  90096. }
  90097. else {
  90098. this.maxPitch = Math.PI;
  90099. }
  90100. if (options.minPitch != null) {
  90101. this.minPitch = options.minPitch;
  90102. }
  90103. else {
  90104. this.minPitch = -Math.PI;
  90105. }
  90106. if (options.slerpAmount != null) {
  90107. this.slerpAmount = options.slerpAmount;
  90108. }
  90109. if (options.upAxis != null) {
  90110. this.upAxis = options.upAxis;
  90111. }
  90112. if (options.upAxisSpace != null) {
  90113. this.upAxisSpace = options.upAxisSpace;
  90114. }
  90115. if (options.yawAxis != null || options.pitchAxis != null) {
  90116. var newYawAxis = BABYLON.Axis.Y;
  90117. var newPitchAxis = BABYLON.Axis.X;
  90118. if (options.yawAxis != null) {
  90119. newYawAxis = options.yawAxis.clone();
  90120. newYawAxis.normalize();
  90121. }
  90122. if (options.pitchAxis != null) {
  90123. newPitchAxis = options.pitchAxis.clone();
  90124. newPitchAxis.normalize();
  90125. }
  90126. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  90127. this._transformYawPitch = BABYLON.Matrix.Identity();
  90128. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  90129. this._transformYawPitchInv = this._transformYawPitch.clone();
  90130. this._transformYawPitch.invert();
  90131. }
  90132. }
  90133. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  90134. this.upAxisSpace = BABYLON.Space.LOCAL;
  90135. }
  90136. }
  90137. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  90138. /**
  90139. * Gets or sets the minimum yaw angle that the bone can look to
  90140. */
  90141. get: function () {
  90142. return this._minYaw;
  90143. },
  90144. set: function (value) {
  90145. this._minYaw = value;
  90146. this._minYawSin = Math.sin(value);
  90147. this._minYawCos = Math.cos(value);
  90148. if (this._maxYaw != null) {
  90149. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  90150. this._yawRange = this._maxYaw - this._minYaw;
  90151. }
  90152. },
  90153. enumerable: true,
  90154. configurable: true
  90155. });
  90156. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  90157. /**
  90158. * Gets or sets the maximum yaw angle that the bone can look to
  90159. */
  90160. get: function () {
  90161. return this._maxYaw;
  90162. },
  90163. set: function (value) {
  90164. this._maxYaw = value;
  90165. this._maxYawSin = Math.sin(value);
  90166. this._maxYawCos = Math.cos(value);
  90167. if (this._minYaw != null) {
  90168. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  90169. this._yawRange = this._maxYaw - this._minYaw;
  90170. }
  90171. },
  90172. enumerable: true,
  90173. configurable: true
  90174. });
  90175. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  90176. /**
  90177. * Gets or sets the minimum pitch angle that the bone can look to
  90178. */
  90179. get: function () {
  90180. return this._minPitch;
  90181. },
  90182. set: function (value) {
  90183. this._minPitch = value;
  90184. this._minPitchTan = Math.tan(value);
  90185. },
  90186. enumerable: true,
  90187. configurable: true
  90188. });
  90189. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  90190. /**
  90191. * Gets or sets the maximum pitch angle that the bone can look to
  90192. */
  90193. get: function () {
  90194. return this._maxPitch;
  90195. },
  90196. set: function (value) {
  90197. this._maxPitch = value;
  90198. this._maxPitchTan = Math.tan(value);
  90199. },
  90200. enumerable: true,
  90201. configurable: true
  90202. });
  90203. /**
  90204. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  90205. */
  90206. BoneLookController.prototype.update = function () {
  90207. //skip the first frame when slerping so that the mesh rotation is correct
  90208. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  90209. this._firstFrameSkipped = true;
  90210. return;
  90211. }
  90212. var bone = this.bone;
  90213. var bonePos = BoneLookController._tmpVecs[0];
  90214. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  90215. var target = this.target;
  90216. var _tmpMat1 = BoneLookController._tmpMats[0];
  90217. var _tmpMat2 = BoneLookController._tmpMats[1];
  90218. var mesh = this.mesh;
  90219. var parentBone = bone.getParent();
  90220. var upAxis = BoneLookController._tmpVecs[1];
  90221. upAxis.copyFrom(this.upAxis);
  90222. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  90223. if (this._transformYawPitch) {
  90224. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  90225. }
  90226. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  90227. }
  90228. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  90229. mesh.getDirectionToRef(upAxis, upAxis);
  90230. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  90231. upAxis.normalize();
  90232. }
  90233. }
  90234. var checkYaw = false;
  90235. var checkPitch = false;
  90236. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  90237. checkYaw = true;
  90238. }
  90239. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  90240. checkPitch = true;
  90241. }
  90242. if (checkYaw || checkPitch) {
  90243. var spaceMat = BoneLookController._tmpMats[2];
  90244. var spaceMatInv = BoneLookController._tmpMats[3];
  90245. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  90246. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  90247. }
  90248. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  90249. spaceMat.copyFrom(mesh.getWorldMatrix());
  90250. }
  90251. else {
  90252. var forwardAxis = BoneLookController._tmpVecs[2];
  90253. forwardAxis.copyFrom(this._fowardAxis);
  90254. if (this._transformYawPitch) {
  90255. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  90256. }
  90257. if (parentBone) {
  90258. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  90259. }
  90260. else {
  90261. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  90262. }
  90263. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  90264. rightAxis.normalize();
  90265. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  90266. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  90267. }
  90268. spaceMat.invertToRef(spaceMatInv);
  90269. var xzlen = null;
  90270. if (checkPitch) {
  90271. var localTarget = BoneLookController._tmpVecs[3];
  90272. target.subtractToRef(bonePos, localTarget);
  90273. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  90274. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90275. var pitch = Math.atan2(localTarget.y, xzlen);
  90276. var newPitch = pitch;
  90277. if (pitch > this._maxPitch) {
  90278. localTarget.y = this._maxPitchTan * xzlen;
  90279. newPitch = this._maxPitch;
  90280. }
  90281. else if (pitch < this._minPitch) {
  90282. localTarget.y = this._minPitchTan * xzlen;
  90283. newPitch = this._minPitch;
  90284. }
  90285. if (pitch != newPitch) {
  90286. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  90287. localTarget.addInPlace(bonePos);
  90288. target = localTarget;
  90289. }
  90290. }
  90291. if (checkYaw) {
  90292. var localTarget = BoneLookController._tmpVecs[4];
  90293. target.subtractToRef(bonePos, localTarget);
  90294. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  90295. var yaw = Math.atan2(localTarget.x, localTarget.z);
  90296. var newYaw = yaw;
  90297. if (yaw > this._maxYaw || yaw < this._minYaw) {
  90298. if (xzlen == null) {
  90299. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90300. }
  90301. if (this._yawRange > Math.PI) {
  90302. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  90303. localTarget.z = this._maxYawCos * xzlen;
  90304. localTarget.x = this._maxYawSin * xzlen;
  90305. newYaw = this._maxYaw;
  90306. }
  90307. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  90308. localTarget.z = this._minYawCos * xzlen;
  90309. localTarget.x = this._minYawSin * xzlen;
  90310. newYaw = this._minYaw;
  90311. }
  90312. }
  90313. else {
  90314. if (yaw > this._maxYaw) {
  90315. localTarget.z = this._maxYawCos * xzlen;
  90316. localTarget.x = this._maxYawSin * xzlen;
  90317. newYaw = this._maxYaw;
  90318. }
  90319. else if (yaw < this._minYaw) {
  90320. localTarget.z = this._minYawCos * xzlen;
  90321. localTarget.x = this._minYawSin * xzlen;
  90322. newYaw = this._minYaw;
  90323. }
  90324. }
  90325. }
  90326. if (this._slerping && this._yawRange > Math.PI) {
  90327. //are we going to be crossing into the min/max region?
  90328. var boneFwd = BoneLookController._tmpVecs[8];
  90329. boneFwd.copyFrom(BABYLON.Axis.Z);
  90330. if (this._transformYawPitch) {
  90331. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  90332. }
  90333. var boneRotMat = BoneLookController._tmpMats[4];
  90334. this._boneQuat.toRotationMatrix(boneRotMat);
  90335. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  90336. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  90337. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  90338. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  90339. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  90340. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  90341. if (angBtwTar > angBtwMidYaw) {
  90342. if (xzlen == null) {
  90343. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90344. }
  90345. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  90346. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  90347. if (angBtwMin < angBtwMax) {
  90348. newYaw = boneYaw + Math.PI * .75;
  90349. localTarget.z = Math.cos(newYaw) * xzlen;
  90350. localTarget.x = Math.sin(newYaw) * xzlen;
  90351. }
  90352. else {
  90353. newYaw = boneYaw - Math.PI * .75;
  90354. localTarget.z = Math.cos(newYaw) * xzlen;
  90355. localTarget.x = Math.sin(newYaw) * xzlen;
  90356. }
  90357. }
  90358. }
  90359. if (yaw != newYaw) {
  90360. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  90361. localTarget.addInPlace(bonePos);
  90362. target = localTarget;
  90363. }
  90364. }
  90365. }
  90366. var zaxis = BoneLookController._tmpVecs[5];
  90367. var xaxis = BoneLookController._tmpVecs[6];
  90368. var yaxis = BoneLookController._tmpVecs[7];
  90369. var _tmpQuat = BoneLookController._tmpQuat;
  90370. target.subtractToRef(bonePos, zaxis);
  90371. zaxis.normalize();
  90372. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  90373. xaxis.normalize();
  90374. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  90375. yaxis.normalize();
  90376. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  90377. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  90378. return;
  90379. }
  90380. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  90381. return;
  90382. }
  90383. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  90384. return;
  90385. }
  90386. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  90387. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  90388. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  90389. }
  90390. if (this.slerpAmount < 1) {
  90391. if (!this._slerping) {
  90392. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  90393. }
  90394. if (this._transformYawPitch) {
  90395. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  90396. }
  90397. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  90398. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  90399. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  90400. this._slerping = true;
  90401. }
  90402. else {
  90403. if (this._transformYawPitch) {
  90404. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  90405. }
  90406. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  90407. this._slerping = false;
  90408. }
  90409. };
  90410. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  90411. var angDiff = ang2 - ang1;
  90412. angDiff %= Math.PI * 2;
  90413. if (angDiff > Math.PI) {
  90414. angDiff -= Math.PI * 2;
  90415. }
  90416. else if (angDiff < -Math.PI) {
  90417. angDiff += Math.PI * 2;
  90418. }
  90419. return angDiff;
  90420. };
  90421. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  90422. ang1 %= (2 * Math.PI);
  90423. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  90424. ang2 %= (2 * Math.PI);
  90425. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  90426. var ab = 0;
  90427. if (ang1 < ang2) {
  90428. ab = ang2 - ang1;
  90429. }
  90430. else {
  90431. ab = ang1 - ang2;
  90432. }
  90433. if (ab > Math.PI) {
  90434. ab = Math.PI * 2 - ab;
  90435. }
  90436. return ab;
  90437. };
  90438. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  90439. ang %= (2 * Math.PI);
  90440. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  90441. ang1 %= (2 * Math.PI);
  90442. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  90443. ang2 %= (2 * Math.PI);
  90444. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  90445. if (ang1 < ang2) {
  90446. if (ang > ang1 && ang < ang2) {
  90447. return true;
  90448. }
  90449. }
  90450. else {
  90451. if (ang > ang2 && ang < ang1) {
  90452. return true;
  90453. }
  90454. }
  90455. return false;
  90456. };
  90457. 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()];
  90458. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  90459. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90460. return BoneLookController;
  90461. }());
  90462. BABYLON.BoneLookController = BoneLookController;
  90463. })(BABYLON || (BABYLON = {}));
  90464. //# sourceMappingURL=babylon.boneLookController.js.map
  90465. var BABYLON;
  90466. (function (BABYLON) {
  90467. /**
  90468. * Class used to handle skinning animations
  90469. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  90470. */
  90471. var Skeleton = /** @class */ (function () {
  90472. /**
  90473. * Creates a new skeleton
  90474. * @param name defines the skeleton name
  90475. * @param id defines the skeleton Id
  90476. * @param scene defines the hosting scene
  90477. */
  90478. function Skeleton(
  90479. /** defines the skeleton name */
  90480. name,
  90481. /** defines the skeleton Id */
  90482. id, scene) {
  90483. this.name = name;
  90484. this.id = id;
  90485. /**
  90486. * Gets the list of child bones
  90487. */
  90488. this.bones = new Array();
  90489. /**
  90490. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  90491. */
  90492. this.needInitialSkinMatrix = false;
  90493. this._isDirty = true;
  90494. this._meshesWithPoseMatrix = new Array();
  90495. this._identity = BABYLON.Matrix.Identity();
  90496. this._ranges = {};
  90497. this._lastAbsoluteTransformsUpdateId = -1;
  90498. /**
  90499. * Specifies if the skeleton should be serialized
  90500. */
  90501. this.doNotSerialize = false;
  90502. this._animationPropertiesOverride = null;
  90503. // Events
  90504. /**
  90505. * An observable triggered before computing the skeleton's matrices
  90506. */
  90507. this.onBeforeComputeObservable = new BABYLON.Observable();
  90508. this.bones = [];
  90509. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90510. scene.skeletons.push(this);
  90511. //make sure it will recalculate the matrix next time prepare is called.
  90512. this._isDirty = true;
  90513. }
  90514. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  90515. /**
  90516. * Gets or sets the animation properties override
  90517. */
  90518. get: function () {
  90519. if (!this._animationPropertiesOverride) {
  90520. return this._scene.animationPropertiesOverride;
  90521. }
  90522. return this._animationPropertiesOverride;
  90523. },
  90524. set: function (value) {
  90525. this._animationPropertiesOverride = value;
  90526. },
  90527. enumerable: true,
  90528. configurable: true
  90529. });
  90530. // Members
  90531. /**
  90532. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  90533. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  90534. * @returns a Float32Array containing matrices data
  90535. */
  90536. Skeleton.prototype.getTransformMatrices = function (mesh) {
  90537. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  90538. return mesh._bonesTransformMatrices;
  90539. }
  90540. if (!this._transformMatrices) {
  90541. this.prepare();
  90542. }
  90543. return this._transformMatrices;
  90544. };
  90545. /**
  90546. * Gets the current hosting scene
  90547. * @returns a scene object
  90548. */
  90549. Skeleton.prototype.getScene = function () {
  90550. return this._scene;
  90551. };
  90552. // Methods
  90553. /**
  90554. * Gets a string representing the current skeleton data
  90555. * @param fullDetails defines a boolean indicating if we want a verbose version
  90556. * @returns a string representing the current skeleton data
  90557. */
  90558. Skeleton.prototype.toString = function (fullDetails) {
  90559. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  90560. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  90561. if (fullDetails) {
  90562. ret += ", Ranges: {";
  90563. var first = true;
  90564. for (var name_1 in this._ranges) {
  90565. if (first) {
  90566. ret += ", ";
  90567. first = false;
  90568. }
  90569. ret += name_1;
  90570. }
  90571. ret += "}";
  90572. }
  90573. return ret;
  90574. };
  90575. /**
  90576. * Get bone's index searching by name
  90577. * @param name defines bone's name to search for
  90578. * @return the indice of the bone. Returns -1 if not found
  90579. */
  90580. Skeleton.prototype.getBoneIndexByName = function (name) {
  90581. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  90582. if (this.bones[boneIndex].name === name) {
  90583. return boneIndex;
  90584. }
  90585. }
  90586. return -1;
  90587. };
  90588. /**
  90589. * Creater a new animation range
  90590. * @param name defines the name of the range
  90591. * @param from defines the start key
  90592. * @param to defines the end key
  90593. */
  90594. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  90595. // check name not already in use
  90596. if (!this._ranges[name]) {
  90597. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  90598. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90599. if (this.bones[i].animations[0]) {
  90600. this.bones[i].animations[0].createRange(name, from, to);
  90601. }
  90602. }
  90603. }
  90604. };
  90605. /**
  90606. * Delete a specific animation range
  90607. * @param name defines the name of the range
  90608. * @param deleteFrames defines if frames must be removed as well
  90609. */
  90610. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  90611. if (deleteFrames === void 0) { deleteFrames = true; }
  90612. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90613. if (this.bones[i].animations[0]) {
  90614. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  90615. }
  90616. }
  90617. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  90618. };
  90619. /**
  90620. * Gets a specific animation range
  90621. * @param name defines the name of the range to look for
  90622. * @returns the requested animation range or null if not found
  90623. */
  90624. Skeleton.prototype.getAnimationRange = function (name) {
  90625. return this._ranges[name];
  90626. };
  90627. /**
  90628. * Gets the list of all animation ranges defined on this skeleton
  90629. * @returns an array
  90630. */
  90631. Skeleton.prototype.getAnimationRanges = function () {
  90632. var animationRanges = [];
  90633. var name;
  90634. var i = 0;
  90635. for (name in this._ranges) {
  90636. animationRanges[i] = this._ranges[name];
  90637. i++;
  90638. }
  90639. return animationRanges;
  90640. };
  90641. /**
  90642. * Copy animation range from a source skeleton.
  90643. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  90644. * @param source defines the source skeleton
  90645. * @param name defines the name of the range to copy
  90646. * @param rescaleAsRequired defines if rescaling must be applied if required
  90647. * @returns true if operation was successful
  90648. */
  90649. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  90650. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90651. if (this._ranges[name] || !source.getAnimationRange(name)) {
  90652. return false;
  90653. }
  90654. var ret = true;
  90655. var frameOffset = this._getHighestAnimationFrame() + 1;
  90656. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  90657. var boneDict = {};
  90658. var sourceBones = source.bones;
  90659. var nBones;
  90660. var i;
  90661. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  90662. boneDict[sourceBones[i].name] = sourceBones[i];
  90663. }
  90664. if (this.bones.length !== sourceBones.length) {
  90665. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  90666. ret = false;
  90667. }
  90668. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  90669. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  90670. var boneName = this.bones[i].name;
  90671. var sourceBone = boneDict[boneName];
  90672. if (sourceBone) {
  90673. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  90674. }
  90675. else {
  90676. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  90677. ret = false;
  90678. }
  90679. }
  90680. // do not call createAnimationRange(), since it also is done to bones, which was already done
  90681. var range = source.getAnimationRange(name);
  90682. if (range) {
  90683. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  90684. }
  90685. return ret;
  90686. };
  90687. /**
  90688. * Forces the skeleton to go to rest pose
  90689. */
  90690. Skeleton.prototype.returnToRest = function () {
  90691. for (var index = 0; index < this.bones.length; index++) {
  90692. this.bones[index].returnToRest();
  90693. }
  90694. };
  90695. Skeleton.prototype._getHighestAnimationFrame = function () {
  90696. var ret = 0;
  90697. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90698. if (this.bones[i].animations[0]) {
  90699. var highest = this.bones[i].animations[0].getHighestFrame();
  90700. if (ret < highest) {
  90701. ret = highest;
  90702. }
  90703. }
  90704. }
  90705. return ret;
  90706. };
  90707. /**
  90708. * Begin a specific animation range
  90709. * @param name defines the name of the range to start
  90710. * @param loop defines if looping must be turned on (false by default)
  90711. * @param speedRatio defines the speed ratio to apply (1 by default)
  90712. * @param onAnimationEnd defines a callback which will be called when animation will end
  90713. * @returns a new animatable
  90714. */
  90715. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  90716. var range = this.getAnimationRange(name);
  90717. if (!range) {
  90718. return null;
  90719. }
  90720. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  90721. };
  90722. /** @hidden */
  90723. Skeleton.prototype._markAsDirty = function () {
  90724. this._isDirty = true;
  90725. };
  90726. /** @hidden */
  90727. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  90728. this._meshesWithPoseMatrix.push(mesh);
  90729. };
  90730. /** @hidden */
  90731. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  90732. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  90733. if (index > -1) {
  90734. this._meshesWithPoseMatrix.splice(index, 1);
  90735. }
  90736. };
  90737. /** @hidden */
  90738. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  90739. this.onBeforeComputeObservable.notifyObservers(this);
  90740. for (var index = 0; index < this.bones.length; index++) {
  90741. var bone = this.bones[index];
  90742. var parentBone = bone.getParent();
  90743. if (parentBone) {
  90744. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  90745. }
  90746. else {
  90747. if (initialSkinMatrix) {
  90748. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  90749. }
  90750. else {
  90751. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  90752. }
  90753. }
  90754. if (bone._index !== -1) {
  90755. var mappedIndex = bone._index === null ? index : bone._index;
  90756. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  90757. }
  90758. }
  90759. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  90760. };
  90761. /**
  90762. * Build all resources required to render a skeleton
  90763. */
  90764. Skeleton.prototype.prepare = function () {
  90765. if (!this._isDirty) {
  90766. return;
  90767. }
  90768. if (this.needInitialSkinMatrix) {
  90769. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  90770. var mesh = this._meshesWithPoseMatrix[index];
  90771. var poseMatrix = mesh.getPoseMatrix();
  90772. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  90773. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90774. }
  90775. if (this._synchronizedWithMesh !== mesh) {
  90776. this._synchronizedWithMesh = mesh;
  90777. // Prepare bones
  90778. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  90779. var bone = this.bones[boneIndex];
  90780. if (!bone.getParent()) {
  90781. var matrix = bone.getBaseMatrix();
  90782. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  90783. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  90784. }
  90785. }
  90786. }
  90787. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  90788. }
  90789. }
  90790. else {
  90791. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  90792. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90793. }
  90794. this._computeTransformMatrices(this._transformMatrices, null);
  90795. }
  90796. this._isDirty = false;
  90797. this._scene._activeBones.addCount(this.bones.length, false);
  90798. };
  90799. /**
  90800. * Gets the list of animatables currently running for this skeleton
  90801. * @returns an array of animatables
  90802. */
  90803. Skeleton.prototype.getAnimatables = function () {
  90804. if (!this._animatables || this._animatables.length !== this.bones.length) {
  90805. this._animatables = [];
  90806. for (var index = 0; index < this.bones.length; index++) {
  90807. this._animatables.push(this.bones[index]);
  90808. }
  90809. }
  90810. return this._animatables;
  90811. };
  90812. /**
  90813. * Clone the current skeleton
  90814. * @param name defines the name of the new skeleton
  90815. * @param id defines the id of the enw skeleton
  90816. * @returns the new skeleton
  90817. */
  90818. Skeleton.prototype.clone = function (name, id) {
  90819. var result = new Skeleton(name, id || name, this._scene);
  90820. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90821. for (var index = 0; index < this.bones.length; index++) {
  90822. var source = this.bones[index];
  90823. var parentBone = null;
  90824. var parent_1 = source.getParent();
  90825. if (parent_1) {
  90826. var parentIndex = this.bones.indexOf(parent_1);
  90827. parentBone = result.bones[parentIndex];
  90828. }
  90829. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  90830. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  90831. }
  90832. if (this._ranges) {
  90833. result._ranges = {};
  90834. for (var rangeName in this._ranges) {
  90835. var range = this._ranges[rangeName];
  90836. if (range) {
  90837. result._ranges[rangeName] = range.clone();
  90838. }
  90839. }
  90840. }
  90841. this._isDirty = true;
  90842. return result;
  90843. };
  90844. /**
  90845. * Enable animation blending for this skeleton
  90846. * @param blendingSpeed defines the blending speed to apply
  90847. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  90848. */
  90849. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  90850. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  90851. this.bones.forEach(function (bone) {
  90852. bone.animations.forEach(function (animation) {
  90853. animation.enableBlending = true;
  90854. animation.blendingSpeed = blendingSpeed;
  90855. });
  90856. });
  90857. };
  90858. /**
  90859. * Releases all resources associated with the current skeleton
  90860. */
  90861. Skeleton.prototype.dispose = function () {
  90862. this._meshesWithPoseMatrix = [];
  90863. // Animations
  90864. this.getScene().stopAnimation(this);
  90865. // Remove from scene
  90866. this.getScene().removeSkeleton(this);
  90867. };
  90868. /**
  90869. * Serialize the skeleton in a JSON object
  90870. * @returns a JSON object
  90871. */
  90872. Skeleton.prototype.serialize = function () {
  90873. var serializationObject = {};
  90874. serializationObject.name = this.name;
  90875. serializationObject.id = this.id;
  90876. if (this.dimensionsAtRest) {
  90877. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  90878. }
  90879. serializationObject.bones = [];
  90880. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90881. for (var index = 0; index < this.bones.length; index++) {
  90882. var bone = this.bones[index];
  90883. var parent_2 = bone.getParent();
  90884. var serializedBone = {
  90885. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  90886. name: bone.name,
  90887. matrix: bone.getBaseMatrix().toArray(),
  90888. rest: bone.getRestPose().toArray()
  90889. };
  90890. serializationObject.bones.push(serializedBone);
  90891. if (bone.length) {
  90892. serializedBone.length = bone.length;
  90893. }
  90894. if (bone.metadata) {
  90895. serializedBone.metadata = bone.metadata;
  90896. }
  90897. if (bone.animations && bone.animations.length > 0) {
  90898. serializedBone.animation = bone.animations[0].serialize();
  90899. }
  90900. serializationObject.ranges = [];
  90901. for (var name in this._ranges) {
  90902. var source = this._ranges[name];
  90903. if (!source) {
  90904. continue;
  90905. }
  90906. var range = {};
  90907. range.name = name;
  90908. range.from = source.from;
  90909. range.to = source.to;
  90910. serializationObject.ranges.push(range);
  90911. }
  90912. }
  90913. return serializationObject;
  90914. };
  90915. /**
  90916. * Creates a new skeleton from serialized data
  90917. * @param parsedSkeleton defines the serialized data
  90918. * @param scene defines the hosting scene
  90919. * @returns a new skeleton
  90920. */
  90921. Skeleton.Parse = function (parsedSkeleton, scene) {
  90922. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  90923. if (parsedSkeleton.dimensionsAtRest) {
  90924. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  90925. }
  90926. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  90927. var index;
  90928. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  90929. var parsedBone = parsedSkeleton.bones[index];
  90930. var parentBone = null;
  90931. if (parsedBone.parentBoneIndex > -1) {
  90932. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  90933. }
  90934. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  90935. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  90936. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  90937. bone.id = parsedBone.id;
  90938. }
  90939. if (parsedBone.length) {
  90940. bone.length = parsedBone.length;
  90941. }
  90942. if (parsedBone.metadata) {
  90943. bone.metadata = parsedBone.metadata;
  90944. }
  90945. if (parsedBone.animation) {
  90946. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  90947. }
  90948. }
  90949. // placed after bones, so createAnimationRange can cascade down
  90950. if (parsedSkeleton.ranges) {
  90951. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  90952. var data = parsedSkeleton.ranges[index];
  90953. skeleton.createAnimationRange(data.name, data.from, data.to);
  90954. }
  90955. }
  90956. return skeleton;
  90957. };
  90958. /**
  90959. * Compute all node absolute transforms
  90960. * @param forceUpdate defines if computation must be done even if cache is up to date
  90961. */
  90962. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  90963. if (forceUpdate === void 0) { forceUpdate = false; }
  90964. var renderId = this._scene.getRenderId();
  90965. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  90966. this.bones[0].computeAbsoluteTransforms();
  90967. this._lastAbsoluteTransformsUpdateId = renderId;
  90968. }
  90969. };
  90970. /**
  90971. * Gets the root pose matrix
  90972. * @returns a matrix
  90973. */
  90974. Skeleton.prototype.getPoseMatrix = function () {
  90975. var poseMatrix = null;
  90976. if (this._meshesWithPoseMatrix.length > 0) {
  90977. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  90978. }
  90979. return poseMatrix;
  90980. };
  90981. /**
  90982. * Sorts bones per internal index
  90983. */
  90984. Skeleton.prototype.sortBones = function () {
  90985. var bones = new Array();
  90986. var visited = new Array(this.bones.length);
  90987. for (var index = 0; index < this.bones.length; index++) {
  90988. this._sortBones(index, bones, visited);
  90989. }
  90990. this.bones = bones;
  90991. };
  90992. Skeleton.prototype._sortBones = function (index, bones, visited) {
  90993. if (visited[index]) {
  90994. return;
  90995. }
  90996. visited[index] = true;
  90997. var bone = this.bones[index];
  90998. if (bone._index === undefined) {
  90999. bone._index = index;
  91000. }
  91001. var parentBone = bone.getParent();
  91002. if (parentBone) {
  91003. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  91004. }
  91005. bones.push(bone);
  91006. };
  91007. return Skeleton;
  91008. }());
  91009. BABYLON.Skeleton = Skeleton;
  91010. })(BABYLON || (BABYLON = {}));
  91011. //# sourceMappingURL=babylon.skeleton.js.map
  91012. var BABYLON;
  91013. (function (BABYLON) {
  91014. ;
  91015. /**
  91016. * This groups tools to convert HDR texture to native colors array.
  91017. */
  91018. var HDRTools = /** @class */ (function () {
  91019. function HDRTools() {
  91020. }
  91021. HDRTools.Ldexp = function (mantissa, exponent) {
  91022. if (exponent > 1023) {
  91023. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  91024. }
  91025. if (exponent < -1074) {
  91026. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  91027. }
  91028. return mantissa * Math.pow(2, exponent);
  91029. };
  91030. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  91031. if (exponent > 0) { /*nonzero pixel*/
  91032. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  91033. float32array[index + 0] = red * exponent;
  91034. float32array[index + 1] = green * exponent;
  91035. float32array[index + 2] = blue * exponent;
  91036. }
  91037. else {
  91038. float32array[index + 0] = 0;
  91039. float32array[index + 1] = 0;
  91040. float32array[index + 2] = 0;
  91041. }
  91042. };
  91043. HDRTools.readStringLine = function (uint8array, startIndex) {
  91044. var line = "";
  91045. var character = "";
  91046. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  91047. character = String.fromCharCode(uint8array[i]);
  91048. if (character == "\n") {
  91049. break;
  91050. }
  91051. line += character;
  91052. }
  91053. return line;
  91054. };
  91055. /**
  91056. * Reads header information from an RGBE texture stored in a native array.
  91057. * More information on this format are available here:
  91058. * https://en.wikipedia.org/wiki/RGBE_image_format
  91059. *
  91060. * @param uint8array The binary file stored in native array.
  91061. * @return The header information.
  91062. */
  91063. HDRTools.RGBE_ReadHeader = function (uint8array) {
  91064. var height = 0;
  91065. var width = 0;
  91066. var line = this.readStringLine(uint8array, 0);
  91067. if (line[0] != '#' || line[1] != '?') {
  91068. throw "Bad HDR Format.";
  91069. }
  91070. var endOfHeader = false;
  91071. var findFormat = false;
  91072. var lineIndex = 0;
  91073. do {
  91074. lineIndex += (line.length + 1);
  91075. line = this.readStringLine(uint8array, lineIndex);
  91076. if (line == "FORMAT=32-bit_rle_rgbe") {
  91077. findFormat = true;
  91078. }
  91079. else if (line.length == 0) {
  91080. endOfHeader = true;
  91081. }
  91082. } while (!endOfHeader);
  91083. if (!findFormat) {
  91084. throw "HDR Bad header format, unsupported FORMAT";
  91085. }
  91086. lineIndex += (line.length + 1);
  91087. line = this.readStringLine(uint8array, lineIndex);
  91088. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  91089. var match = sizeRegexp.exec(line);
  91090. // TODO. Support +Y and -X if needed.
  91091. if (!match || match.length < 3) {
  91092. throw "HDR Bad header format, no size";
  91093. }
  91094. width = parseInt(match[2]);
  91095. height = parseInt(match[1]);
  91096. if (width < 8 || width > 0x7fff) {
  91097. throw "HDR Bad header format, unsupported size";
  91098. }
  91099. lineIndex += (line.length + 1);
  91100. return {
  91101. height: height,
  91102. width: width,
  91103. dataPosition: lineIndex
  91104. };
  91105. };
  91106. /**
  91107. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  91108. * This RGBE texture needs to store the information as a panorama.
  91109. *
  91110. * More information on this format are available here:
  91111. * https://en.wikipedia.org/wiki/RGBE_image_format
  91112. *
  91113. * @param buffer The binary file stored in an array buffer.
  91114. * @param size The expected size of the extracted cubemap.
  91115. * @return The Cube Map information.
  91116. */
  91117. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  91118. var uint8array = new Uint8Array(buffer);
  91119. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  91120. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  91121. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  91122. return cubeMapData;
  91123. };
  91124. /**
  91125. * Returns the pixels data extracted from an RGBE texture.
  91126. * This pixels will be stored left to right up to down in the R G B order in one array.
  91127. *
  91128. * More information on this format are available here:
  91129. * https://en.wikipedia.org/wiki/RGBE_image_format
  91130. *
  91131. * @param uint8array The binary file stored in an array buffer.
  91132. * @param hdrInfo The header information of the file.
  91133. * @return The pixels data in RGB right to left up to down order.
  91134. */
  91135. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  91136. // Keep for multi format supports.
  91137. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  91138. };
  91139. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  91140. var num_scanlines = hdrInfo.height;
  91141. var scanline_width = hdrInfo.width;
  91142. var a, b, c, d, count;
  91143. var dataIndex = hdrInfo.dataPosition;
  91144. var index = 0, endIndex = 0, i = 0;
  91145. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  91146. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  91147. // 3 channels of 4 bytes per pixel in float.
  91148. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  91149. var resultArray = new Float32Array(resultBuffer);
  91150. // read in each successive scanline
  91151. while (num_scanlines > 0) {
  91152. a = uint8array[dataIndex++];
  91153. b = uint8array[dataIndex++];
  91154. c = uint8array[dataIndex++];
  91155. d = uint8array[dataIndex++];
  91156. if (a != 2 || b != 2 || (c & 0x80)) {
  91157. // this file is not run length encoded
  91158. throw "HDR Bad header format, not RLE";
  91159. }
  91160. if (((c << 8) | d) != scanline_width) {
  91161. throw "HDR Bad header format, wrong scan line width";
  91162. }
  91163. index = 0;
  91164. // read each of the four channels for the scanline into the buffer
  91165. for (i = 0; i < 4; i++) {
  91166. endIndex = (i + 1) * scanline_width;
  91167. while (index < endIndex) {
  91168. a = uint8array[dataIndex++];
  91169. b = uint8array[dataIndex++];
  91170. if (a > 128) {
  91171. // a run of the same value
  91172. count = a - 128;
  91173. if ((count == 0) || (count > endIndex - index)) {
  91174. throw "HDR Bad Format, bad scanline data (run)";
  91175. }
  91176. while (count-- > 0) {
  91177. scanLineArray[index++] = b;
  91178. }
  91179. }
  91180. else {
  91181. // a non-run
  91182. count = a;
  91183. if ((count == 0) || (count > endIndex - index)) {
  91184. throw "HDR Bad Format, bad scanline data (non-run)";
  91185. }
  91186. scanLineArray[index++] = b;
  91187. if (--count > 0) {
  91188. for (var j = 0; j < count; j++) {
  91189. scanLineArray[index++] = uint8array[dataIndex++];
  91190. }
  91191. }
  91192. }
  91193. }
  91194. }
  91195. // now convert data from buffer into floats
  91196. for (i = 0; i < scanline_width; i++) {
  91197. a = scanLineArray[i];
  91198. b = scanLineArray[i + scanline_width];
  91199. c = scanLineArray[i + 2 * scanline_width];
  91200. d = scanLineArray[i + 3 * scanline_width];
  91201. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  91202. }
  91203. num_scanlines--;
  91204. }
  91205. return resultArray;
  91206. };
  91207. return HDRTools;
  91208. }());
  91209. BABYLON.HDRTools = HDRTools;
  91210. })(BABYLON || (BABYLON = {}));
  91211. //# sourceMappingURL=babylon.hdr.js.map
  91212. var BABYLON;
  91213. (function (BABYLON) {
  91214. /**
  91215. * This represents a texture coming from an HDR input.
  91216. *
  91217. * The only supported format is currently panorama picture stored in RGBE format.
  91218. * Example of such files can be found on HDRLib: http://hdrlib.com/
  91219. */
  91220. var HDRCubeTexture = /** @class */ (function (_super) {
  91221. __extends(HDRCubeTexture, _super);
  91222. /**
  91223. * Instantiates an HDRTexture from the following parameters.
  91224. *
  91225. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  91226. * @param scene The scene the texture will be used in
  91227. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  91228. * @param noMipmap Forces to not generate the mipmap if true
  91229. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  91230. * @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)
  91231. * @param reserved Reserved flag for internal use.
  91232. */
  91233. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  91234. if (noMipmap === void 0) { noMipmap = false; }
  91235. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91236. if (gammaSpace === void 0) { gammaSpace = false; }
  91237. if (reserved === void 0) { reserved = false; }
  91238. if (onLoad === void 0) { onLoad = null; }
  91239. if (onError === void 0) { onError = null; }
  91240. var _this = _super.call(this, scene) || this;
  91241. _this._generateHarmonics = true;
  91242. _this._onLoad = null;
  91243. _this._onError = null;
  91244. /**
  91245. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  91246. */
  91247. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  91248. _this._isBlocking = true;
  91249. _this._rotationY = 0;
  91250. /**
  91251. * Gets or sets the center of the bounding box associated with the cube texture
  91252. * It must define where the camera used to render the texture was set
  91253. */
  91254. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  91255. if (!url) {
  91256. return _this;
  91257. }
  91258. _this.name = url;
  91259. _this.url = url;
  91260. _this.hasAlpha = false;
  91261. _this.isCube = true;
  91262. _this._textureMatrix = BABYLON.Matrix.Identity();
  91263. _this._onLoad = onLoad;
  91264. _this._onError = onError;
  91265. _this.gammaSpace = gammaSpace;
  91266. _this._noMipmap = noMipmap;
  91267. _this._size = size;
  91268. _this._texture = _this._getFromCache(url, _this._noMipmap);
  91269. if (!_this._texture) {
  91270. if (!scene.useDelayedTextureLoading) {
  91271. _this.loadTexture();
  91272. }
  91273. else {
  91274. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  91275. }
  91276. }
  91277. return _this;
  91278. }
  91279. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  91280. /**
  91281. * Gets wether or not the texture is blocking during loading.
  91282. */
  91283. get: function () {
  91284. return this._isBlocking;
  91285. },
  91286. /**
  91287. * Sets wether or not the texture is blocking during loading.
  91288. */
  91289. set: function (value) {
  91290. this._isBlocking = value;
  91291. },
  91292. enumerable: true,
  91293. configurable: true
  91294. });
  91295. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  91296. /**
  91297. * Gets texture matrix rotation angle around Y axis radians.
  91298. */
  91299. get: function () {
  91300. return this._rotationY;
  91301. },
  91302. /**
  91303. * Sets texture matrix rotation angle around Y axis in radians.
  91304. */
  91305. set: function (value) {
  91306. this._rotationY = value;
  91307. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  91308. },
  91309. enumerable: true,
  91310. configurable: true
  91311. });
  91312. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  91313. get: function () {
  91314. return this._boundingBoxSize;
  91315. },
  91316. /**
  91317. * Gets or sets the size of the bounding box associated with the cube texture
  91318. * When defined, the cubemap will switch to local mode
  91319. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  91320. * @example https://www.babylonjs-playground.com/#RNASML
  91321. */
  91322. set: function (value) {
  91323. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  91324. return;
  91325. }
  91326. this._boundingBoxSize = value;
  91327. var scene = this.getScene();
  91328. if (scene) {
  91329. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  91330. }
  91331. },
  91332. enumerable: true,
  91333. configurable: true
  91334. });
  91335. /**
  91336. * Occurs when the file is raw .hdr file.
  91337. */
  91338. HDRCubeTexture.prototype.loadTexture = function () {
  91339. var _this = this;
  91340. var callback = function (buffer) {
  91341. _this.lodGenerationOffset = 0.0;
  91342. _this.lodGenerationScale = 0.8;
  91343. var scene = _this.getScene();
  91344. if (!scene) {
  91345. return null;
  91346. }
  91347. // Extract the raw linear data.
  91348. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  91349. // Generate harmonics if needed.
  91350. if (_this._generateHarmonics) {
  91351. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  91352. _this.sphericalPolynomial = sphericalPolynomial;
  91353. }
  91354. var results = [];
  91355. var byteArray = null;
  91356. // Push each faces.
  91357. for (var j = 0; j < 6; j++) {
  91358. // Create uintarray fallback.
  91359. if (!scene.getEngine().getCaps().textureFloat) {
  91360. // 3 channels of 1 bytes per pixel in bytes.
  91361. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  91362. byteArray = new Uint8Array(byteBuffer);
  91363. }
  91364. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  91365. // If special cases.
  91366. if (_this.gammaSpace || byteArray) {
  91367. for (var i = 0; i < _this._size * _this._size; i++) {
  91368. // Put in gamma space if requested.
  91369. if (_this.gammaSpace) {
  91370. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  91371. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  91372. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  91373. }
  91374. // Convert to int texture for fallback.
  91375. if (byteArray) {
  91376. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  91377. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  91378. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  91379. // May use luminance instead if the result is not accurate.
  91380. var max = Math.max(Math.max(r, g), b);
  91381. if (max > 255) {
  91382. var scale = 255 / max;
  91383. r *= scale;
  91384. g *= scale;
  91385. b *= scale;
  91386. }
  91387. byteArray[(i * 3) + 0] = r;
  91388. byteArray[(i * 3) + 1] = g;
  91389. byteArray[(i * 3) + 2] = b;
  91390. }
  91391. }
  91392. }
  91393. if (byteArray) {
  91394. results.push(byteArray);
  91395. }
  91396. else {
  91397. results.push(dataFace);
  91398. }
  91399. }
  91400. return results;
  91401. };
  91402. var scene = this.getScene();
  91403. if (scene) {
  91404. 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);
  91405. }
  91406. };
  91407. HDRCubeTexture.prototype.clone = function () {
  91408. var scene = this.getScene();
  91409. if (!scene) {
  91410. return this;
  91411. }
  91412. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  91413. // Base texture
  91414. newTexture.level = this.level;
  91415. newTexture.wrapU = this.wrapU;
  91416. newTexture.wrapV = this.wrapV;
  91417. newTexture.coordinatesIndex = this.coordinatesIndex;
  91418. newTexture.coordinatesMode = this.coordinatesMode;
  91419. return newTexture;
  91420. };
  91421. // Methods
  91422. HDRCubeTexture.prototype.delayLoad = function () {
  91423. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  91424. return;
  91425. }
  91426. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  91427. this._texture = this._getFromCache(this.url, this._noMipmap);
  91428. if (!this._texture) {
  91429. this.loadTexture();
  91430. }
  91431. };
  91432. /**
  91433. * Get the texture reflection matrix used to rotate/transform the reflection.
  91434. * @returns the reflection matrix
  91435. */
  91436. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  91437. return this._textureMatrix;
  91438. };
  91439. /**
  91440. * Set the texture reflection matrix used to rotate/transform the reflection.
  91441. * @param value Define the reflection matrix to set
  91442. */
  91443. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  91444. this._textureMatrix = value;
  91445. };
  91446. /**
  91447. * Parses a JSON representation of an HDR Texture in order to create the texture
  91448. * @param parsedTexture Define the JSON representation
  91449. * @param scene Define the scene the texture should be created in
  91450. * @param rootUrl Define the root url in case we need to load relative dependencies
  91451. * @returns the newly created texture after parsing
  91452. */
  91453. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  91454. var texture = null;
  91455. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  91456. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  91457. texture.name = parsedTexture.name;
  91458. texture.hasAlpha = parsedTexture.hasAlpha;
  91459. texture.level = parsedTexture.level;
  91460. texture.coordinatesMode = parsedTexture.coordinatesMode;
  91461. texture.isBlocking = parsedTexture.isBlocking;
  91462. }
  91463. if (texture) {
  91464. if (parsedTexture.boundingBoxPosition) {
  91465. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  91466. }
  91467. if (parsedTexture.boundingBoxSize) {
  91468. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  91469. }
  91470. if (parsedTexture.rotationY) {
  91471. texture.rotationY = parsedTexture.rotationY;
  91472. }
  91473. }
  91474. return texture;
  91475. };
  91476. HDRCubeTexture.prototype.serialize = function () {
  91477. if (!this.name) {
  91478. return null;
  91479. }
  91480. var serializationObject = {};
  91481. serializationObject.name = this.name;
  91482. serializationObject.hasAlpha = this.hasAlpha;
  91483. serializationObject.isCube = true;
  91484. serializationObject.level = this.level;
  91485. serializationObject.size = this._size;
  91486. serializationObject.coordinatesMode = this.coordinatesMode;
  91487. serializationObject.useInGammaSpace = this.gammaSpace;
  91488. serializationObject.generateHarmonics = this._generateHarmonics;
  91489. serializationObject.customType = "BABYLON.HDRCubeTexture";
  91490. serializationObject.noMipmap = this._noMipmap;
  91491. serializationObject.isBlocking = this._isBlocking;
  91492. serializationObject.rotationY = this._rotationY;
  91493. return serializationObject;
  91494. };
  91495. HDRCubeTexture._facesMapping = [
  91496. "right",
  91497. "left",
  91498. "up",
  91499. "down",
  91500. "front",
  91501. "back"
  91502. ];
  91503. return HDRCubeTexture;
  91504. }(BABYLON.BaseTexture));
  91505. BABYLON.HDRCubeTexture = HDRCubeTexture;
  91506. })(BABYLON || (BABYLON = {}));
  91507. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  91508. var BABYLON;
  91509. (function (BABYLON) {
  91510. /**
  91511. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  91512. */
  91513. var PanoramaToCubeMapTools = /** @class */ (function () {
  91514. function PanoramaToCubeMapTools() {
  91515. }
  91516. /**
  91517. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  91518. *
  91519. * @param float32Array The source data.
  91520. * @param inputWidth The width of the input panorama.
  91521. * @param inputhHeight The height of the input panorama.
  91522. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  91523. * @return The cubemap data
  91524. */
  91525. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  91526. if (!float32Array) {
  91527. throw "ConvertPanoramaToCubemap: input cannot be null";
  91528. }
  91529. if (float32Array.length != inputWidth * inputHeight * 3) {
  91530. throw "ConvertPanoramaToCubemap: input size is wrong";
  91531. }
  91532. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  91533. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  91534. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  91535. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  91536. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  91537. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  91538. return {
  91539. front: textureFront,
  91540. back: textureBack,
  91541. left: textureLeft,
  91542. right: textureRight,
  91543. up: textureUp,
  91544. down: textureDown,
  91545. size: size,
  91546. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91547. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  91548. gammaSpace: false,
  91549. };
  91550. };
  91551. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  91552. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  91553. var textureArray = new Float32Array(buffer);
  91554. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  91555. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  91556. var dy = 1 / texSize;
  91557. var fy = 0;
  91558. for (var y = 0; y < texSize; y++) {
  91559. var xv1 = faceData[0];
  91560. var xv2 = faceData[2];
  91561. for (var x = 0; x < texSize; x++) {
  91562. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  91563. v.normalize();
  91564. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  91565. // 3 channels per pixels
  91566. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  91567. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  91568. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  91569. xv1 = xv1.add(rotDX1);
  91570. xv2 = xv2.add(rotDX2);
  91571. }
  91572. fy += dy;
  91573. }
  91574. return textureArray;
  91575. };
  91576. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  91577. var theta = Math.atan2(vDir.z, vDir.x);
  91578. var phi = Math.acos(vDir.y);
  91579. while (theta < -Math.PI)
  91580. theta += 2 * Math.PI;
  91581. while (theta > Math.PI)
  91582. theta -= 2 * Math.PI;
  91583. var dx = theta / Math.PI;
  91584. var dy = phi / Math.PI;
  91585. // recenter.
  91586. dx = dx * 0.5 + 0.5;
  91587. var px = Math.round(dx * inputWidth);
  91588. if (px < 0)
  91589. px = 0;
  91590. else if (px >= inputWidth)
  91591. px = inputWidth - 1;
  91592. var py = Math.round(dy * inputHeight);
  91593. if (py < 0)
  91594. py = 0;
  91595. else if (py >= inputHeight)
  91596. py = inputHeight - 1;
  91597. var inputY = (inputHeight - py - 1);
  91598. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  91599. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  91600. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  91601. return {
  91602. r: r,
  91603. g: g,
  91604. b: b
  91605. };
  91606. };
  91607. PanoramaToCubeMapTools.FACE_FRONT = [
  91608. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91609. new BABYLON.Vector3(1.0, -1.0, -1.0),
  91610. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  91611. new BABYLON.Vector3(1.0, 1.0, -1.0)
  91612. ];
  91613. PanoramaToCubeMapTools.FACE_BACK = [
  91614. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91615. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91616. new BABYLON.Vector3(1.0, 1.0, 1.0),
  91617. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  91618. ];
  91619. PanoramaToCubeMapTools.FACE_RIGHT = [
  91620. new BABYLON.Vector3(1.0, -1.0, -1.0),
  91621. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91622. new BABYLON.Vector3(1.0, 1.0, -1.0),
  91623. new BABYLON.Vector3(1.0, 1.0, 1.0)
  91624. ];
  91625. PanoramaToCubeMapTools.FACE_LEFT = [
  91626. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91627. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91628. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  91629. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  91630. ];
  91631. PanoramaToCubeMapTools.FACE_DOWN = [
  91632. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  91633. new BABYLON.Vector3(1.0, 1.0, -1.0),
  91634. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  91635. new BABYLON.Vector3(1.0, 1.0, 1.0)
  91636. ];
  91637. PanoramaToCubeMapTools.FACE_UP = [
  91638. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91639. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91640. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91641. new BABYLON.Vector3(1.0, -1.0, -1.0)
  91642. ];
  91643. return PanoramaToCubeMapTools;
  91644. }());
  91645. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  91646. })(BABYLON || (BABYLON = {}));
  91647. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  91648. var BABYLON;
  91649. (function (BABYLON) {
  91650. var IndexedVector2 = /** @class */ (function (_super) {
  91651. __extends(IndexedVector2, _super);
  91652. function IndexedVector2(original, index) {
  91653. var _this = _super.call(this, original.x, original.y) || this;
  91654. _this.index = index;
  91655. return _this;
  91656. }
  91657. return IndexedVector2;
  91658. }(BABYLON.Vector2));
  91659. var PolygonPoints = /** @class */ (function () {
  91660. function PolygonPoints() {
  91661. this.elements = new Array();
  91662. }
  91663. PolygonPoints.prototype.add = function (originalPoints) {
  91664. var _this = this;
  91665. var result = new Array();
  91666. originalPoints.forEach(function (point) {
  91667. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  91668. var newPoint = new IndexedVector2(point, _this.elements.length);
  91669. result.push(newPoint);
  91670. _this.elements.push(newPoint);
  91671. }
  91672. });
  91673. return result;
  91674. };
  91675. PolygonPoints.prototype.computeBounds = function () {
  91676. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  91677. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  91678. this.elements.forEach(function (point) {
  91679. // x
  91680. if (point.x < lmin.x) {
  91681. lmin.x = point.x;
  91682. }
  91683. else if (point.x > lmax.x) {
  91684. lmax.x = point.x;
  91685. }
  91686. // y
  91687. if (point.y < lmin.y) {
  91688. lmin.y = point.y;
  91689. }
  91690. else if (point.y > lmax.y) {
  91691. lmax.y = point.y;
  91692. }
  91693. });
  91694. return {
  91695. min: lmin,
  91696. max: lmax,
  91697. width: lmax.x - lmin.x,
  91698. height: lmax.y - lmin.y
  91699. };
  91700. };
  91701. return PolygonPoints;
  91702. }());
  91703. var Polygon = /** @class */ (function () {
  91704. function Polygon() {
  91705. }
  91706. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  91707. return [
  91708. new BABYLON.Vector2(xmin, ymin),
  91709. new BABYLON.Vector2(xmax, ymin),
  91710. new BABYLON.Vector2(xmax, ymax),
  91711. new BABYLON.Vector2(xmin, ymax)
  91712. ];
  91713. };
  91714. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  91715. if (cx === void 0) { cx = 0; }
  91716. if (cy === void 0) { cy = 0; }
  91717. if (numberOfSides === void 0) { numberOfSides = 32; }
  91718. var result = new Array();
  91719. var angle = 0;
  91720. var increment = (Math.PI * 2) / numberOfSides;
  91721. for (var i = 0; i < numberOfSides; i++) {
  91722. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  91723. angle -= increment;
  91724. }
  91725. return result;
  91726. };
  91727. Polygon.Parse = function (input) {
  91728. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  91729. var i, result = [];
  91730. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  91731. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  91732. }
  91733. return result;
  91734. };
  91735. Polygon.StartingAt = function (x, y) {
  91736. return BABYLON.Path2.StartingAt(x, y);
  91737. };
  91738. return Polygon;
  91739. }());
  91740. BABYLON.Polygon = Polygon;
  91741. var PolygonMeshBuilder = /** @class */ (function () {
  91742. function PolygonMeshBuilder(name, contours, scene) {
  91743. this._points = new PolygonPoints();
  91744. this._outlinepoints = new PolygonPoints();
  91745. this._holes = new Array();
  91746. this._epoints = new Array();
  91747. this._eholes = new Array();
  91748. this._name = name;
  91749. this._scene = scene;
  91750. var points;
  91751. if (contours instanceof BABYLON.Path2) {
  91752. points = contours.getPoints();
  91753. }
  91754. else {
  91755. points = contours;
  91756. }
  91757. this._addToepoint(points);
  91758. this._points.add(points);
  91759. this._outlinepoints.add(points);
  91760. if (typeof earcut === 'undefined') {
  91761. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  91762. }
  91763. }
  91764. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  91765. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  91766. var p = points_1[_i];
  91767. this._epoints.push(p.x, p.y);
  91768. }
  91769. };
  91770. PolygonMeshBuilder.prototype.addHole = function (hole) {
  91771. this._points.add(hole);
  91772. var holepoints = new PolygonPoints();
  91773. holepoints.add(hole);
  91774. this._holes.push(holepoints);
  91775. this._eholes.push(this._epoints.length / 2);
  91776. this._addToepoint(hole);
  91777. return this;
  91778. };
  91779. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  91780. var _this = this;
  91781. if (updatable === void 0) { updatable = false; }
  91782. if (depth === void 0) { depth = 0; }
  91783. var result = new BABYLON.Mesh(this._name, this._scene);
  91784. var normals = new Array();
  91785. var positions = new Array();
  91786. var uvs = new Array();
  91787. var bounds = this._points.computeBounds();
  91788. this._points.elements.forEach(function (p) {
  91789. normals.push(0, 1.0, 0);
  91790. positions.push(p.x, 0, p.y);
  91791. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  91792. });
  91793. var indices = new Array();
  91794. var res = earcut(this._epoints, this._eholes, 2);
  91795. for (var i = 0; i < res.length; i++) {
  91796. indices.push(res[i]);
  91797. }
  91798. if (depth > 0) {
  91799. var positionscount = (positions.length / 3); //get the current pointcount
  91800. this._points.elements.forEach(function (p) {
  91801. normals.push(0, -1.0, 0);
  91802. positions.push(p.x, -depth, p.y);
  91803. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  91804. });
  91805. var totalCount = indices.length;
  91806. for (var i = 0; i < totalCount; i += 3) {
  91807. var i0 = indices[i + 0];
  91808. var i1 = indices[i + 1];
  91809. var i2 = indices[i + 2];
  91810. indices.push(i2 + positionscount);
  91811. indices.push(i1 + positionscount);
  91812. indices.push(i0 + positionscount);
  91813. }
  91814. //Add the sides
  91815. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  91816. this._holes.forEach(function (hole) {
  91817. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  91818. });
  91819. }
  91820. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  91821. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  91822. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  91823. result.setIndices(indices);
  91824. return result;
  91825. };
  91826. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  91827. var StartIndex = positions.length / 3;
  91828. var ulength = 0;
  91829. for (var i = 0; i < points.elements.length; i++) {
  91830. var p = points.elements[i];
  91831. var p1;
  91832. if ((i + 1) > points.elements.length - 1) {
  91833. p1 = points.elements[0];
  91834. }
  91835. else {
  91836. p1 = points.elements[i + 1];
  91837. }
  91838. positions.push(p.x, 0, p.y);
  91839. positions.push(p.x, -depth, p.y);
  91840. positions.push(p1.x, 0, p1.y);
  91841. positions.push(p1.x, -depth, p1.y);
  91842. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  91843. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  91844. var v3 = v2.subtract(v1);
  91845. var v4 = new BABYLON.Vector3(0, 1, 0);
  91846. var vn = BABYLON.Vector3.Cross(v3, v4);
  91847. vn = vn.normalize();
  91848. uvs.push(ulength / bounds.width, 0);
  91849. uvs.push(ulength / bounds.width, 1);
  91850. ulength += v3.length();
  91851. uvs.push((ulength / bounds.width), 0);
  91852. uvs.push((ulength / bounds.width), 1);
  91853. if (!flip) {
  91854. normals.push(-vn.x, -vn.y, -vn.z);
  91855. normals.push(-vn.x, -vn.y, -vn.z);
  91856. normals.push(-vn.x, -vn.y, -vn.z);
  91857. normals.push(-vn.x, -vn.y, -vn.z);
  91858. indices.push(StartIndex);
  91859. indices.push(StartIndex + 1);
  91860. indices.push(StartIndex + 2);
  91861. indices.push(StartIndex + 1);
  91862. indices.push(StartIndex + 3);
  91863. indices.push(StartIndex + 2);
  91864. }
  91865. else {
  91866. normals.push(vn.x, vn.y, vn.z);
  91867. normals.push(vn.x, vn.y, vn.z);
  91868. normals.push(vn.x, vn.y, vn.z);
  91869. normals.push(vn.x, vn.y, vn.z);
  91870. indices.push(StartIndex);
  91871. indices.push(StartIndex + 2);
  91872. indices.push(StartIndex + 1);
  91873. indices.push(StartIndex + 1);
  91874. indices.push(StartIndex + 2);
  91875. indices.push(StartIndex + 3);
  91876. }
  91877. StartIndex += 4;
  91878. }
  91879. ;
  91880. };
  91881. return PolygonMeshBuilder;
  91882. }());
  91883. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  91884. })(BABYLON || (BABYLON = {}));
  91885. //# sourceMappingURL=babylon.polygonMesh.js.map
  91886. var BABYLON;
  91887. (function (BABYLON) {
  91888. /**
  91889. * Unique ID when we import meshes from Babylon to CSG
  91890. */
  91891. var currentCSGMeshId = 0;
  91892. /**
  91893. * Represents a vertex of a polygon. Use your own vertex class instead of this
  91894. * one to provide additional features like texture coordinates and vertex
  91895. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  91896. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  91897. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  91898. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  91899. * is not used anywhere else.
  91900. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  91901. */
  91902. var Vertex = /** @class */ (function () {
  91903. /**
  91904. * Initializes the vertex
  91905. * @param pos The position of the vertex
  91906. * @param normal The normal of the vertex
  91907. * @param uv The texture coordinate of the vertex
  91908. */
  91909. function Vertex(
  91910. /**
  91911. * The position of the vertex
  91912. */
  91913. pos,
  91914. /**
  91915. * The normal of the vertex
  91916. */
  91917. normal,
  91918. /**
  91919. * The texture coordinate of the vertex
  91920. */
  91921. uv) {
  91922. this.pos = pos;
  91923. this.normal = normal;
  91924. this.uv = uv;
  91925. }
  91926. /**
  91927. * Make a clone, or deep copy, of the vertex
  91928. * @returns A new Vertex
  91929. */
  91930. Vertex.prototype.clone = function () {
  91931. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  91932. };
  91933. /**
  91934. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  91935. * orientation of a polygon is flipped.
  91936. */
  91937. Vertex.prototype.flip = function () {
  91938. this.normal = this.normal.scale(-1);
  91939. };
  91940. /**
  91941. * Create a new vertex between this vertex and `other` by linearly
  91942. * interpolating all properties using a parameter of `t`. Subclasses should
  91943. * override this to interpolate additional properties.
  91944. * @param other the vertex to interpolate against
  91945. * @param t The factor used to linearly interpolate between the vertices
  91946. */
  91947. Vertex.prototype.interpolate = function (other, t) {
  91948. 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));
  91949. };
  91950. return Vertex;
  91951. }());
  91952. /**
  91953. * Represents a plane in 3D space.
  91954. */
  91955. var Plane = /** @class */ (function () {
  91956. /**
  91957. * Initializes the plane
  91958. * @param normal The normal for the plane
  91959. * @param w
  91960. */
  91961. function Plane(normal, w) {
  91962. this.normal = normal;
  91963. this.w = w;
  91964. }
  91965. /**
  91966. * Construct a plane from three points
  91967. * @param a Point a
  91968. * @param b Point b
  91969. * @param c Point c
  91970. */
  91971. Plane.FromPoints = function (a, b, c) {
  91972. var v0 = c.subtract(a);
  91973. var v1 = b.subtract(a);
  91974. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  91975. return null;
  91976. }
  91977. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  91978. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  91979. };
  91980. /**
  91981. * Clone, or make a deep copy of the plane
  91982. * @returns a new Plane
  91983. */
  91984. Plane.prototype.clone = function () {
  91985. return new Plane(this.normal.clone(), this.w);
  91986. };
  91987. /**
  91988. * Flip the face of the plane
  91989. */
  91990. Plane.prototype.flip = function () {
  91991. this.normal.scaleInPlace(-1);
  91992. this.w = -this.w;
  91993. };
  91994. /**
  91995. * Split `polygon` by this plane if needed, then put the polygon or polygon
  91996. * fragments in the appropriate lists. Coplanar polygons go into either
  91997. `* coplanarFront` or `coplanarBack` depending on their orientation with
  91998. * respect to this plane. Polygons in front or in back of this plane go into
  91999. * either `front` or `back`
  92000. * @param polygon The polygon to be split
  92001. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  92002. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  92003. * @param front Will contain the polygons in front of the plane
  92004. * @param back Will contain the polygons begind the plane
  92005. */
  92006. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  92007. var COPLANAR = 0;
  92008. var FRONT = 1;
  92009. var BACK = 2;
  92010. var SPANNING = 3;
  92011. // Classify each point as well as the entire polygon into one of the above
  92012. // four classes.
  92013. var polygonType = 0;
  92014. var types = [];
  92015. var i;
  92016. var t;
  92017. for (i = 0; i < polygon.vertices.length; i++) {
  92018. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  92019. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  92020. polygonType |= type;
  92021. types.push(type);
  92022. }
  92023. // Put the polygon in the correct list, splitting it when necessary
  92024. switch (polygonType) {
  92025. case COPLANAR:
  92026. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  92027. break;
  92028. case FRONT:
  92029. front.push(polygon);
  92030. break;
  92031. case BACK:
  92032. back.push(polygon);
  92033. break;
  92034. case SPANNING:
  92035. var f = [], b = [];
  92036. for (i = 0; i < polygon.vertices.length; i++) {
  92037. var j = (i + 1) % polygon.vertices.length;
  92038. var ti = types[i], tj = types[j];
  92039. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  92040. if (ti !== BACK)
  92041. f.push(vi);
  92042. if (ti !== FRONT)
  92043. b.push(ti !== BACK ? vi.clone() : vi);
  92044. if ((ti | tj) === SPANNING) {
  92045. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  92046. var v = vi.interpolate(vj, t);
  92047. f.push(v);
  92048. b.push(v.clone());
  92049. }
  92050. }
  92051. var poly;
  92052. if (f.length >= 3) {
  92053. poly = new Polygon(f, polygon.shared);
  92054. if (poly.plane)
  92055. front.push(poly);
  92056. }
  92057. if (b.length >= 3) {
  92058. poly = new Polygon(b, polygon.shared);
  92059. if (poly.plane)
  92060. back.push(poly);
  92061. }
  92062. break;
  92063. }
  92064. };
  92065. /**
  92066. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  92067. * point is on the plane
  92068. */
  92069. Plane.EPSILON = 1e-5;
  92070. return Plane;
  92071. }());
  92072. /**
  92073. * Represents a convex polygon. The vertices used to initialize a polygon must
  92074. * be coplanar and form a convex loop.
  92075. *
  92076. * Each convex polygon has a `shared` property, which is shared between all
  92077. * polygons that are clones of each other or were split from the same polygon.
  92078. * This can be used to define per-polygon properties (such as surface color)
  92079. */
  92080. var Polygon = /** @class */ (function () {
  92081. /**
  92082. * Initializes the polygon
  92083. * @param vertices The vertices of the polygon
  92084. * @param shared The properties shared across all polygons
  92085. */
  92086. function Polygon(vertices, shared) {
  92087. this.vertices = vertices;
  92088. this.shared = shared;
  92089. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  92090. }
  92091. /**
  92092. * Clones, or makes a deep copy, or the polygon
  92093. */
  92094. Polygon.prototype.clone = function () {
  92095. var vertices = this.vertices.map(function (v) { return v.clone(); });
  92096. return new Polygon(vertices, this.shared);
  92097. };
  92098. /**
  92099. * Flips the faces of the polygon
  92100. */
  92101. Polygon.prototype.flip = function () {
  92102. this.vertices.reverse().map(function (v) { v.flip(); });
  92103. this.plane.flip();
  92104. };
  92105. return Polygon;
  92106. }());
  92107. /**
  92108. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  92109. * by picking a polygon to split along. That polygon (and all other coplanar
  92110. * polygons) are added directly to that node and the other polygons are added to
  92111. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  92112. * no distinction between internal and leaf nodes
  92113. */
  92114. var Node = /** @class */ (function () {
  92115. /**
  92116. * Initializes the node
  92117. * @param polygons A collection of polygons held in the node
  92118. */
  92119. function Node(polygons) {
  92120. this.plane = null;
  92121. this.front = null;
  92122. this.back = null;
  92123. this.polygons = new Array();
  92124. if (polygons) {
  92125. this.build(polygons);
  92126. }
  92127. }
  92128. /**
  92129. * Clones, or makes a deep copy, of the node
  92130. * @returns The cloned node
  92131. */
  92132. Node.prototype.clone = function () {
  92133. var node = new Node();
  92134. node.plane = this.plane && this.plane.clone();
  92135. node.front = this.front && this.front.clone();
  92136. node.back = this.back && this.back.clone();
  92137. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  92138. return node;
  92139. };
  92140. /**
  92141. * Convert solid space to empty space and empty space to solid space
  92142. */
  92143. Node.prototype.invert = function () {
  92144. for (var i = 0; i < this.polygons.length; i++) {
  92145. this.polygons[i].flip();
  92146. }
  92147. if (this.plane) {
  92148. this.plane.flip();
  92149. }
  92150. if (this.front) {
  92151. this.front.invert();
  92152. }
  92153. if (this.back) {
  92154. this.back.invert();
  92155. }
  92156. var temp = this.front;
  92157. this.front = this.back;
  92158. this.back = temp;
  92159. };
  92160. /**
  92161. * Recursively remove all polygons in `polygons` that are inside this BSP
  92162. * tree.
  92163. * @param polygons Polygons to remove from the BSP
  92164. * @returns Polygons clipped from the BSP
  92165. */
  92166. Node.prototype.clipPolygons = function (polygons) {
  92167. if (!this.plane)
  92168. return polygons.slice();
  92169. var front = new Array(), back = new Array();
  92170. for (var i = 0; i < polygons.length; i++) {
  92171. this.plane.splitPolygon(polygons[i], front, back, front, back);
  92172. }
  92173. if (this.front) {
  92174. front = this.front.clipPolygons(front);
  92175. }
  92176. if (this.back) {
  92177. back = this.back.clipPolygons(back);
  92178. }
  92179. else {
  92180. back = [];
  92181. }
  92182. return front.concat(back);
  92183. };
  92184. /**
  92185. * Remove all polygons in this BSP tree that are inside the other BSP tree
  92186. * `bsp`.
  92187. * @param bsp BSP containing polygons to remove from this BSP
  92188. */
  92189. Node.prototype.clipTo = function (bsp) {
  92190. this.polygons = bsp.clipPolygons(this.polygons);
  92191. if (this.front)
  92192. this.front.clipTo(bsp);
  92193. if (this.back)
  92194. this.back.clipTo(bsp);
  92195. };
  92196. /**
  92197. * Return a list of all polygons in this BSP tree
  92198. * @returns List of all polygons in this BSP tree
  92199. */
  92200. Node.prototype.allPolygons = function () {
  92201. var polygons = this.polygons.slice();
  92202. if (this.front)
  92203. polygons = polygons.concat(this.front.allPolygons());
  92204. if (this.back)
  92205. polygons = polygons.concat(this.back.allPolygons());
  92206. return polygons;
  92207. };
  92208. /**
  92209. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  92210. * new polygons are filtered down to the bottom of the tree and become new
  92211. * nodes there. Each set of polygons is partitioned using the first polygon
  92212. * (no heuristic is used to pick a good split)
  92213. * @param polygons Polygons used to construct the BSP tree
  92214. */
  92215. Node.prototype.build = function (polygons) {
  92216. if (!polygons.length)
  92217. return;
  92218. if (!this.plane)
  92219. this.plane = polygons[0].plane.clone();
  92220. var front = new Array(), back = new Array();
  92221. for (var i = 0; i < polygons.length; i++) {
  92222. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  92223. }
  92224. if (front.length) {
  92225. if (!this.front)
  92226. this.front = new Node();
  92227. this.front.build(front);
  92228. }
  92229. if (back.length) {
  92230. if (!this.back)
  92231. this.back = new Node();
  92232. this.back.build(back);
  92233. }
  92234. };
  92235. return Node;
  92236. }());
  92237. /**
  92238. * Class for building Constructive Solid Geometry
  92239. */
  92240. var CSG = /** @class */ (function () {
  92241. function CSG() {
  92242. this.polygons = new Array();
  92243. }
  92244. /**
  92245. * Convert the BABYLON.Mesh to BABYLON.CSG
  92246. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  92247. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  92248. */
  92249. CSG.FromMesh = function (mesh) {
  92250. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  92251. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  92252. if (mesh instanceof BABYLON.Mesh) {
  92253. mesh.computeWorldMatrix(true);
  92254. matrix = mesh.getWorldMatrix();
  92255. meshPosition = mesh.position.clone();
  92256. meshRotation = mesh.rotation.clone();
  92257. if (mesh.rotationQuaternion) {
  92258. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  92259. }
  92260. meshScaling = mesh.scaling.clone();
  92261. }
  92262. else {
  92263. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  92264. }
  92265. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92266. var subMeshes = mesh.subMeshes;
  92267. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  92268. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  92269. vertices = [];
  92270. for (var j = 0; j < 3; j++) {
  92271. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  92272. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  92273. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  92274. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  92275. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  92276. vertex = new Vertex(position, normal, uv);
  92277. vertices.push(vertex);
  92278. }
  92279. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  92280. // To handle the case of degenerated triangle
  92281. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  92282. if (polygon.plane)
  92283. polygons.push(polygon);
  92284. }
  92285. }
  92286. var csg = CSG.FromPolygons(polygons);
  92287. csg.matrix = matrix;
  92288. csg.position = meshPosition;
  92289. csg.rotation = meshRotation;
  92290. csg.scaling = meshScaling;
  92291. csg.rotationQuaternion = meshRotationQuaternion;
  92292. currentCSGMeshId++;
  92293. return csg;
  92294. };
  92295. /**
  92296. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  92297. * @param polygons Polygons used to construct a BABYLON.CSG solid
  92298. */
  92299. CSG.FromPolygons = function (polygons) {
  92300. var csg = new CSG();
  92301. csg.polygons = polygons;
  92302. return csg;
  92303. };
  92304. /**
  92305. * Clones, or makes a deep copy, of the BABYLON.CSG
  92306. * @returns A new BABYLON.CSG
  92307. */
  92308. CSG.prototype.clone = function () {
  92309. var csg = new CSG();
  92310. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  92311. csg.copyTransformAttributes(this);
  92312. return csg;
  92313. };
  92314. /**
  92315. * Unions this CSG with another CSG
  92316. * @param csg The CSG to union against this CSG
  92317. * @returns The unioned CSG
  92318. */
  92319. CSG.prototype.union = function (csg) {
  92320. var a = new Node(this.clone().polygons);
  92321. var b = new Node(csg.clone().polygons);
  92322. a.clipTo(b);
  92323. b.clipTo(a);
  92324. b.invert();
  92325. b.clipTo(a);
  92326. b.invert();
  92327. a.build(b.allPolygons());
  92328. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92329. };
  92330. /**
  92331. * Unions this CSG with another CSG in place
  92332. * @param csg The CSG to union against this CSG
  92333. */
  92334. CSG.prototype.unionInPlace = function (csg) {
  92335. var a = new Node(this.polygons);
  92336. var b = new Node(csg.polygons);
  92337. a.clipTo(b);
  92338. b.clipTo(a);
  92339. b.invert();
  92340. b.clipTo(a);
  92341. b.invert();
  92342. a.build(b.allPolygons());
  92343. this.polygons = a.allPolygons();
  92344. };
  92345. /**
  92346. * Subtracts this CSG with another CSG
  92347. * @param csg The CSG to subtract against this CSG
  92348. * @returns A new BABYLON.CSG
  92349. */
  92350. CSG.prototype.subtract = function (csg) {
  92351. var a = new Node(this.clone().polygons);
  92352. var b = new Node(csg.clone().polygons);
  92353. a.invert();
  92354. a.clipTo(b);
  92355. b.clipTo(a);
  92356. b.invert();
  92357. b.clipTo(a);
  92358. b.invert();
  92359. a.build(b.allPolygons());
  92360. a.invert();
  92361. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92362. };
  92363. /**
  92364. * Subtracts this CSG with another CSG in place
  92365. * @param csg The CSG to subtact against this CSG
  92366. */
  92367. CSG.prototype.subtractInPlace = function (csg) {
  92368. var a = new Node(this.polygons);
  92369. var b = new Node(csg.polygons);
  92370. a.invert();
  92371. a.clipTo(b);
  92372. b.clipTo(a);
  92373. b.invert();
  92374. b.clipTo(a);
  92375. b.invert();
  92376. a.build(b.allPolygons());
  92377. a.invert();
  92378. this.polygons = a.allPolygons();
  92379. };
  92380. /**
  92381. * Intersect this CSG with another CSG
  92382. * @param csg The CSG to intersect against this CSG
  92383. * @returns A new BABYLON.CSG
  92384. */
  92385. CSG.prototype.intersect = function (csg) {
  92386. var a = new Node(this.clone().polygons);
  92387. var b = new Node(csg.clone().polygons);
  92388. a.invert();
  92389. b.clipTo(a);
  92390. b.invert();
  92391. a.clipTo(b);
  92392. b.clipTo(a);
  92393. a.build(b.allPolygons());
  92394. a.invert();
  92395. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92396. };
  92397. /**
  92398. * Intersects this CSG with another CSG in place
  92399. * @param csg The CSG to intersect against this CSG
  92400. */
  92401. CSG.prototype.intersectInPlace = function (csg) {
  92402. var a = new Node(this.polygons);
  92403. var b = new Node(csg.polygons);
  92404. a.invert();
  92405. b.clipTo(a);
  92406. b.invert();
  92407. a.clipTo(b);
  92408. b.clipTo(a);
  92409. a.build(b.allPolygons());
  92410. a.invert();
  92411. this.polygons = a.allPolygons();
  92412. };
  92413. /**
  92414. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  92415. * not modified.
  92416. * @returns A new BABYLON.CSG solid with solid and empty space switched
  92417. */
  92418. CSG.prototype.inverse = function () {
  92419. var csg = this.clone();
  92420. csg.inverseInPlace();
  92421. return csg;
  92422. };
  92423. /**
  92424. * Inverses the BABYLON.CSG in place
  92425. */
  92426. CSG.prototype.inverseInPlace = function () {
  92427. this.polygons.map(function (p) { p.flip(); });
  92428. };
  92429. /**
  92430. * This is used to keep meshes transformations so they can be restored
  92431. * when we build back a Babylon Mesh
  92432. * NB : All CSG operations are performed in world coordinates
  92433. * @param csg The BABYLON.CSG to copy the transform attributes from
  92434. * @returns This BABYLON.CSG
  92435. */
  92436. CSG.prototype.copyTransformAttributes = function (csg) {
  92437. this.matrix = csg.matrix;
  92438. this.position = csg.position;
  92439. this.rotation = csg.rotation;
  92440. this.scaling = csg.scaling;
  92441. this.rotationQuaternion = csg.rotationQuaternion;
  92442. return this;
  92443. };
  92444. /**
  92445. * Build Raw mesh from CSG
  92446. * Coordinates here are in world space
  92447. * @param name The name of the mesh geometry
  92448. * @param scene The BABYLON.Scene
  92449. * @param keepSubMeshes Specifies if the submeshes should be kept
  92450. * @returns A new BABYLON.Mesh
  92451. */
  92452. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  92453. var matrix = this.matrix.clone();
  92454. matrix.invert();
  92455. 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;
  92456. if (keepSubMeshes) {
  92457. // Sort Polygons, since subMeshes are indices range
  92458. polygons.sort(function (a, b) {
  92459. if (a.shared.meshId === b.shared.meshId) {
  92460. return a.shared.subMeshId - b.shared.subMeshId;
  92461. }
  92462. else {
  92463. return a.shared.meshId - b.shared.meshId;
  92464. }
  92465. });
  92466. }
  92467. for (var i = 0, il = polygons.length; i < il; i++) {
  92468. polygon = polygons[i];
  92469. // Building SubMeshes
  92470. if (!subMesh_dict[polygon.shared.meshId]) {
  92471. subMesh_dict[polygon.shared.meshId] = {};
  92472. }
  92473. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  92474. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  92475. indexStart: +Infinity,
  92476. indexEnd: -Infinity,
  92477. materialIndex: polygon.shared.materialIndex
  92478. };
  92479. }
  92480. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  92481. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  92482. polygonIndices[0] = 0;
  92483. polygonIndices[1] = j - 1;
  92484. polygonIndices[2] = j;
  92485. for (var k = 0; k < 3; k++) {
  92486. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  92487. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  92488. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  92489. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  92490. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  92491. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  92492. // Check if 2 points can be merged
  92493. if (!(typeof vertex_idx !== 'undefined' &&
  92494. normals[vertex_idx * 3] === localNormal.x &&
  92495. normals[vertex_idx * 3 + 1] === localNormal.y &&
  92496. normals[vertex_idx * 3 + 2] === localNormal.z &&
  92497. uvs[vertex_idx * 2] === uv.x &&
  92498. uvs[vertex_idx * 2 + 1] === uv.y)) {
  92499. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  92500. uvs.push(uv.x, uv.y);
  92501. normals.push(normal.x, normal.y, normal.z);
  92502. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  92503. }
  92504. indices.push(vertex_idx);
  92505. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  92506. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  92507. currentIndex++;
  92508. }
  92509. }
  92510. }
  92511. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  92512. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  92513. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  92514. mesh.setIndices(indices, null);
  92515. if (keepSubMeshes) {
  92516. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  92517. var materialIndexOffset = 0, materialMaxIndex;
  92518. mesh.subMeshes = new Array();
  92519. for (var m in subMesh_dict) {
  92520. materialMaxIndex = -1;
  92521. for (var sm in subMesh_dict[m]) {
  92522. subMesh_obj = subMesh_dict[m][sm];
  92523. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  92524. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  92525. }
  92526. materialIndexOffset += ++materialMaxIndex;
  92527. }
  92528. }
  92529. return mesh;
  92530. };
  92531. /**
  92532. * Build Mesh from CSG taking material and transforms into account
  92533. * @param name The name of the BABYLON.Mesh
  92534. * @param material The material of the BABYLON.Mesh
  92535. * @param scene The BABYLON.Scene
  92536. * @param keepSubMeshes Specifies if submeshes should be kept
  92537. * @returns The new BABYLON.Mesh
  92538. */
  92539. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  92540. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  92541. mesh.material = material;
  92542. mesh.position.copyFrom(this.position);
  92543. mesh.rotation.copyFrom(this.rotation);
  92544. if (this.rotationQuaternion) {
  92545. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  92546. }
  92547. mesh.scaling.copyFrom(this.scaling);
  92548. mesh.computeWorldMatrix(true);
  92549. return mesh;
  92550. };
  92551. return CSG;
  92552. }());
  92553. BABYLON.CSG = CSG;
  92554. })(BABYLON || (BABYLON = {}));
  92555. //# sourceMappingURL=babylon.csg.js.map
  92556. var BABYLON;
  92557. (function (BABYLON) {
  92558. /**
  92559. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92560. * It controls one of the indiviual texture used in the effect.
  92561. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92562. */
  92563. var LensFlare = /** @class */ (function () {
  92564. /**
  92565. * Instantiates a new Lens Flare.
  92566. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92567. * It controls one of the indiviual texture used in the effect.
  92568. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92569. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  92570. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92571. * @param color Define the lens color
  92572. * @param imgUrl Define the lens texture url
  92573. * @param system Define the `lensFlareSystem` this flare is part of
  92574. */
  92575. function LensFlare(
  92576. /**
  92577. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  92578. */
  92579. size,
  92580. /**
  92581. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92582. */
  92583. position, color, imgUrl, system) {
  92584. this.size = size;
  92585. this.position = position;
  92586. /**
  92587. * Define the alpha mode to render this particular lens.
  92588. */
  92589. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  92590. this.color = color || new BABYLON.Color3(1, 1, 1);
  92591. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  92592. this._system = system;
  92593. system.lensFlares.push(this);
  92594. }
  92595. /**
  92596. * Creates a new Lens Flare.
  92597. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92598. * It controls one of the indiviual texture used in the effect.
  92599. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92600. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  92601. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92602. * @param color Define the lens color
  92603. * @param imgUrl Define the lens texture url
  92604. * @param system Define the `lensFlareSystem` this flare is part of
  92605. * @returns The newly created Lens Flare
  92606. */
  92607. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  92608. return new LensFlare(size, position, color, imgUrl, system);
  92609. };
  92610. /**
  92611. * Dispose and release the lens flare with its associated resources.
  92612. */
  92613. LensFlare.prototype.dispose = function () {
  92614. if (this.texture) {
  92615. this.texture.dispose();
  92616. }
  92617. // Remove from scene
  92618. var index = this._system.lensFlares.indexOf(this);
  92619. this._system.lensFlares.splice(index, 1);
  92620. };
  92621. ;
  92622. return LensFlare;
  92623. }());
  92624. BABYLON.LensFlare = LensFlare;
  92625. })(BABYLON || (BABYLON = {}));
  92626. //# sourceMappingURL=babylon.lensFlare.js.map
  92627. var BABYLON;
  92628. (function (BABYLON) {
  92629. // Adds the parser to the scene parsers.
  92630. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  92631. // Lens flares
  92632. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  92633. if (!container.lensFlareSystems) {
  92634. container.lensFlareSystems = new Array();
  92635. }
  92636. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  92637. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  92638. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  92639. container.lensFlareSystems.push(lf);
  92640. }
  92641. }
  92642. });
  92643. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  92644. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  92645. if (this.lensFlareSystems[index].name === name) {
  92646. return this.lensFlareSystems[index];
  92647. }
  92648. }
  92649. return null;
  92650. };
  92651. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  92652. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  92653. if (this.lensFlareSystems[index].id === id) {
  92654. return this.lensFlareSystems[index];
  92655. }
  92656. }
  92657. return null;
  92658. };
  92659. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  92660. var index = this.lensFlareSystems.indexOf(toRemove);
  92661. if (index !== -1) {
  92662. this.lensFlareSystems.splice(index, 1);
  92663. }
  92664. return index;
  92665. };
  92666. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  92667. this.lensFlareSystems.push(newLensFlareSystem);
  92668. };
  92669. /**
  92670. * Defines the lens flare scene component responsible to manage any lens flares
  92671. * in a given scene.
  92672. */
  92673. var LensFlareSystemSceneComponent = /** @class */ (function () {
  92674. /**
  92675. * Creates a new instance of the component for the given scene
  92676. * @param scene Defines the scene to register the component in
  92677. */
  92678. function LensFlareSystemSceneComponent(scene) {
  92679. /**
  92680. * The component name helpfull to identify the component in the list of scene components.
  92681. */
  92682. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  92683. this.scene = scene;
  92684. scene.lensFlareSystems = new Array();
  92685. }
  92686. /**
  92687. * Registers the component in a given scene
  92688. */
  92689. LensFlareSystemSceneComponent.prototype.register = function () {
  92690. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  92691. };
  92692. /**
  92693. * Rebuilds the elements related to this component in case of
  92694. * context lost for instance.
  92695. */
  92696. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  92697. // Nothing to do for lens flare
  92698. };
  92699. /**
  92700. * Adds all the element from the container to the scene
  92701. * @param container the container holding the elements
  92702. */
  92703. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  92704. var _this = this;
  92705. if (!container.lensFlareSystems) {
  92706. return;
  92707. }
  92708. container.lensFlareSystems.forEach(function (o) {
  92709. _this.scene.addLensFlareSystem(o);
  92710. });
  92711. };
  92712. /**
  92713. * Removes all the elements in the container from the scene
  92714. * @param container contains the elements to remove
  92715. */
  92716. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  92717. var _this = this;
  92718. if (!container.lensFlareSystems) {
  92719. return;
  92720. }
  92721. container.lensFlareSystems.forEach(function (o) {
  92722. _this.scene.removeLensFlareSystem(o);
  92723. });
  92724. };
  92725. /**
  92726. * Serializes the component data to the specified json object
  92727. * @param serializationObject The object to serialize to
  92728. */
  92729. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  92730. // Lens flares
  92731. serializationObject.lensFlareSystems = [];
  92732. var lensFlareSystems = this.scene.lensFlareSystems;
  92733. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  92734. var lensFlareSystem = lensFlareSystems_1[_i];
  92735. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  92736. }
  92737. };
  92738. /**
  92739. * Disposes the component and the associated ressources.
  92740. */
  92741. LensFlareSystemSceneComponent.prototype.dispose = function () {
  92742. var lensFlareSystems = this.scene.lensFlareSystems;
  92743. while (lensFlareSystems.length) {
  92744. lensFlareSystems[0].dispose();
  92745. }
  92746. };
  92747. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  92748. // Lens flares
  92749. if (this.scene.lensFlaresEnabled) {
  92750. var lensFlareSystems = this.scene.lensFlareSystems;
  92751. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  92752. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  92753. var lensFlareSystem = lensFlareSystems_2[_i];
  92754. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  92755. lensFlareSystem.render();
  92756. }
  92757. }
  92758. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  92759. }
  92760. };
  92761. return LensFlareSystemSceneComponent;
  92762. }());
  92763. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  92764. })(BABYLON || (BABYLON = {}));
  92765. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  92766. var BABYLON;
  92767. (function (BABYLON) {
  92768. /**
  92769. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  92770. * It is usually composed of several `BABYLON.lensFlare`.
  92771. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92772. */
  92773. var LensFlareSystem = /** @class */ (function () {
  92774. /**
  92775. * Instantiates a lens flare system.
  92776. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  92777. * It is usually composed of several `BABYLON.lensFlare`.
  92778. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92779. * @param name Define the name of the lens flare system in the scene
  92780. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  92781. * @param scene Define the scene the lens flare system belongs to
  92782. */
  92783. function LensFlareSystem(
  92784. /**
  92785. * Define the name of the lens flare system
  92786. */
  92787. name, emitter, scene) {
  92788. this.name = name;
  92789. /**
  92790. * List of lens flares used in this system.
  92791. */
  92792. this.lensFlares = new Array();
  92793. /**
  92794. * Define a limit from the border the lens flare can be visible.
  92795. */
  92796. this.borderLimit = 300;
  92797. /**
  92798. * Define a viewport border we do not want to see the lens flare in.
  92799. */
  92800. this.viewportBorder = 0;
  92801. /**
  92802. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  92803. */
  92804. this.layerMask = 0x0FFFFFFF;
  92805. this._vertexBuffers = {};
  92806. this._isEnabled = true;
  92807. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92808. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  92809. if (!component) {
  92810. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  92811. scene._addComponent(component);
  92812. }
  92813. this._emitter = emitter;
  92814. this.id = name;
  92815. scene.lensFlareSystems.push(this);
  92816. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  92817. var engine = scene.getEngine();
  92818. // VBO
  92819. var vertices = [];
  92820. vertices.push(1, 1);
  92821. vertices.push(-1, 1);
  92822. vertices.push(-1, -1);
  92823. vertices.push(1, -1);
  92824. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92825. // Indices
  92826. var indices = [];
  92827. indices.push(0);
  92828. indices.push(1);
  92829. indices.push(2);
  92830. indices.push(0);
  92831. indices.push(2);
  92832. indices.push(3);
  92833. this._indexBuffer = engine.createIndexBuffer(indices);
  92834. // Effects
  92835. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  92836. }
  92837. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  92838. /**
  92839. * Define if the lens flare system is enabled.
  92840. */
  92841. get: function () {
  92842. return this._isEnabled;
  92843. },
  92844. set: function (value) {
  92845. this._isEnabled = value;
  92846. },
  92847. enumerable: true,
  92848. configurable: true
  92849. });
  92850. /**
  92851. * Get the scene the effects belongs to.
  92852. * @returns the scene holding the lens flare system
  92853. */
  92854. LensFlareSystem.prototype.getScene = function () {
  92855. return this._scene;
  92856. };
  92857. /**
  92858. * Get the emitter of the lens flare system.
  92859. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92860. * @returns the emitter of the lens flare system
  92861. */
  92862. LensFlareSystem.prototype.getEmitter = function () {
  92863. return this._emitter;
  92864. };
  92865. /**
  92866. * Set the emitter of the lens flare system.
  92867. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92868. * @param newEmitter Define the new emitter of the system
  92869. */
  92870. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  92871. this._emitter = newEmitter;
  92872. };
  92873. /**
  92874. * Get the lens flare system emitter position.
  92875. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  92876. * @returns the position
  92877. */
  92878. LensFlareSystem.prototype.getEmitterPosition = function () {
  92879. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  92880. };
  92881. /**
  92882. * @hidden
  92883. */
  92884. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  92885. var position = this.getEmitterPosition();
  92886. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  92887. this._positionX = position.x;
  92888. this._positionY = position.y;
  92889. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  92890. if (this.viewportBorder > 0) {
  92891. globalViewport.x -= this.viewportBorder;
  92892. globalViewport.y -= this.viewportBorder;
  92893. globalViewport.width += this.viewportBorder * 2;
  92894. globalViewport.height += this.viewportBorder * 2;
  92895. position.x += this.viewportBorder;
  92896. position.y += this.viewportBorder;
  92897. this._positionX += this.viewportBorder;
  92898. this._positionY += this.viewportBorder;
  92899. }
  92900. if (position.z > 0) {
  92901. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  92902. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  92903. return true;
  92904. }
  92905. return true;
  92906. }
  92907. return false;
  92908. };
  92909. /** @hidden */
  92910. LensFlareSystem.prototype._isVisible = function () {
  92911. if (!this._isEnabled || !this._scene.activeCamera) {
  92912. return false;
  92913. }
  92914. var emitterPosition = this.getEmitterPosition();
  92915. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  92916. var distance = direction.length();
  92917. direction.normalize();
  92918. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  92919. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  92920. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  92921. };
  92922. /**
  92923. * @hidden
  92924. */
  92925. LensFlareSystem.prototype.render = function () {
  92926. if (!this._effect.isReady() || !this._scene.activeCamera)
  92927. return false;
  92928. var engine = this._scene.getEngine();
  92929. var viewport = this._scene.activeCamera.viewport;
  92930. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  92931. // Position
  92932. if (!this.computeEffectivePosition(globalViewport)) {
  92933. return false;
  92934. }
  92935. // Visibility
  92936. if (!this._isVisible()) {
  92937. return false;
  92938. }
  92939. // Intensity
  92940. var awayX;
  92941. var awayY;
  92942. if (this._positionX < this.borderLimit + globalViewport.x) {
  92943. awayX = this.borderLimit + globalViewport.x - this._positionX;
  92944. }
  92945. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  92946. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  92947. }
  92948. else {
  92949. awayX = 0;
  92950. }
  92951. if (this._positionY < this.borderLimit + globalViewport.y) {
  92952. awayY = this.borderLimit + globalViewport.y - this._positionY;
  92953. }
  92954. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  92955. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  92956. }
  92957. else {
  92958. awayY = 0;
  92959. }
  92960. var away = (awayX > awayY) ? awayX : awayY;
  92961. away -= this.viewportBorder;
  92962. if (away > this.borderLimit) {
  92963. away = this.borderLimit;
  92964. }
  92965. var intensity = 1.0 - (away / this.borderLimit);
  92966. if (intensity < 0) {
  92967. return false;
  92968. }
  92969. if (intensity > 1.0) {
  92970. intensity = 1.0;
  92971. }
  92972. if (this.viewportBorder > 0) {
  92973. globalViewport.x += this.viewportBorder;
  92974. globalViewport.y += this.viewportBorder;
  92975. globalViewport.width -= this.viewportBorder * 2;
  92976. globalViewport.height -= this.viewportBorder * 2;
  92977. this._positionX -= this.viewportBorder;
  92978. this._positionY -= this.viewportBorder;
  92979. }
  92980. // Position
  92981. var centerX = globalViewport.x + globalViewport.width / 2;
  92982. var centerY = globalViewport.y + globalViewport.height / 2;
  92983. var distX = centerX - this._positionX;
  92984. var distY = centerY - this._positionY;
  92985. // Effects
  92986. engine.enableEffect(this._effect);
  92987. engine.setState(false);
  92988. engine.setDepthBuffer(false);
  92989. // VBOs
  92990. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  92991. // Flares
  92992. for (var index = 0; index < this.lensFlares.length; index++) {
  92993. var flare = this.lensFlares[index];
  92994. engine.setAlphaMode(flare.alphaMode);
  92995. var x = centerX - (distX * flare.position);
  92996. var y = centerY - (distY * flare.position);
  92997. var cw = flare.size;
  92998. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  92999. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  93000. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  93001. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  93002. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  93003. // Texture
  93004. this._effect.setTexture("textureSampler", flare.texture);
  93005. // Color
  93006. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  93007. // Draw order
  93008. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93009. }
  93010. engine.setDepthBuffer(true);
  93011. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93012. return true;
  93013. };
  93014. /**
  93015. * Dispose and release the lens flare with its associated resources.
  93016. */
  93017. LensFlareSystem.prototype.dispose = function () {
  93018. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93019. if (vertexBuffer) {
  93020. vertexBuffer.dispose();
  93021. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93022. }
  93023. if (this._indexBuffer) {
  93024. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93025. this._indexBuffer = null;
  93026. }
  93027. while (this.lensFlares.length) {
  93028. this.lensFlares[0].dispose();
  93029. }
  93030. // Remove from scene
  93031. var index = this._scene.lensFlareSystems.indexOf(this);
  93032. this._scene.lensFlareSystems.splice(index, 1);
  93033. };
  93034. /**
  93035. * Parse a lens flare system from a JSON repressentation
  93036. * @param parsedLensFlareSystem Define the JSON to parse
  93037. * @param scene Define the scene the parsed system should be instantiated in
  93038. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  93039. * @returns the parsed system
  93040. */
  93041. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  93042. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  93043. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  93044. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  93045. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  93046. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  93047. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  93048. var parsedFlare = parsedLensFlareSystem.flares[index];
  93049. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  93050. }
  93051. return lensFlareSystem;
  93052. };
  93053. /**
  93054. * Serialize the current Lens Flare System into a JSON representation.
  93055. * @returns the serialized JSON
  93056. */
  93057. LensFlareSystem.prototype.serialize = function () {
  93058. var serializationObject = {};
  93059. serializationObject.id = this.id;
  93060. serializationObject.name = this.name;
  93061. serializationObject.emitterId = this.getEmitter().id;
  93062. serializationObject.borderLimit = this.borderLimit;
  93063. serializationObject.flares = [];
  93064. for (var index = 0; index < this.lensFlares.length; index++) {
  93065. var flare = this.lensFlares[index];
  93066. serializationObject.flares.push({
  93067. size: flare.size,
  93068. position: flare.position,
  93069. color: flare.color.asArray(),
  93070. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  93071. });
  93072. }
  93073. return serializationObject;
  93074. };
  93075. return LensFlareSystem;
  93076. }());
  93077. BABYLON.LensFlareSystem = LensFlareSystem;
  93078. })(BABYLON || (BABYLON = {}));
  93079. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  93080. var BABYLON;
  93081. (function (BABYLON) {
  93082. /**
  93083. * This is a holder class for the physics joint created by the physics plugin.
  93084. * It holds a set of functions to control the underlying joint.
  93085. */
  93086. var PhysicsJoint = /** @class */ (function () {
  93087. function PhysicsJoint(type, jointData) {
  93088. this.type = type;
  93089. this.jointData = jointData;
  93090. jointData.nativeParams = jointData.nativeParams || {};
  93091. }
  93092. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  93093. get: function () {
  93094. return this._physicsJoint;
  93095. },
  93096. set: function (newJoint) {
  93097. if (this._physicsJoint) {
  93098. //remove from the wolrd
  93099. }
  93100. this._physicsJoint = newJoint;
  93101. },
  93102. enumerable: true,
  93103. configurable: true
  93104. });
  93105. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  93106. set: function (physicsPlugin) {
  93107. this._physicsPlugin = physicsPlugin;
  93108. },
  93109. enumerable: true,
  93110. configurable: true
  93111. });
  93112. /**
  93113. * Execute a function that is physics-plugin specific.
  93114. * @param {Function} func the function that will be executed.
  93115. * It accepts two parameters: the physics world and the physics joint.
  93116. */
  93117. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  93118. func(this._physicsPlugin.world, this._physicsJoint);
  93119. };
  93120. //TODO check if the native joints are the same
  93121. //Joint Types
  93122. PhysicsJoint.DistanceJoint = 0;
  93123. PhysicsJoint.HingeJoint = 1;
  93124. PhysicsJoint.BallAndSocketJoint = 2;
  93125. PhysicsJoint.WheelJoint = 3;
  93126. PhysicsJoint.SliderJoint = 4;
  93127. //OIMO
  93128. PhysicsJoint.PrismaticJoint = 5;
  93129. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  93130. PhysicsJoint.UniversalJoint = 6;
  93131. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  93132. //Cannon
  93133. //Similar to a Ball-Joint. Different in params
  93134. PhysicsJoint.PointToPointJoint = 8;
  93135. //Cannon only at the moment
  93136. PhysicsJoint.SpringJoint = 9;
  93137. PhysicsJoint.LockJoint = 10;
  93138. return PhysicsJoint;
  93139. }());
  93140. BABYLON.PhysicsJoint = PhysicsJoint;
  93141. /**
  93142. * A class representing a physics distance joint.
  93143. */
  93144. var DistanceJoint = /** @class */ (function (_super) {
  93145. __extends(DistanceJoint, _super);
  93146. function DistanceJoint(jointData) {
  93147. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  93148. }
  93149. /**
  93150. * Update the predefined distance.
  93151. */
  93152. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  93153. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  93154. };
  93155. return DistanceJoint;
  93156. }(PhysicsJoint));
  93157. BABYLON.DistanceJoint = DistanceJoint;
  93158. var MotorEnabledJoint = /** @class */ (function (_super) {
  93159. __extends(MotorEnabledJoint, _super);
  93160. function MotorEnabledJoint(type, jointData) {
  93161. return _super.call(this, type, jointData) || this;
  93162. }
  93163. /**
  93164. * Set the motor values.
  93165. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93166. * @param {number} force the force to apply
  93167. * @param {number} maxForce max force for this motor.
  93168. */
  93169. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  93170. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  93171. };
  93172. /**
  93173. * Set the motor's limits.
  93174. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93175. */
  93176. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  93177. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  93178. };
  93179. return MotorEnabledJoint;
  93180. }(PhysicsJoint));
  93181. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  93182. /**
  93183. * This class represents a single hinge physics joint
  93184. */
  93185. var HingeJoint = /** @class */ (function (_super) {
  93186. __extends(HingeJoint, _super);
  93187. function HingeJoint(jointData) {
  93188. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  93189. }
  93190. /**
  93191. * Set the motor values.
  93192. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93193. * @param {number} force the force to apply
  93194. * @param {number} maxForce max force for this motor.
  93195. */
  93196. HingeJoint.prototype.setMotor = function (force, maxForce) {
  93197. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  93198. };
  93199. /**
  93200. * Set the motor's limits.
  93201. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93202. */
  93203. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  93204. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  93205. };
  93206. return HingeJoint;
  93207. }(MotorEnabledJoint));
  93208. BABYLON.HingeJoint = HingeJoint;
  93209. /**
  93210. * This class represents a dual hinge physics joint (same as wheel joint)
  93211. */
  93212. var Hinge2Joint = /** @class */ (function (_super) {
  93213. __extends(Hinge2Joint, _super);
  93214. function Hinge2Joint(jointData) {
  93215. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  93216. }
  93217. /**
  93218. * Set the motor values.
  93219. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93220. * @param {number} force the force to apply
  93221. * @param {number} maxForce max force for this motor.
  93222. * @param {motorIndex} the motor's index, 0 or 1.
  93223. */
  93224. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  93225. if (motorIndex === void 0) { motorIndex = 0; }
  93226. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  93227. };
  93228. /**
  93229. * Set the motor limits.
  93230. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93231. * @param {number} upperLimit the upper limit
  93232. * @param {number} lowerLimit lower limit
  93233. * @param {motorIndex} the motor's index, 0 or 1.
  93234. */
  93235. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  93236. if (motorIndex === void 0) { motorIndex = 0; }
  93237. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  93238. };
  93239. return Hinge2Joint;
  93240. }(MotorEnabledJoint));
  93241. BABYLON.Hinge2Joint = Hinge2Joint;
  93242. })(BABYLON || (BABYLON = {}));
  93243. //# sourceMappingURL=babylon.physicsJoint.js.map
  93244. var BABYLON;
  93245. (function (BABYLON) {
  93246. var PhysicsImpostor = /** @class */ (function () {
  93247. function PhysicsImpostor(object, type, _options, _scene) {
  93248. if (_options === void 0) { _options = { mass: 0 }; }
  93249. var _this = this;
  93250. this.object = object;
  93251. this.type = type;
  93252. this._options = _options;
  93253. this._scene = _scene;
  93254. this._bodyUpdateRequired = false;
  93255. this._onBeforePhysicsStepCallbacks = new Array();
  93256. this._onAfterPhysicsStepCallbacks = new Array();
  93257. this._onPhysicsCollideCallbacks = [];
  93258. this._deltaPosition = BABYLON.Vector3.Zero();
  93259. this._isDisposed = false;
  93260. //temp variables for parent rotation calculations
  93261. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  93262. this._tmpQuat = new BABYLON.Quaternion();
  93263. this._tmpQuat2 = new BABYLON.Quaternion();
  93264. /**
  93265. * this function is executed by the physics engine.
  93266. */
  93267. this.beforeStep = function () {
  93268. if (!_this._physicsEngine) {
  93269. return;
  93270. }
  93271. _this.object.translate(_this._deltaPosition, -1);
  93272. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  93273. _this.object.computeWorldMatrix(false);
  93274. if (_this.object.parent && _this.object.rotationQuaternion) {
  93275. _this.getParentsRotation();
  93276. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  93277. }
  93278. else {
  93279. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  93280. }
  93281. if (!_this._options.disableBidirectionalTransformation) {
  93282. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  93283. }
  93284. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  93285. func(_this);
  93286. });
  93287. };
  93288. /**
  93289. * this function is executed by the physics engine.
  93290. */
  93291. this.afterStep = function () {
  93292. if (!_this._physicsEngine) {
  93293. return;
  93294. }
  93295. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  93296. func(_this);
  93297. });
  93298. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  93299. // object has now its world rotation. needs to be converted to local.
  93300. if (_this.object.parent && _this.object.rotationQuaternion) {
  93301. _this.getParentsRotation();
  93302. _this._tmpQuat.conjugateInPlace();
  93303. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  93304. }
  93305. // take the position set and make it the absolute position of this object.
  93306. _this.object.setAbsolutePosition(_this.object.position);
  93307. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  93308. _this.object.translate(_this._deltaPosition, 1);
  93309. };
  93310. /**
  93311. * Legacy collision detection event support
  93312. */
  93313. this.onCollideEvent = null;
  93314. //event and body object due to cannon's event-based architecture.
  93315. this.onCollide = function (e) {
  93316. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  93317. return;
  93318. }
  93319. if (!_this._physicsEngine) {
  93320. return;
  93321. }
  93322. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  93323. if (otherImpostor) {
  93324. // Legacy collision detection event support
  93325. if (_this.onCollideEvent) {
  93326. _this.onCollideEvent(_this, otherImpostor);
  93327. }
  93328. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  93329. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  93330. }).forEach(function (obj) {
  93331. obj.callback(_this, otherImpostor);
  93332. });
  93333. }
  93334. };
  93335. //sanity check!
  93336. if (!this.object) {
  93337. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  93338. return;
  93339. }
  93340. //legacy support for old syntax.
  93341. if (!this._scene && object.getScene) {
  93342. this._scene = object.getScene();
  93343. }
  93344. if (!this._scene) {
  93345. return;
  93346. }
  93347. this._physicsEngine = this._scene.getPhysicsEngine();
  93348. if (!this._physicsEngine) {
  93349. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  93350. }
  93351. else {
  93352. //set the object's quaternion, if not set
  93353. if (!this.object.rotationQuaternion) {
  93354. if (this.object.rotation) {
  93355. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  93356. }
  93357. else {
  93358. this.object.rotationQuaternion = new BABYLON.Quaternion();
  93359. }
  93360. }
  93361. //default options params
  93362. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  93363. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  93364. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  93365. this._joints = [];
  93366. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  93367. if (!this.object.parent || this._options.ignoreParent) {
  93368. this._init();
  93369. }
  93370. else if (this.object.parent.physicsImpostor) {
  93371. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  93372. }
  93373. }
  93374. }
  93375. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  93376. get: function () {
  93377. return this._isDisposed;
  93378. },
  93379. enumerable: true,
  93380. configurable: true
  93381. });
  93382. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  93383. get: function () {
  93384. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  93385. },
  93386. set: function (value) {
  93387. this.setMass(value);
  93388. },
  93389. enumerable: true,
  93390. configurable: true
  93391. });
  93392. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  93393. get: function () {
  93394. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  93395. },
  93396. set: function (value) {
  93397. if (!this._physicsEngine) {
  93398. return;
  93399. }
  93400. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  93401. },
  93402. enumerable: true,
  93403. configurable: true
  93404. });
  93405. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  93406. get: function () {
  93407. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  93408. },
  93409. set: function (value) {
  93410. if (!this._physicsEngine) {
  93411. return;
  93412. }
  93413. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  93414. },
  93415. enumerable: true,
  93416. configurable: true
  93417. });
  93418. /**
  93419. * This function will completly initialize this impostor.
  93420. * It will create a new body - but only if this mesh has no parent.
  93421. * If it has, this impostor will not be used other than to define the impostor
  93422. * of the child mesh.
  93423. * @hidden
  93424. */
  93425. PhysicsImpostor.prototype._init = function () {
  93426. if (!this._physicsEngine) {
  93427. return;
  93428. }
  93429. this._physicsEngine.removeImpostor(this);
  93430. this.physicsBody = null;
  93431. this._parent = this._parent || this._getPhysicsParent();
  93432. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  93433. this._physicsEngine.addImpostor(this);
  93434. }
  93435. };
  93436. PhysicsImpostor.prototype._getPhysicsParent = function () {
  93437. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  93438. var parentMesh = this.object.parent;
  93439. return parentMesh.physicsImpostor;
  93440. }
  93441. return null;
  93442. };
  93443. /**
  93444. * Should a new body be generated.
  93445. */
  93446. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  93447. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  93448. };
  93449. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  93450. this.forceUpdate();
  93451. };
  93452. /**
  93453. * Force a regeneration of this or the parent's impostor's body.
  93454. * Use under cautious - This will remove all joints already implemented.
  93455. */
  93456. PhysicsImpostor.prototype.forceUpdate = function () {
  93457. this._init();
  93458. if (this.parent && !this._options.ignoreParent) {
  93459. this.parent.forceUpdate();
  93460. }
  93461. };
  93462. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  93463. /*public get mesh(): AbstractMesh {
  93464. return this._mesh;
  93465. }*/
  93466. /**
  93467. * Gets the body that holds this impostor. Either its own, or its parent.
  93468. */
  93469. get: function () {
  93470. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  93471. },
  93472. /**
  93473. * Set the physics body. Used mainly by the physics engine/plugin
  93474. */
  93475. set: function (physicsBody) {
  93476. if (this._physicsBody && this._physicsEngine) {
  93477. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  93478. }
  93479. this._physicsBody = physicsBody;
  93480. this.resetUpdateFlags();
  93481. },
  93482. enumerable: true,
  93483. configurable: true
  93484. });
  93485. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  93486. get: function () {
  93487. return !this._options.ignoreParent && this._parent ? this._parent : null;
  93488. },
  93489. set: function (value) {
  93490. this._parent = value;
  93491. },
  93492. enumerable: true,
  93493. configurable: true
  93494. });
  93495. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  93496. this._bodyUpdateRequired = false;
  93497. };
  93498. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  93499. if (this.object.getBoundingInfo) {
  93500. var q = this.object.rotationQuaternion;
  93501. //reset rotation
  93502. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  93503. //calculate the world matrix with no rotation
  93504. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  93505. var boundingInfo = this.object.getBoundingInfo();
  93506. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  93507. //bring back the rotation
  93508. this.object.rotationQuaternion = q;
  93509. //calculate the world matrix with the new rotation
  93510. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  93511. return size;
  93512. }
  93513. else {
  93514. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  93515. }
  93516. };
  93517. PhysicsImpostor.prototype.getObjectCenter = function () {
  93518. if (this.object.getBoundingInfo) {
  93519. var boundingInfo = this.object.getBoundingInfo();
  93520. return boundingInfo.boundingBox.centerWorld;
  93521. }
  93522. else {
  93523. return this.object.position;
  93524. }
  93525. };
  93526. /**
  93527. * Get a specific parametes from the options parameter.
  93528. */
  93529. PhysicsImpostor.prototype.getParam = function (paramName) {
  93530. return this._options[paramName];
  93531. };
  93532. /**
  93533. * Sets a specific parameter in the options given to the physics plugin
  93534. */
  93535. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  93536. this._options[paramName] = value;
  93537. this._bodyUpdateRequired = true;
  93538. };
  93539. /**
  93540. * Specifically change the body's mass option. Won't recreate the physics body object
  93541. */
  93542. PhysicsImpostor.prototype.setMass = function (mass) {
  93543. if (this.getParam("mass") !== mass) {
  93544. this.setParam("mass", mass);
  93545. }
  93546. if (this._physicsEngine) {
  93547. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  93548. }
  93549. };
  93550. PhysicsImpostor.prototype.getLinearVelocity = function () {
  93551. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  93552. };
  93553. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  93554. if (this._physicsEngine) {
  93555. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  93556. }
  93557. };
  93558. PhysicsImpostor.prototype.getAngularVelocity = function () {
  93559. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  93560. };
  93561. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  93562. if (this._physicsEngine) {
  93563. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  93564. }
  93565. };
  93566. /**
  93567. * Execute a function with the physics plugin native code.
  93568. * Provide a function the will have two variables - the world object and the physics body object.
  93569. */
  93570. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  93571. if (this._physicsEngine) {
  93572. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  93573. }
  93574. };
  93575. /**
  93576. * Register a function that will be executed before the physics world is stepping forward.
  93577. */
  93578. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  93579. this._onBeforePhysicsStepCallbacks.push(func);
  93580. };
  93581. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  93582. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  93583. if (index > -1) {
  93584. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  93585. }
  93586. else {
  93587. BABYLON.Tools.Warn("Function to remove was not found");
  93588. }
  93589. };
  93590. /**
  93591. * Register a function that will be executed after the physics step
  93592. */
  93593. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  93594. this._onAfterPhysicsStepCallbacks.push(func);
  93595. };
  93596. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  93597. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  93598. if (index > -1) {
  93599. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  93600. }
  93601. else {
  93602. BABYLON.Tools.Warn("Function to remove was not found");
  93603. }
  93604. };
  93605. /**
  93606. * register a function that will be executed when this impostor collides against a different body.
  93607. */
  93608. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  93609. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  93610. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  93611. };
  93612. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  93613. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  93614. var index = -1;
  93615. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  93616. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  93617. // chcek the arrays match
  93618. var sameList = cbDef.otherImpostors.every(function (impostor) {
  93619. return collidedAgainstList.indexOf(impostor) > -1;
  93620. });
  93621. if (sameList) {
  93622. index = idx;
  93623. }
  93624. return sameList;
  93625. }
  93626. return false;
  93627. });
  93628. if (found) {
  93629. this._onPhysicsCollideCallbacks.splice(index, 1);
  93630. }
  93631. else {
  93632. BABYLON.Tools.Warn("Function to remove was not found");
  93633. }
  93634. };
  93635. PhysicsImpostor.prototype.getParentsRotation = function () {
  93636. var parent = this.object.parent;
  93637. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  93638. while (parent) {
  93639. if (parent.rotationQuaternion) {
  93640. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  93641. }
  93642. else {
  93643. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  93644. }
  93645. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  93646. parent = parent.parent;
  93647. }
  93648. return this._tmpQuat;
  93649. };
  93650. /**
  93651. * Apply a force
  93652. */
  93653. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  93654. if (this._physicsEngine) {
  93655. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  93656. }
  93657. return this;
  93658. };
  93659. /**
  93660. * Apply an impulse
  93661. */
  93662. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  93663. if (this._physicsEngine) {
  93664. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  93665. }
  93666. return this;
  93667. };
  93668. /**
  93669. * A help function to create a joint.
  93670. */
  93671. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  93672. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  93673. this.addJoint(otherImpostor, joint);
  93674. return this;
  93675. };
  93676. /**
  93677. * Add a joint to this impostor with a different impostor.
  93678. */
  93679. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  93680. this._joints.push({
  93681. otherImpostor: otherImpostor,
  93682. joint: joint
  93683. });
  93684. if (this._physicsEngine) {
  93685. this._physicsEngine.addJoint(this, otherImpostor, joint);
  93686. }
  93687. return this;
  93688. };
  93689. /**
  93690. * Will keep this body still, in a sleep mode.
  93691. */
  93692. PhysicsImpostor.prototype.sleep = function () {
  93693. if (this._physicsEngine) {
  93694. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  93695. }
  93696. return this;
  93697. };
  93698. /**
  93699. * Wake the body up.
  93700. */
  93701. PhysicsImpostor.prototype.wakeUp = function () {
  93702. if (this._physicsEngine) {
  93703. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  93704. }
  93705. return this;
  93706. };
  93707. PhysicsImpostor.prototype.clone = function (newObject) {
  93708. if (!newObject)
  93709. return null;
  93710. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  93711. };
  93712. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  93713. var _this = this;
  93714. //no dispose if no physics engine is available.
  93715. if (!this._physicsEngine) {
  93716. return;
  93717. }
  93718. this._joints.forEach(function (j) {
  93719. if (_this._physicsEngine) {
  93720. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  93721. }
  93722. });
  93723. //dispose the physics body
  93724. this._physicsEngine.removeImpostor(this);
  93725. if (this.parent) {
  93726. this.parent.forceUpdate();
  93727. }
  93728. else {
  93729. /*this._object.getChildMeshes().forEach(function(mesh) {
  93730. if (mesh.physicsImpostor) {
  93731. if (disposeChildren) {
  93732. mesh.physicsImpostor.dispose();
  93733. mesh.physicsImpostor = null;
  93734. }
  93735. }
  93736. })*/
  93737. }
  93738. this._isDisposed = true;
  93739. };
  93740. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  93741. this._deltaPosition.copyFrom(position);
  93742. };
  93743. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  93744. if (!this._deltaRotation) {
  93745. this._deltaRotation = new BABYLON.Quaternion();
  93746. }
  93747. this._deltaRotation.copyFrom(rotation);
  93748. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  93749. };
  93750. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  93751. if (this._physicsEngine) {
  93752. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  93753. }
  93754. return this;
  93755. };
  93756. PhysicsImpostor.prototype.getRadius = function () {
  93757. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  93758. };
  93759. /**
  93760. * Sync a bone with this impostor
  93761. * @param bone The bone to sync to the impostor.
  93762. * @param boneMesh The mesh that the bone is influencing.
  93763. * @param jointPivot The pivot of the joint / bone in local space.
  93764. * @param distToJoint Optional distance from the impostor to the joint.
  93765. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93766. */
  93767. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  93768. var tempVec = PhysicsImpostor._tmpVecs[0];
  93769. var mesh = this.object;
  93770. if (mesh.rotationQuaternion) {
  93771. if (adjustRotation) {
  93772. var tempQuat = PhysicsImpostor._tmpQuat;
  93773. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  93774. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  93775. }
  93776. else {
  93777. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  93778. }
  93779. }
  93780. tempVec.x = 0;
  93781. tempVec.y = 0;
  93782. tempVec.z = 0;
  93783. if (jointPivot) {
  93784. tempVec.x = jointPivot.x;
  93785. tempVec.y = jointPivot.y;
  93786. tempVec.z = jointPivot.z;
  93787. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  93788. if (distToJoint === undefined || distToJoint === null) {
  93789. distToJoint = jointPivot.length();
  93790. }
  93791. tempVec.x *= distToJoint;
  93792. tempVec.y *= distToJoint;
  93793. tempVec.z *= distToJoint;
  93794. }
  93795. if (bone.getParent()) {
  93796. tempVec.addInPlace(mesh.getAbsolutePosition());
  93797. bone.setAbsolutePosition(tempVec, boneMesh);
  93798. }
  93799. else {
  93800. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  93801. boneMesh.position.x -= tempVec.x;
  93802. boneMesh.position.y -= tempVec.y;
  93803. boneMesh.position.z -= tempVec.z;
  93804. }
  93805. };
  93806. /**
  93807. * Sync impostor to a bone
  93808. * @param bone The bone that the impostor will be synced to.
  93809. * @param boneMesh The mesh that the bone is influencing.
  93810. * @param jointPivot The pivot of the joint / bone in local space.
  93811. * @param distToJoint Optional distance from the impostor to the joint.
  93812. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93813. * @param boneAxis Optional vector3 axis the bone is aligned with
  93814. */
  93815. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  93816. var mesh = this.object;
  93817. if (mesh.rotationQuaternion) {
  93818. if (adjustRotation) {
  93819. var tempQuat = PhysicsImpostor._tmpQuat;
  93820. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  93821. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  93822. }
  93823. else {
  93824. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  93825. }
  93826. }
  93827. var pos = PhysicsImpostor._tmpVecs[0];
  93828. var boneDir = PhysicsImpostor._tmpVecs[1];
  93829. if (!boneAxis) {
  93830. boneAxis = PhysicsImpostor._tmpVecs[2];
  93831. boneAxis.x = 0;
  93832. boneAxis.y = 1;
  93833. boneAxis.z = 0;
  93834. }
  93835. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  93836. bone.getAbsolutePositionToRef(boneMesh, pos);
  93837. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  93838. distToJoint = jointPivot.length();
  93839. }
  93840. if (distToJoint !== undefined && distToJoint !== null) {
  93841. pos.x += boneDir.x * distToJoint;
  93842. pos.y += boneDir.y * distToJoint;
  93843. pos.z += boneDir.z * distToJoint;
  93844. }
  93845. mesh.setAbsolutePosition(pos);
  93846. };
  93847. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  93848. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  93849. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  93850. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  93851. //Impostor types
  93852. PhysicsImpostor.NoImpostor = 0;
  93853. PhysicsImpostor.SphereImpostor = 1;
  93854. PhysicsImpostor.BoxImpostor = 2;
  93855. PhysicsImpostor.PlaneImpostor = 3;
  93856. PhysicsImpostor.MeshImpostor = 4;
  93857. PhysicsImpostor.CylinderImpostor = 7;
  93858. PhysicsImpostor.ParticleImpostor = 8;
  93859. PhysicsImpostor.HeightmapImpostor = 9;
  93860. return PhysicsImpostor;
  93861. }());
  93862. BABYLON.PhysicsImpostor = PhysicsImpostor;
  93863. })(BABYLON || (BABYLON = {}));
  93864. //# sourceMappingURL=babylon.physicsImpostor.js.map
  93865. var BABYLON;
  93866. (function (BABYLON) {
  93867. /**
  93868. * Class used to control physics engine
  93869. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93870. */
  93871. var PhysicsEngine = /** @class */ (function () {
  93872. /**
  93873. * Creates a new Physics Engine
  93874. * @param gravity defines the gravity vector used by the simulation
  93875. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  93876. */
  93877. function PhysicsEngine(gravity, _physicsPlugin) {
  93878. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  93879. this._physicsPlugin = _physicsPlugin;
  93880. this._impostors = [];
  93881. this._joints = [];
  93882. if (!this._physicsPlugin.isSupported()) {
  93883. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  93884. + "Please make sure it is included.");
  93885. }
  93886. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  93887. this.setGravity(gravity);
  93888. this.setTimeStep();
  93889. }
  93890. /**
  93891. * Sets the gravity vector used by the simulation
  93892. * @param gravity defines the gravity vector to use
  93893. */
  93894. PhysicsEngine.prototype.setGravity = function (gravity) {
  93895. this.gravity = gravity;
  93896. this._physicsPlugin.setGravity(this.gravity);
  93897. };
  93898. /**
  93899. * Set the time step of the physics engine.
  93900. * Default is 1/60.
  93901. * To slow it down, enter 1/600 for example.
  93902. * To speed it up, 1/30
  93903. * @param newTimeStep defines the new timestep to apply to this world.
  93904. */
  93905. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  93906. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  93907. this._physicsPlugin.setTimeStep(newTimeStep);
  93908. };
  93909. /**
  93910. * Get the time step of the physics engine.
  93911. * @returns the current time step
  93912. */
  93913. PhysicsEngine.prototype.getTimeStep = function () {
  93914. return this._physicsPlugin.getTimeStep();
  93915. };
  93916. /**
  93917. * Release all resources
  93918. */
  93919. PhysicsEngine.prototype.dispose = function () {
  93920. this._impostors.forEach(function (impostor) {
  93921. impostor.dispose();
  93922. });
  93923. this._physicsPlugin.dispose();
  93924. };
  93925. /**
  93926. * Gets the name of the current physics plugin
  93927. * @returns the name of the plugin
  93928. */
  93929. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  93930. return this._physicsPlugin.name;
  93931. };
  93932. /**
  93933. * Adding a new impostor for the impostor tracking.
  93934. * This will be done by the impostor itself.
  93935. * @param impostor the impostor to add
  93936. */
  93937. PhysicsEngine.prototype.addImpostor = function (impostor) {
  93938. impostor.uniqueId = this._impostors.push(impostor);
  93939. //if no parent, generate the body
  93940. if (!impostor.parent) {
  93941. this._physicsPlugin.generatePhysicsBody(impostor);
  93942. }
  93943. };
  93944. /**
  93945. * Remove an impostor from the engine.
  93946. * This impostor and its mesh will not longer be updated by the physics engine.
  93947. * @param impostor the impostor to remove
  93948. */
  93949. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  93950. var index = this._impostors.indexOf(impostor);
  93951. if (index > -1) {
  93952. var removed = this._impostors.splice(index, 1);
  93953. //Is it needed?
  93954. if (removed.length) {
  93955. //this will also remove it from the world.
  93956. removed[0].physicsBody = null;
  93957. }
  93958. }
  93959. };
  93960. /**
  93961. * Add a joint to the physics engine
  93962. * @param mainImpostor defines the main impostor to which the joint is added.
  93963. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  93964. * @param joint defines the joint that will connect both impostors.
  93965. */
  93966. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  93967. var impostorJoint = {
  93968. mainImpostor: mainImpostor,
  93969. connectedImpostor: connectedImpostor,
  93970. joint: joint
  93971. };
  93972. joint.physicsPlugin = this._physicsPlugin;
  93973. this._joints.push(impostorJoint);
  93974. this._physicsPlugin.generateJoint(impostorJoint);
  93975. };
  93976. /**
  93977. * Removes a joint from the simulation
  93978. * @param mainImpostor defines the impostor used with the joint
  93979. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  93980. * @param joint defines the joint to remove
  93981. */
  93982. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  93983. var matchingJoints = this._joints.filter(function (impostorJoint) {
  93984. return (impostorJoint.connectedImpostor === connectedImpostor
  93985. && impostorJoint.joint === joint
  93986. && impostorJoint.mainImpostor === mainImpostor);
  93987. });
  93988. if (matchingJoints.length) {
  93989. this._physicsPlugin.removeJoint(matchingJoints[0]);
  93990. //TODO remove it from the list as well
  93991. }
  93992. };
  93993. /**
  93994. * Called by the scene. No need to call it.
  93995. * @param delta defines the timespam between frames
  93996. */
  93997. PhysicsEngine.prototype._step = function (delta) {
  93998. var _this = this;
  93999. //check if any mesh has no body / requires an update
  94000. this._impostors.forEach(function (impostor) {
  94001. if (impostor.isBodyInitRequired()) {
  94002. _this._physicsPlugin.generatePhysicsBody(impostor);
  94003. }
  94004. });
  94005. if (delta > 0.1) {
  94006. delta = 0.1;
  94007. }
  94008. else if (delta <= 0) {
  94009. delta = 1.0 / 60.0;
  94010. }
  94011. this._physicsPlugin.executeStep(delta, this._impostors);
  94012. };
  94013. /**
  94014. * Gets the current plugin used to run the simulation
  94015. * @returns current plugin
  94016. */
  94017. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  94018. return this._physicsPlugin;
  94019. };
  94020. /**
  94021. * Gets the list of physic impostors
  94022. * @returns an array of PhysicsImpostor
  94023. */
  94024. PhysicsEngine.prototype.getImpostors = function () {
  94025. return this._impostors;
  94026. };
  94027. /**
  94028. * Gets the impostor for a physics enabled object
  94029. * @param object defines the object impersonated by the impostor
  94030. * @returns the PhysicsImpostor or null if not found
  94031. */
  94032. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  94033. for (var i = 0; i < this._impostors.length; ++i) {
  94034. if (this._impostors[i].object === object) {
  94035. return this._impostors[i];
  94036. }
  94037. }
  94038. return null;
  94039. };
  94040. /**
  94041. * Gets the impostor for a physics body object
  94042. * @param body defines physics body used by the impostor
  94043. * @returns the PhysicsImpostor or null if not found
  94044. */
  94045. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  94046. for (var i = 0; i < this._impostors.length; ++i) {
  94047. if (this._impostors[i].physicsBody === body) {
  94048. return this._impostors[i];
  94049. }
  94050. }
  94051. return null;
  94052. };
  94053. /**
  94054. * Global value used to control the smallest number supported by the simulation
  94055. */
  94056. PhysicsEngine.Epsilon = 0.001;
  94057. return PhysicsEngine;
  94058. }());
  94059. BABYLON.PhysicsEngine = PhysicsEngine;
  94060. })(BABYLON || (BABYLON = {}));
  94061. //# sourceMappingURL=babylon.physicsEngine.js.map
  94062. var BABYLON;
  94063. (function (BABYLON) {
  94064. var PhysicsHelper = /** @class */ (function () {
  94065. function PhysicsHelper(scene) {
  94066. this._scene = scene;
  94067. this._physicsEngine = this._scene.getPhysicsEngine();
  94068. if (!this._physicsEngine) {
  94069. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  94070. }
  94071. }
  94072. /**
  94073. * @param {Vector3} origin the origin of the explosion
  94074. * @param {number} radius the explosion radius
  94075. * @param {number} strength the explosion strength
  94076. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94077. */
  94078. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  94079. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94080. if (!this._physicsEngine) {
  94081. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  94082. return null;
  94083. }
  94084. var impostors = this._physicsEngine.getImpostors();
  94085. if (impostors.length === 0) {
  94086. return null;
  94087. }
  94088. var event = new PhysicsRadialExplosionEvent(this._scene);
  94089. impostors.forEach(function (impostor) {
  94090. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  94091. if (!impostorForceAndContactPoint) {
  94092. return;
  94093. }
  94094. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94095. });
  94096. event.dispose(false);
  94097. return event;
  94098. };
  94099. /**
  94100. * @param {Vector3} origin the origin of the explosion
  94101. * @param {number} radius the explosion radius
  94102. * @param {number} strength the explosion strength
  94103. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94104. */
  94105. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  94106. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94107. if (!this._physicsEngine) {
  94108. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94109. return null;
  94110. }
  94111. var impostors = this._physicsEngine.getImpostors();
  94112. if (impostors.length === 0) {
  94113. return null;
  94114. }
  94115. var event = new PhysicsRadialExplosionEvent(this._scene);
  94116. impostors.forEach(function (impostor) {
  94117. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  94118. if (!impostorForceAndContactPoint) {
  94119. return;
  94120. }
  94121. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94122. });
  94123. event.dispose(false);
  94124. return event;
  94125. };
  94126. /**
  94127. * @param {Vector3} origin the origin of the explosion
  94128. * @param {number} radius the explosion radius
  94129. * @param {number} strength the explosion strength
  94130. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94131. */
  94132. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  94133. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94134. if (!this._physicsEngine) {
  94135. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94136. return null;
  94137. }
  94138. var impostors = this._physicsEngine.getImpostors();
  94139. if (impostors.length === 0) {
  94140. return null;
  94141. }
  94142. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  94143. event.dispose(false);
  94144. return event;
  94145. };
  94146. /**
  94147. * @param {Vector3} origin the origin of the updraft
  94148. * @param {number} radius the radius of the updraft
  94149. * @param {number} strength the strength of the updraft
  94150. * @param {number} height the height of the updraft
  94151. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  94152. */
  94153. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  94154. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  94155. if (!this._physicsEngine) {
  94156. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94157. return null;
  94158. }
  94159. if (this._physicsEngine.getImpostors().length === 0) {
  94160. return null;
  94161. }
  94162. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  94163. event.dispose(false);
  94164. return event;
  94165. };
  94166. /**
  94167. * @param {Vector3} origin the of the vortex
  94168. * @param {number} radius the radius of the vortex
  94169. * @param {number} strength the strength of the vortex
  94170. * @param {number} height the height of the vortex
  94171. */
  94172. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  94173. if (!this._physicsEngine) {
  94174. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94175. return null;
  94176. }
  94177. if (this._physicsEngine.getImpostors().length === 0) {
  94178. return null;
  94179. }
  94180. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  94181. event.dispose(false);
  94182. return event;
  94183. };
  94184. return PhysicsHelper;
  94185. }());
  94186. BABYLON.PhysicsHelper = PhysicsHelper;
  94187. /***** Radial explosion *****/
  94188. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  94189. function PhysicsRadialExplosionEvent(scene) {
  94190. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  94191. this._rays = [];
  94192. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  94193. this._scene = scene;
  94194. }
  94195. /**
  94196. * Returns the data related to the radial explosion event (sphere & rays).
  94197. * @returns {PhysicsRadialExplosionEventData}
  94198. */
  94199. PhysicsRadialExplosionEvent.prototype.getData = function () {
  94200. this._dataFetched = true;
  94201. return {
  94202. sphere: this._sphere,
  94203. rays: this._rays,
  94204. };
  94205. };
  94206. /**
  94207. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  94208. * @param impostor
  94209. * @param {Vector3} origin the origin of the explosion
  94210. * @param {number} radius the explosion radius
  94211. * @param {number} strength the explosion strength
  94212. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  94213. * @returns {Nullable<PhysicsForceAndContactPoint>}
  94214. */
  94215. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  94216. if (impostor.mass === 0) {
  94217. return null;
  94218. }
  94219. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  94220. return null;
  94221. }
  94222. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  94223. return null;
  94224. }
  94225. var impostorObjectCenter = impostor.getObjectCenter();
  94226. var direction = impostorObjectCenter.subtract(origin);
  94227. var ray = new BABYLON.Ray(origin, direction, radius);
  94228. this._rays.push(ray);
  94229. var hit = ray.intersectsMesh(impostor.object);
  94230. var contactPoint = hit.pickedPoint;
  94231. if (!contactPoint) {
  94232. return null;
  94233. }
  94234. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  94235. if (distanceFromOrigin > radius) {
  94236. return null;
  94237. }
  94238. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  94239. ? strength
  94240. : strength * (1 - (distanceFromOrigin / radius));
  94241. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  94242. return { force: force, contactPoint: contactPoint };
  94243. };
  94244. /**
  94245. * Disposes the sphere.
  94246. * @param {bolean} force
  94247. */
  94248. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  94249. var _this = this;
  94250. if (force === void 0) { force = true; }
  94251. if (force) {
  94252. this._sphere.dispose();
  94253. }
  94254. else {
  94255. setTimeout(function () {
  94256. if (!_this._dataFetched) {
  94257. _this._sphere.dispose();
  94258. }
  94259. }, 0);
  94260. }
  94261. };
  94262. /*** Helpers ***/
  94263. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  94264. if (!this._sphere) {
  94265. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  94266. this._sphere.isVisible = false;
  94267. }
  94268. };
  94269. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  94270. var impostorObject = impostor.object;
  94271. this._prepareSphere();
  94272. this._sphere.position = origin;
  94273. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  94274. this._sphere._updateBoundingInfo();
  94275. this._sphere.computeWorldMatrix(true);
  94276. return this._sphere.intersectsMesh(impostorObject, true);
  94277. };
  94278. return PhysicsRadialExplosionEvent;
  94279. }());
  94280. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  94281. /***** Gravitational Field *****/
  94282. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  94283. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  94284. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94285. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94286. this._physicsHelper = physicsHelper;
  94287. this._scene = scene;
  94288. this._origin = origin;
  94289. this._radius = radius;
  94290. this._strength = strength;
  94291. this._falloff = falloff;
  94292. this._tickCallback = this._tick.bind(this);
  94293. }
  94294. /**
  94295. * Returns the data related to the gravitational field event (sphere).
  94296. * @returns {PhysicsGravitationalFieldEventData}
  94297. */
  94298. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  94299. this._dataFetched = true;
  94300. return {
  94301. sphere: this._sphere,
  94302. };
  94303. };
  94304. /**
  94305. * Enables the gravitational field.
  94306. */
  94307. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  94308. this._tickCallback.call(this);
  94309. this._scene.registerBeforeRender(this._tickCallback);
  94310. };
  94311. /**
  94312. * Disables the gravitational field.
  94313. */
  94314. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  94315. this._scene.unregisterBeforeRender(this._tickCallback);
  94316. };
  94317. /**
  94318. * Disposes the sphere.
  94319. * @param {bolean} force
  94320. */
  94321. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  94322. var _this = this;
  94323. if (force === void 0) { force = true; }
  94324. if (force) {
  94325. this._sphere.dispose();
  94326. }
  94327. else {
  94328. setTimeout(function () {
  94329. if (!_this._dataFetched) {
  94330. _this._sphere.dispose();
  94331. }
  94332. }, 0);
  94333. }
  94334. };
  94335. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  94336. // Since the params won't change, we fetch the event only once
  94337. if (this._sphere) {
  94338. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  94339. }
  94340. else {
  94341. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  94342. if (radialExplosionEvent) {
  94343. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  94344. }
  94345. }
  94346. };
  94347. return PhysicsGravitationalFieldEvent;
  94348. }());
  94349. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  94350. /***** Updraft *****/
  94351. var PhysicsUpdraftEvent = /** @class */ (function () {
  94352. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  94353. this._scene = _scene;
  94354. this._origin = _origin;
  94355. this._radius = _radius;
  94356. this._strength = _strength;
  94357. this._height = _height;
  94358. this._updraftMode = _updraftMode;
  94359. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  94360. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  94361. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  94362. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94363. this._physicsEngine = this._scene.getPhysicsEngine();
  94364. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  94365. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  94366. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  94367. this._originDirection = this._origin.subtract(this._originTop).normalize();
  94368. }
  94369. this._tickCallback = this._tick.bind(this);
  94370. }
  94371. /**
  94372. * Returns the data related to the updraft event (cylinder).
  94373. * @returns {PhysicsUpdraftEventData}
  94374. */
  94375. PhysicsUpdraftEvent.prototype.getData = function () {
  94376. this._dataFetched = true;
  94377. return {
  94378. cylinder: this._cylinder,
  94379. };
  94380. };
  94381. /**
  94382. * Enables the updraft.
  94383. */
  94384. PhysicsUpdraftEvent.prototype.enable = function () {
  94385. this._tickCallback.call(this);
  94386. this._scene.registerBeforeRender(this._tickCallback);
  94387. };
  94388. /**
  94389. * Disables the cortex.
  94390. */
  94391. PhysicsUpdraftEvent.prototype.disable = function () {
  94392. this._scene.unregisterBeforeRender(this._tickCallback);
  94393. };
  94394. /**
  94395. * Disposes the sphere.
  94396. * @param {bolean} force
  94397. */
  94398. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  94399. var _this = this;
  94400. if (force === void 0) { force = true; }
  94401. if (force) {
  94402. this._cylinder.dispose();
  94403. }
  94404. else {
  94405. setTimeout(function () {
  94406. if (!_this._dataFetched) {
  94407. _this._cylinder.dispose();
  94408. }
  94409. }, 0);
  94410. }
  94411. };
  94412. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  94413. if (impostor.mass === 0) {
  94414. return null;
  94415. }
  94416. if (!this._intersectsWithCylinder(impostor)) {
  94417. return null;
  94418. }
  94419. var impostorObjectCenter = impostor.getObjectCenter();
  94420. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  94421. var direction = this._originDirection;
  94422. }
  94423. else {
  94424. var direction = impostorObjectCenter.subtract(this._originTop);
  94425. }
  94426. var multiplier = this._strength * -1;
  94427. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  94428. return { force: force, contactPoint: impostorObjectCenter };
  94429. };
  94430. PhysicsUpdraftEvent.prototype._tick = function () {
  94431. var _this = this;
  94432. this._physicsEngine.getImpostors().forEach(function (impostor) {
  94433. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  94434. if (!impostorForceAndContactPoint) {
  94435. return;
  94436. }
  94437. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94438. });
  94439. };
  94440. /*** Helpers ***/
  94441. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  94442. if (!this._cylinder) {
  94443. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  94444. height: this._height,
  94445. diameter: this._radius * 2,
  94446. }, this._scene);
  94447. this._cylinder.isVisible = false;
  94448. }
  94449. };
  94450. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  94451. var impostorObject = impostor.object;
  94452. this._prepareCylinder();
  94453. this._cylinder.position = this._cylinderPosition;
  94454. return this._cylinder.intersectsMesh(impostorObject, true);
  94455. };
  94456. return PhysicsUpdraftEvent;
  94457. }());
  94458. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  94459. /***** Vortex *****/
  94460. var PhysicsVortexEvent = /** @class */ (function () {
  94461. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  94462. this._scene = _scene;
  94463. this._origin = _origin;
  94464. this._radius = _radius;
  94465. this._strength = _strength;
  94466. this._height = _height;
  94467. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  94468. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  94469. this._updraftMultiplier = 0.02;
  94470. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  94471. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94472. this._physicsEngine = this._scene.getPhysicsEngine();
  94473. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  94474. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  94475. this._tickCallback = this._tick.bind(this);
  94476. }
  94477. /**
  94478. * Returns the data related to the vortex event (cylinder).
  94479. * @returns {PhysicsVortexEventData}
  94480. */
  94481. PhysicsVortexEvent.prototype.getData = function () {
  94482. this._dataFetched = true;
  94483. return {
  94484. cylinder: this._cylinder,
  94485. };
  94486. };
  94487. /**
  94488. * Enables the vortex.
  94489. */
  94490. PhysicsVortexEvent.prototype.enable = function () {
  94491. this._tickCallback.call(this);
  94492. this._scene.registerBeforeRender(this._tickCallback);
  94493. };
  94494. /**
  94495. * Disables the cortex.
  94496. */
  94497. PhysicsVortexEvent.prototype.disable = function () {
  94498. this._scene.unregisterBeforeRender(this._tickCallback);
  94499. };
  94500. /**
  94501. * Disposes the sphere.
  94502. * @param {bolean} force
  94503. */
  94504. PhysicsVortexEvent.prototype.dispose = function (force) {
  94505. var _this = this;
  94506. if (force === void 0) { force = true; }
  94507. if (force) {
  94508. this._cylinder.dispose();
  94509. }
  94510. else {
  94511. setTimeout(function () {
  94512. if (!_this._dataFetched) {
  94513. _this._cylinder.dispose();
  94514. }
  94515. }, 0);
  94516. }
  94517. };
  94518. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  94519. if (impostor.mass === 0) {
  94520. return null;
  94521. }
  94522. if (!this._intersectsWithCylinder(impostor)) {
  94523. return null;
  94524. }
  94525. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  94526. return null;
  94527. }
  94528. var impostorObjectCenter = impostor.getObjectCenter();
  94529. 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)
  94530. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  94531. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  94532. var hit = ray.intersectsMesh(impostor.object);
  94533. var contactPoint = hit.pickedPoint;
  94534. if (!contactPoint) {
  94535. return null;
  94536. }
  94537. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  94538. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  94539. var directionToOrigin = contactPoint.normalize();
  94540. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  94541. directionToOrigin = directionToOrigin.negate();
  94542. }
  94543. // TODO: find a more physically based solution
  94544. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  94545. var forceX = directionToOrigin.x * this._strength / 8;
  94546. var forceY = directionToOrigin.y * this._updraftMultiplier;
  94547. var forceZ = directionToOrigin.z * this._strength / 8;
  94548. }
  94549. else {
  94550. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  94551. var forceY = this._originTop.y * this._updraftMultiplier;
  94552. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  94553. }
  94554. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  94555. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  94556. return { force: force, contactPoint: impostorObjectCenter };
  94557. };
  94558. PhysicsVortexEvent.prototype._tick = function () {
  94559. var _this = this;
  94560. this._physicsEngine.getImpostors().forEach(function (impostor) {
  94561. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  94562. if (!impostorForceAndContactPoint) {
  94563. return;
  94564. }
  94565. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94566. });
  94567. };
  94568. /*** Helpers ***/
  94569. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  94570. if (!this._cylinder) {
  94571. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  94572. height: this._height,
  94573. diameter: this._radius * 2,
  94574. }, this._scene);
  94575. this._cylinder.isVisible = false;
  94576. }
  94577. };
  94578. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  94579. var impostorObject = impostor.object;
  94580. this._prepareCylinder();
  94581. this._cylinder.position = this._cylinderPosition;
  94582. return this._cylinder.intersectsMesh(impostorObject, true);
  94583. };
  94584. return PhysicsVortexEvent;
  94585. }());
  94586. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  94587. /***** Enums *****/
  94588. /**
  94589. * The strenght of the force in correspondence to the distance of the affected object
  94590. */
  94591. var PhysicsRadialImpulseFalloff;
  94592. (function (PhysicsRadialImpulseFalloff) {
  94593. /** Defines that impulse is constant in strength across it's whole radius */
  94594. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  94595. /** DEfines that impulse gets weaker if it's further from the origin */
  94596. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  94597. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  94598. /**
  94599. * The strenght of the force in correspondence to the distance of the affected object
  94600. */
  94601. var PhysicsUpdraftMode;
  94602. (function (PhysicsUpdraftMode) {
  94603. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  94604. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  94605. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  94606. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  94607. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  94608. })(BABYLON || (BABYLON = {}));
  94609. //# sourceMappingURL=babylon.physicsHelper.js.map
  94610. var BABYLON;
  94611. (function (BABYLON) {
  94612. /** @hidden */
  94613. var CannonJSPlugin = /** @class */ (function () {
  94614. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  94615. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  94616. if (iterations === void 0) { iterations = 10; }
  94617. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  94618. this.name = "CannonJSPlugin";
  94619. this._physicsMaterials = new Array();
  94620. this._fixedTimeStep = 1 / 60;
  94621. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  94622. this.BJSCANNON = CANNON;
  94623. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  94624. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  94625. this._tmpPosition = BABYLON.Vector3.Zero();
  94626. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  94627. this._tmpUnityRotation = new BABYLON.Quaternion();
  94628. if (!this.isSupported()) {
  94629. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  94630. return;
  94631. }
  94632. this._extendNamespace();
  94633. this.world = new this.BJSCANNON.World();
  94634. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  94635. this.world.solver.iterations = iterations;
  94636. }
  94637. CannonJSPlugin.prototype.setGravity = function (gravity) {
  94638. this.world.gravity.copy(gravity);
  94639. };
  94640. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  94641. this._fixedTimeStep = timeStep;
  94642. };
  94643. CannonJSPlugin.prototype.getTimeStep = function () {
  94644. return this._fixedTimeStep;
  94645. };
  94646. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  94647. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  94648. };
  94649. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  94650. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  94651. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  94652. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  94653. };
  94654. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  94655. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  94656. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  94657. impostor.physicsBody.applyForce(impulse, worldPoint);
  94658. };
  94659. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  94660. //parent-child relationship. Does this impostor has a parent impostor?
  94661. if (impostor.parent) {
  94662. if (impostor.physicsBody) {
  94663. this.removePhysicsBody(impostor);
  94664. //TODO is that needed?
  94665. impostor.forceUpdate();
  94666. }
  94667. return;
  94668. }
  94669. //should a new body be created for this impostor?
  94670. if (impostor.isBodyInitRequired()) {
  94671. var shape = this._createShape(impostor);
  94672. //unregister events, if body is being changed
  94673. var oldBody = impostor.physicsBody;
  94674. if (oldBody) {
  94675. this.removePhysicsBody(impostor);
  94676. }
  94677. //create the body and material
  94678. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  94679. var bodyCreationObject = {
  94680. mass: impostor.getParam("mass"),
  94681. material: material
  94682. };
  94683. // A simple extend, in case native options were used.
  94684. var nativeOptions = impostor.getParam("nativeOptions");
  94685. for (var key in nativeOptions) {
  94686. if (nativeOptions.hasOwnProperty(key)) {
  94687. bodyCreationObject[key] = nativeOptions[key];
  94688. }
  94689. }
  94690. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  94691. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  94692. this.world.addEventListener("preStep", impostor.beforeStep);
  94693. this.world.addEventListener("postStep", impostor.afterStep);
  94694. impostor.physicsBody.addShape(shape);
  94695. this.world.add(impostor.physicsBody);
  94696. //try to keep the body moving in the right direction by taking old properties.
  94697. //Should be tested!
  94698. if (oldBody) {
  94699. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  94700. impostor.physicsBody[param].copy(oldBody[param]);
  94701. });
  94702. }
  94703. this._processChildMeshes(impostor);
  94704. }
  94705. //now update the body's transformation
  94706. this._updatePhysicsBodyTransformation(impostor);
  94707. };
  94708. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  94709. var _this = this;
  94710. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  94711. var currentRotation = mainImpostor.object.rotationQuaternion;
  94712. if (meshChildren.length) {
  94713. var processMesh = function (localPosition, mesh) {
  94714. if (!currentRotation || !mesh.rotationQuaternion) {
  94715. return;
  94716. }
  94717. var childImpostor = mesh.getPhysicsImpostor();
  94718. if (childImpostor) {
  94719. var parent = childImpostor.parent;
  94720. if (parent !== mainImpostor) {
  94721. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  94722. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  94723. if (childImpostor.physicsBody) {
  94724. _this.removePhysicsBody(childImpostor);
  94725. childImpostor.physicsBody = null;
  94726. }
  94727. childImpostor.parent = mainImpostor;
  94728. childImpostor.resetUpdateFlags();
  94729. 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));
  94730. //Add the mass of the children.
  94731. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  94732. }
  94733. }
  94734. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  94735. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  94736. };
  94737. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  94738. }
  94739. };
  94740. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  94741. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  94742. this.world.removeEventListener("preStep", impostor.beforeStep);
  94743. this.world.removeEventListener("postStep", impostor.afterStep);
  94744. this.world.remove(impostor.physicsBody);
  94745. };
  94746. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  94747. var mainBody = impostorJoint.mainImpostor.physicsBody;
  94748. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  94749. if (!mainBody || !connectedBody) {
  94750. return;
  94751. }
  94752. var constraint;
  94753. var jointData = impostorJoint.joint.jointData;
  94754. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  94755. var constraintData = {
  94756. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  94757. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  94758. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  94759. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  94760. maxForce: jointData.nativeParams.maxForce,
  94761. collideConnected: !!jointData.collision
  94762. };
  94763. switch (impostorJoint.joint.type) {
  94764. case BABYLON.PhysicsJoint.HingeJoint:
  94765. case BABYLON.PhysicsJoint.Hinge2Joint:
  94766. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  94767. break;
  94768. case BABYLON.PhysicsJoint.DistanceJoint:
  94769. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  94770. break;
  94771. case BABYLON.PhysicsJoint.SpringJoint:
  94772. var springData = jointData;
  94773. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  94774. restLength: springData.length,
  94775. stiffness: springData.stiffness,
  94776. damping: springData.damping,
  94777. localAnchorA: constraintData.pivotA,
  94778. localAnchorB: constraintData.pivotB
  94779. });
  94780. break;
  94781. case BABYLON.PhysicsJoint.LockJoint:
  94782. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  94783. break;
  94784. case BABYLON.PhysicsJoint.PointToPointJoint:
  94785. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  94786. default:
  94787. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  94788. break;
  94789. }
  94790. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  94791. constraint.collideConnected = !!jointData.collision;
  94792. impostorJoint.joint.physicsJoint = constraint;
  94793. //don't add spring as constraint, as it is not one.
  94794. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94795. this.world.addConstraint(constraint);
  94796. }
  94797. else {
  94798. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  94799. constraint.applyForce();
  94800. };
  94801. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94802. }
  94803. };
  94804. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  94805. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94806. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  94807. }
  94808. else {
  94809. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94810. }
  94811. };
  94812. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  94813. var index;
  94814. var mat;
  94815. for (index = 0; index < this._physicsMaterials.length; index++) {
  94816. mat = this._physicsMaterials[index];
  94817. if (mat.friction === friction && mat.restitution === restitution) {
  94818. return mat;
  94819. }
  94820. }
  94821. var currentMat = new this.BJSCANNON.Material(name);
  94822. currentMat.friction = friction;
  94823. currentMat.restitution = restitution;
  94824. this._physicsMaterials.push(currentMat);
  94825. return currentMat;
  94826. };
  94827. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  94828. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  94829. };
  94830. CannonJSPlugin.prototype._createShape = function (impostor) {
  94831. var object = impostor.object;
  94832. var returnValue;
  94833. var extendSize = impostor.getObjectExtendSize();
  94834. switch (impostor.type) {
  94835. case BABYLON.PhysicsImpostor.SphereImpostor:
  94836. var radiusX = extendSize.x;
  94837. var radiusY = extendSize.y;
  94838. var radiusZ = extendSize.z;
  94839. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  94840. break;
  94841. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  94842. case BABYLON.PhysicsImpostor.CylinderImpostor:
  94843. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  94844. break;
  94845. case BABYLON.PhysicsImpostor.BoxImpostor:
  94846. var box = extendSize.scale(0.5);
  94847. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  94848. break;
  94849. case BABYLON.PhysicsImpostor.PlaneImpostor:
  94850. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  94851. returnValue = new this.BJSCANNON.Plane();
  94852. break;
  94853. case BABYLON.PhysicsImpostor.MeshImpostor:
  94854. // should transform the vertex data to world coordinates!!
  94855. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  94856. var rawFaces = object.getIndices ? object.getIndices() : [];
  94857. if (!rawVerts)
  94858. return;
  94859. // get only scale! so the object could transform correctly.
  94860. var oldPosition = object.position.clone();
  94861. var oldRotation = object.rotation && object.rotation.clone();
  94862. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  94863. object.position.copyFromFloats(0, 0, 0);
  94864. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94865. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94866. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94867. var transform = object.computeWorldMatrix(true);
  94868. // convert rawVerts to object space
  94869. var temp = new Array();
  94870. var index;
  94871. for (index = 0; index < rawVerts.length; index += 3) {
  94872. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  94873. }
  94874. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  94875. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  94876. //now set back the transformation!
  94877. object.position.copyFrom(oldPosition);
  94878. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  94879. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  94880. break;
  94881. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  94882. var oldPosition2 = object.position.clone();
  94883. var oldRotation2 = object.rotation && object.rotation.clone();
  94884. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  94885. object.position.copyFromFloats(0, 0, 0);
  94886. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94887. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94888. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94889. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  94890. returnValue = this._createHeightmap(object);
  94891. object.position.copyFrom(oldPosition2);
  94892. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  94893. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  94894. object.computeWorldMatrix(true);
  94895. break;
  94896. case BABYLON.PhysicsImpostor.ParticleImpostor:
  94897. returnValue = new this.BJSCANNON.Particle();
  94898. break;
  94899. }
  94900. return returnValue;
  94901. };
  94902. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  94903. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  94904. var transform = object.computeWorldMatrix(true);
  94905. // convert rawVerts to object space
  94906. var temp = new Array();
  94907. var index;
  94908. for (index = 0; index < pos.length; index += 3) {
  94909. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  94910. }
  94911. pos = temp;
  94912. var matrix = new Array();
  94913. //For now pointDepth will not be used and will be automatically calculated.
  94914. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  94915. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  94916. var boundingInfo = object.getBoundingInfo();
  94917. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  94918. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  94919. var elementSize = dim * 2 / arraySize;
  94920. for (var i = 0; i < pos.length; i = i + 3) {
  94921. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  94922. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  94923. var y = -pos[i + 2] + minY;
  94924. if (!matrix[x]) {
  94925. matrix[x] = [];
  94926. }
  94927. if (!matrix[x][z]) {
  94928. matrix[x][z] = y;
  94929. }
  94930. matrix[x][z] = Math.max(y, matrix[x][z]);
  94931. }
  94932. for (var x = 0; x <= arraySize; ++x) {
  94933. if (!matrix[x]) {
  94934. var loc = 1;
  94935. while (!matrix[(x + loc) % arraySize]) {
  94936. loc++;
  94937. }
  94938. matrix[x] = matrix[(x + loc) % arraySize].slice();
  94939. //console.log("missing x", x);
  94940. }
  94941. for (var z = 0; z <= arraySize; ++z) {
  94942. if (!matrix[x][z]) {
  94943. var loc = 1;
  94944. var newValue;
  94945. while (newValue === undefined) {
  94946. newValue = matrix[x][(z + loc++) % arraySize];
  94947. }
  94948. matrix[x][z] = newValue;
  94949. }
  94950. }
  94951. }
  94952. var shape = new this.BJSCANNON.Heightfield(matrix, {
  94953. elementSize: elementSize
  94954. });
  94955. //For future reference, needed for body transformation
  94956. shape.minY = minY;
  94957. return shape;
  94958. };
  94959. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  94960. var object = impostor.object;
  94961. //make sure it is updated...
  94962. object.computeWorldMatrix && object.computeWorldMatrix(true);
  94963. // The delta between the mesh position and the mesh bounding box center
  94964. var bInfo = object.getBoundingInfo();
  94965. if (!bInfo)
  94966. return;
  94967. var center = impostor.getObjectCenter();
  94968. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  94969. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  94970. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  94971. this._tmpPosition.copyFrom(center);
  94972. var quaternion = object.rotationQuaternion;
  94973. if (!quaternion) {
  94974. return;
  94975. }
  94976. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  94977. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  94978. //-90 DEG in X, precalculated
  94979. quaternion = quaternion.multiply(this._minus90X);
  94980. //Invert! (Precalculated, 90 deg in X)
  94981. //No need to clone. this will never change.
  94982. impostor.setDeltaRotation(this._plus90X);
  94983. }
  94984. //If it is a heightfield, if should be centered.
  94985. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  94986. var mesh = object;
  94987. var boundingInfo = mesh.getBoundingInfo();
  94988. //calculate the correct body position:
  94989. var rotationQuaternion = mesh.rotationQuaternion;
  94990. mesh.rotationQuaternion = this._tmpUnityRotation;
  94991. mesh.computeWorldMatrix(true);
  94992. //get original center with no rotation
  94993. var c = center.clone();
  94994. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  94995. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  94996. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  94997. mesh.setPreTransformMatrix(p);
  94998. mesh.computeWorldMatrix(true);
  94999. //calculate the translation
  95000. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  95001. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  95002. //add it inverted to the delta
  95003. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  95004. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  95005. //rotation is back
  95006. mesh.rotationQuaternion = rotationQuaternion;
  95007. mesh.setPreTransformMatrix(oldPivot);
  95008. mesh.computeWorldMatrix(true);
  95009. }
  95010. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  95011. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  95012. //this._tmpPosition.copyFrom(object.position);
  95013. }
  95014. impostor.setDeltaPosition(this._tmpDeltaPosition);
  95015. //Now update the impostor object
  95016. impostor.physicsBody.position.copy(this._tmpPosition);
  95017. impostor.physicsBody.quaternion.copy(quaternion);
  95018. };
  95019. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  95020. impostor.object.position.copyFrom(impostor.physicsBody.position);
  95021. if (impostor.object.rotationQuaternion) {
  95022. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  95023. }
  95024. };
  95025. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  95026. impostor.physicsBody.position.copy(newPosition);
  95027. impostor.physicsBody.quaternion.copy(newRotation);
  95028. };
  95029. CannonJSPlugin.prototype.isSupported = function () {
  95030. return this.BJSCANNON !== undefined;
  95031. };
  95032. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  95033. impostor.physicsBody.velocity.copy(velocity);
  95034. };
  95035. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  95036. impostor.physicsBody.angularVelocity.copy(velocity);
  95037. };
  95038. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  95039. var v = impostor.physicsBody.velocity;
  95040. if (!v) {
  95041. return null;
  95042. }
  95043. return new BABYLON.Vector3(v.x, v.y, v.z);
  95044. };
  95045. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  95046. var v = impostor.physicsBody.angularVelocity;
  95047. if (!v) {
  95048. return null;
  95049. }
  95050. return new BABYLON.Vector3(v.x, v.y, v.z);
  95051. };
  95052. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  95053. impostor.physicsBody.mass = mass;
  95054. impostor.physicsBody.updateMassProperties();
  95055. };
  95056. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  95057. return impostor.physicsBody.mass;
  95058. };
  95059. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  95060. return impostor.physicsBody.material.friction;
  95061. };
  95062. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  95063. impostor.physicsBody.material.friction = friction;
  95064. };
  95065. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  95066. return impostor.physicsBody.material.restitution;
  95067. };
  95068. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  95069. impostor.physicsBody.material.restitution = restitution;
  95070. };
  95071. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  95072. impostor.physicsBody.sleep();
  95073. };
  95074. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  95075. impostor.physicsBody.wakeUp();
  95076. };
  95077. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  95078. joint.physicsJoint.distance = maxDistance;
  95079. };
  95080. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  95081. // if (!motorIndex) {
  95082. // joint.physicsJoint.enableMotor();
  95083. // }
  95084. // }
  95085. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  95086. // if (!motorIndex) {
  95087. // joint.physicsJoint.disableMotor();
  95088. // }
  95089. // }
  95090. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  95091. if (!motorIndex) {
  95092. joint.physicsJoint.enableMotor();
  95093. joint.physicsJoint.setMotorSpeed(speed);
  95094. if (maxForce) {
  95095. this.setLimit(joint, maxForce);
  95096. }
  95097. }
  95098. };
  95099. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  95100. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  95101. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  95102. };
  95103. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  95104. var body = impostor.physicsBody;
  95105. mesh.position.x = body.position.x;
  95106. mesh.position.y = body.position.y;
  95107. mesh.position.z = body.position.z;
  95108. if (mesh.rotationQuaternion) {
  95109. mesh.rotationQuaternion.x = body.quaternion.x;
  95110. mesh.rotationQuaternion.y = body.quaternion.y;
  95111. mesh.rotationQuaternion.z = body.quaternion.z;
  95112. mesh.rotationQuaternion.w = body.quaternion.w;
  95113. }
  95114. };
  95115. CannonJSPlugin.prototype.getRadius = function (impostor) {
  95116. var shape = impostor.physicsBody.shapes[0];
  95117. return shape.boundingSphereRadius;
  95118. };
  95119. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  95120. var shape = impostor.physicsBody.shapes[0];
  95121. result.x = shape.halfExtents.x * 2;
  95122. result.y = shape.halfExtents.y * 2;
  95123. result.z = shape.halfExtents.z * 2;
  95124. };
  95125. CannonJSPlugin.prototype.dispose = function () {
  95126. };
  95127. CannonJSPlugin.prototype._extendNamespace = function () {
  95128. //this will force cannon to execute at least one step when using interpolation
  95129. var step_tmp1 = new this.BJSCANNON.Vec3();
  95130. var Engine = this.BJSCANNON;
  95131. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  95132. maxSubSteps = maxSubSteps || 10;
  95133. timeSinceLastCalled = timeSinceLastCalled || 0;
  95134. if (timeSinceLastCalled === 0) {
  95135. this.internalStep(dt);
  95136. this.time += dt;
  95137. }
  95138. else {
  95139. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  95140. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  95141. var t0 = performance.now();
  95142. for (var i = 0; i !== internalSteps; i++) {
  95143. this.internalStep(dt);
  95144. if (performance.now() - t0 > dt * 1000) {
  95145. break;
  95146. }
  95147. }
  95148. this.time += timeSinceLastCalled;
  95149. var h = this.time % dt;
  95150. var h_div_dt = h / dt;
  95151. var interpvelo = step_tmp1;
  95152. var bodies = this.bodies;
  95153. for (var j = 0; j !== bodies.length; j++) {
  95154. var b = bodies[j];
  95155. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  95156. b.position.vsub(b.previousPosition, interpvelo);
  95157. interpvelo.scale(h_div_dt, interpvelo);
  95158. b.position.vadd(interpvelo, b.interpolatedPosition);
  95159. }
  95160. else {
  95161. b.interpolatedPosition.copy(b.position);
  95162. b.interpolatedQuaternion.copy(b.quaternion);
  95163. }
  95164. }
  95165. }
  95166. };
  95167. };
  95168. return CannonJSPlugin;
  95169. }());
  95170. BABYLON.CannonJSPlugin = CannonJSPlugin;
  95171. })(BABYLON || (BABYLON = {}));
  95172. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  95173. var BABYLON;
  95174. (function (BABYLON) {
  95175. /** @hidden */
  95176. var OimoJSPlugin = /** @class */ (function () {
  95177. function OimoJSPlugin(iterations) {
  95178. this.name = "OimoJSPlugin";
  95179. this._tmpImpostorsArray = [];
  95180. this._tmpPositionVector = BABYLON.Vector3.Zero();
  95181. this.BJSOIMO = OIMO;
  95182. this.world = new this.BJSOIMO.World({
  95183. iterations: iterations
  95184. });
  95185. this.world.clear();
  95186. }
  95187. OimoJSPlugin.prototype.setGravity = function (gravity) {
  95188. this.world.gravity.copy(gravity);
  95189. };
  95190. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  95191. this.world.timeStep = timeStep;
  95192. };
  95193. OimoJSPlugin.prototype.getTimeStep = function () {
  95194. return this.world.timeStep;
  95195. };
  95196. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  95197. var _this = this;
  95198. impostors.forEach(function (impostor) {
  95199. impostor.beforeStep();
  95200. });
  95201. this.world.step();
  95202. impostors.forEach(function (impostor) {
  95203. impostor.afterStep();
  95204. //update the ordered impostors array
  95205. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  95206. });
  95207. //check for collisions
  95208. var contact = this.world.contacts;
  95209. while (contact !== null) {
  95210. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  95211. contact = contact.next;
  95212. continue;
  95213. }
  95214. //is this body colliding with any other? get the impostor
  95215. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  95216. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  95217. if (!mainImpostor || !collidingImpostor) {
  95218. contact = contact.next;
  95219. continue;
  95220. }
  95221. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  95222. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  95223. contact = contact.next;
  95224. }
  95225. };
  95226. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  95227. var mass = impostor.physicsBody.mass;
  95228. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  95229. };
  95230. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  95231. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  95232. this.applyImpulse(impostor, force, contactPoint);
  95233. };
  95234. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  95235. var _this = this;
  95236. //parent-child relationship. Does this impostor has a parent impostor?
  95237. if (impostor.parent) {
  95238. if (impostor.physicsBody) {
  95239. this.removePhysicsBody(impostor);
  95240. //TODO is that needed?
  95241. impostor.forceUpdate();
  95242. }
  95243. return;
  95244. }
  95245. if (impostor.isBodyInitRequired()) {
  95246. var bodyConfig = {
  95247. name: impostor.uniqueId,
  95248. //Oimo must have mass, also for static objects.
  95249. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  95250. size: [],
  95251. type: [],
  95252. pos: [],
  95253. posShape: [],
  95254. rot: [],
  95255. rotShape: [],
  95256. move: impostor.getParam("mass") !== 0,
  95257. density: impostor.getParam("mass"),
  95258. friction: impostor.getParam("friction"),
  95259. restitution: impostor.getParam("restitution"),
  95260. //Supporting older versions of Oimo
  95261. world: this.world
  95262. };
  95263. var impostors = [impostor];
  95264. var addToArray = function (parent) {
  95265. if (!parent.getChildMeshes)
  95266. return;
  95267. parent.getChildMeshes().forEach(function (m) {
  95268. if (m.physicsImpostor) {
  95269. impostors.push(m.physicsImpostor);
  95270. //m.physicsImpostor._init();
  95271. }
  95272. });
  95273. };
  95274. addToArray(impostor.object);
  95275. var checkWithEpsilon_1 = function (value) {
  95276. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  95277. };
  95278. var globalQuaternion_1 = new BABYLON.Quaternion();
  95279. impostors.forEach(function (i) {
  95280. if (!i.object.rotationQuaternion) {
  95281. return;
  95282. }
  95283. //get the correct bounding box
  95284. var oldQuaternion = i.object.rotationQuaternion;
  95285. globalQuaternion_1 = oldQuaternion.clone();
  95286. var rot = oldQuaternion.toEulerAngles();
  95287. var extendSize = i.getObjectExtendSize();
  95288. var radToDeg = 57.295779513082320876;
  95289. if (i === impostor) {
  95290. var center = impostor.getObjectCenter();
  95291. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  95292. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  95293. //Can also use Array.prototype.push.apply
  95294. bodyConfig.pos.push(center.x);
  95295. bodyConfig.pos.push(center.y);
  95296. bodyConfig.pos.push(center.z);
  95297. bodyConfig.posShape.push(0, 0, 0);
  95298. //tmp solution
  95299. bodyConfig.rot.push(0);
  95300. bodyConfig.rot.push(0);
  95301. bodyConfig.rot.push(0);
  95302. bodyConfig.rotShape.push(0, 0, 0);
  95303. }
  95304. else {
  95305. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  95306. bodyConfig.posShape.push(localPosition.x);
  95307. bodyConfig.posShape.push(localPosition.y);
  95308. bodyConfig.posShape.push(localPosition.z);
  95309. bodyConfig.pos.push(0, 0, 0);
  95310. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  95311. bodyConfig.rot.push(0);
  95312. bodyConfig.rot.push(0);
  95313. bodyConfig.rot.push(0);
  95314. bodyConfig.rotShape.push(rot.x * radToDeg);
  95315. bodyConfig.rotShape.push(rot.y * radToDeg);
  95316. bodyConfig.rotShape.push(rot.z * radToDeg);
  95317. }
  95318. // register mesh
  95319. switch (i.type) {
  95320. case BABYLON.PhysicsImpostor.ParticleImpostor:
  95321. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  95322. case BABYLON.PhysicsImpostor.SphereImpostor:
  95323. var radiusX = extendSize.x;
  95324. var radiusY = extendSize.y;
  95325. var radiusZ = extendSize.z;
  95326. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  95327. bodyConfig.type.push('sphere');
  95328. //due to the way oimo works with compounds, add 3 times
  95329. bodyConfig.size.push(size);
  95330. bodyConfig.size.push(size);
  95331. bodyConfig.size.push(size);
  95332. break;
  95333. case BABYLON.PhysicsImpostor.CylinderImpostor:
  95334. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  95335. var sizeY = checkWithEpsilon_1(extendSize.y);
  95336. bodyConfig.type.push('cylinder');
  95337. bodyConfig.size.push(sizeX);
  95338. bodyConfig.size.push(sizeY);
  95339. //due to the way oimo works with compounds, add one more value.
  95340. bodyConfig.size.push(sizeY);
  95341. break;
  95342. case BABYLON.PhysicsImpostor.PlaneImpostor:
  95343. case BABYLON.PhysicsImpostor.BoxImpostor:
  95344. default:
  95345. var sizeX = checkWithEpsilon_1(extendSize.x);
  95346. var sizeY = checkWithEpsilon_1(extendSize.y);
  95347. var sizeZ = checkWithEpsilon_1(extendSize.z);
  95348. bodyConfig.type.push('box');
  95349. //if (i === impostor) {
  95350. bodyConfig.size.push(sizeX);
  95351. bodyConfig.size.push(sizeY);
  95352. bodyConfig.size.push(sizeZ);
  95353. //} else {
  95354. // bodyConfig.size.push(0,0,0);
  95355. //}
  95356. break;
  95357. }
  95358. //actually not needed, but hey...
  95359. i.object.rotationQuaternion = oldQuaternion;
  95360. });
  95361. impostor.physicsBody = this.world.add(bodyConfig);
  95362. // set the quaternion, ignoring the previously defined (euler) rotation
  95363. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  95364. // update with delta 0, so the body will reveive the new rotation.
  95365. impostor.physicsBody.updatePosition(0);
  95366. }
  95367. else {
  95368. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  95369. }
  95370. impostor.setDeltaPosition(this._tmpPositionVector);
  95371. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  95372. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  95373. };
  95374. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  95375. //impostor.physicsBody.dispose();
  95376. //Same as : (older oimo versions)
  95377. this.world.removeRigidBody(impostor.physicsBody);
  95378. };
  95379. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  95380. var mainBody = impostorJoint.mainImpostor.physicsBody;
  95381. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  95382. if (!mainBody || !connectedBody) {
  95383. return;
  95384. }
  95385. var jointData = impostorJoint.joint.jointData;
  95386. var options = jointData.nativeParams || {};
  95387. var type;
  95388. var nativeJointData = {
  95389. body1: mainBody,
  95390. body2: connectedBody,
  95391. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  95392. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  95393. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  95394. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  95395. min: options.min,
  95396. max: options.max,
  95397. collision: options.collision || jointData.collision,
  95398. spring: options.spring,
  95399. //supporting older version of Oimo
  95400. world: this.world
  95401. };
  95402. switch (impostorJoint.joint.type) {
  95403. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  95404. type = "jointBall";
  95405. break;
  95406. case BABYLON.PhysicsJoint.SpringJoint:
  95407. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  95408. var springData = jointData;
  95409. nativeJointData.min = springData.length || nativeJointData.min;
  95410. //Max should also be set, just make sure it is at least min
  95411. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  95412. case BABYLON.PhysicsJoint.DistanceJoint:
  95413. type = "jointDistance";
  95414. nativeJointData.max = jointData.maxDistance;
  95415. break;
  95416. case BABYLON.PhysicsJoint.PrismaticJoint:
  95417. type = "jointPrisme";
  95418. break;
  95419. case BABYLON.PhysicsJoint.SliderJoint:
  95420. type = "jointSlide";
  95421. break;
  95422. case BABYLON.PhysicsJoint.WheelJoint:
  95423. type = "jointWheel";
  95424. break;
  95425. case BABYLON.PhysicsJoint.HingeJoint:
  95426. default:
  95427. type = "jointHinge";
  95428. break;
  95429. }
  95430. nativeJointData.type = type;
  95431. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  95432. };
  95433. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  95434. //Bug in Oimo prevents us from disposing a joint in the playground
  95435. //joint.joint.physicsJoint.dispose();
  95436. //So we will bruteforce it!
  95437. try {
  95438. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  95439. }
  95440. catch (e) {
  95441. BABYLON.Tools.Warn(e);
  95442. }
  95443. };
  95444. OimoJSPlugin.prototype.isSupported = function () {
  95445. return this.BJSOIMO !== undefined;
  95446. };
  95447. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  95448. if (!impostor.physicsBody.sleeping) {
  95449. //TODO check that
  95450. /*if (impostor.physicsBody.shapes.next) {
  95451. var parentShape = this._getLastShape(impostor.physicsBody);
  95452. impostor.object.position.copyFrom(parentShape.position);
  95453. console.log(parentShape.position);
  95454. } else {*/
  95455. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  95456. //}
  95457. if (impostor.object.rotationQuaternion) {
  95458. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  95459. }
  95460. }
  95461. };
  95462. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  95463. var body = impostor.physicsBody;
  95464. body.position.copy(newPosition);
  95465. body.orientation.copy(newRotation);
  95466. body.syncShapes();
  95467. body.awake();
  95468. };
  95469. /*private _getLastShape(body: any): any {
  95470. var lastShape = body.shapes;
  95471. while (lastShape.next) {
  95472. lastShape = lastShape.next;
  95473. }
  95474. return lastShape;
  95475. }*/
  95476. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  95477. impostor.physicsBody.linearVelocity.copy(velocity);
  95478. };
  95479. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  95480. impostor.physicsBody.angularVelocity.copy(velocity);
  95481. };
  95482. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  95483. var v = impostor.physicsBody.linearVelocity;
  95484. if (!v) {
  95485. return null;
  95486. }
  95487. return new BABYLON.Vector3(v.x, v.y, v.z);
  95488. };
  95489. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  95490. var v = impostor.physicsBody.angularVelocity;
  95491. if (!v) {
  95492. return null;
  95493. }
  95494. return new BABYLON.Vector3(v.x, v.y, v.z);
  95495. };
  95496. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  95497. var staticBody = mass === 0;
  95498. //this will actually set the body's density and not its mass.
  95499. //But this is how oimo treats the mass variable.
  95500. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  95501. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  95502. };
  95503. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  95504. return impostor.physicsBody.shapes.density;
  95505. };
  95506. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  95507. return impostor.physicsBody.shapes.friction;
  95508. };
  95509. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  95510. impostor.physicsBody.shapes.friction = friction;
  95511. };
  95512. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  95513. return impostor.physicsBody.shapes.restitution;
  95514. };
  95515. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  95516. impostor.physicsBody.shapes.restitution = restitution;
  95517. };
  95518. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  95519. impostor.physicsBody.sleep();
  95520. };
  95521. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  95522. impostor.physicsBody.awake();
  95523. };
  95524. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  95525. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  95526. if (minDistance !== void 0) {
  95527. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  95528. }
  95529. };
  95530. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  95531. //TODO separate rotational and transational motors.
  95532. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  95533. if (motor) {
  95534. motor.setMotor(speed, maxForce);
  95535. }
  95536. };
  95537. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  95538. //TODO separate rotational and transational motors.
  95539. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  95540. if (motor) {
  95541. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  95542. }
  95543. };
  95544. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  95545. var body = impostor.physicsBody;
  95546. mesh.position.x = body.position.x;
  95547. mesh.position.y = body.position.y;
  95548. mesh.position.z = body.position.z;
  95549. if (mesh.rotationQuaternion) {
  95550. mesh.rotationQuaternion.x = body.orientation.x;
  95551. mesh.rotationQuaternion.y = body.orientation.y;
  95552. mesh.rotationQuaternion.z = body.orientation.z;
  95553. mesh.rotationQuaternion.w = body.orientation.s;
  95554. }
  95555. };
  95556. OimoJSPlugin.prototype.getRadius = function (impostor) {
  95557. return impostor.physicsBody.shapes.radius;
  95558. };
  95559. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  95560. var shape = impostor.physicsBody.shapes;
  95561. result.x = shape.halfWidth * 2;
  95562. result.y = shape.halfHeight * 2;
  95563. result.z = shape.halfDepth * 2;
  95564. };
  95565. OimoJSPlugin.prototype.dispose = function () {
  95566. this.world.clear();
  95567. };
  95568. return OimoJSPlugin;
  95569. }());
  95570. BABYLON.OimoJSPlugin = OimoJSPlugin;
  95571. })(BABYLON || (BABYLON = {}));
  95572. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  95573. var BABYLON;
  95574. (function (BABYLON) {
  95575. /**
  95576. * Gets the current physics engine
  95577. * @returns a IPhysicsEngine or null if none attached
  95578. */
  95579. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  95580. return this._physicsEngine;
  95581. };
  95582. /**
  95583. * Enables physics to the current scene
  95584. * @param gravity defines the scene's gravity for the physics engine
  95585. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  95586. * @return a boolean indicating if the physics engine was initialized
  95587. */
  95588. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  95589. if (gravity === void 0) { gravity = null; }
  95590. if (this._physicsEngine) {
  95591. return true;
  95592. }
  95593. // Register the component to the scene
  95594. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  95595. if (!component) {
  95596. component = new PhysicsEngineSceneComponent(this);
  95597. this._addComponent(component);
  95598. }
  95599. try {
  95600. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  95601. return true;
  95602. }
  95603. catch (e) {
  95604. BABYLON.Tools.Error(e.message);
  95605. return false;
  95606. }
  95607. };
  95608. /**
  95609. * Disables and disposes the physics engine associated with the scene
  95610. */
  95611. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  95612. if (!this._physicsEngine) {
  95613. return;
  95614. }
  95615. this._physicsEngine.dispose();
  95616. this._physicsEngine = null;
  95617. };
  95618. /**
  95619. * Gets a boolean indicating if there is an active physics engine
  95620. * @returns a boolean indicating if there is an active physics engine
  95621. */
  95622. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  95623. return this._physicsEngine !== undefined;
  95624. };
  95625. /**
  95626. * Deletes a physics compound impostor
  95627. * @param compound defines the compound to delete
  95628. */
  95629. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  95630. var mesh = compound.parts[0].mesh;
  95631. if (mesh.physicsImpostor) {
  95632. mesh.physicsImpostor.dispose( /*true*/);
  95633. mesh.physicsImpostor = null;
  95634. }
  95635. };
  95636. /** @hidden */
  95637. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  95638. if (this._physicsEngine) {
  95639. this.onBeforePhysicsObservable.notifyObservers(this);
  95640. this._physicsEngine._step(step / 1000);
  95641. this.onAfterPhysicsObservable.notifyObservers(this);
  95642. }
  95643. };
  95644. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  95645. get: function () {
  95646. return this._physicsImpostor;
  95647. },
  95648. set: function (value) {
  95649. var _this = this;
  95650. if (this._physicsImpostor === value) {
  95651. return;
  95652. }
  95653. if (this._disposePhysicsObserver) {
  95654. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  95655. }
  95656. this._physicsImpostor = value;
  95657. if (value) {
  95658. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  95659. // Physics
  95660. if (_this.physicsImpostor) {
  95661. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  95662. _this.physicsImpostor = null;
  95663. }
  95664. });
  95665. }
  95666. },
  95667. enumerable: true,
  95668. configurable: true
  95669. });
  95670. /**
  95671. * Gets the current physics impostor
  95672. * @see http://doc.babylonjs.com/features/physics_engine
  95673. * @returns a physics impostor or null
  95674. */
  95675. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  95676. return this.physicsImpostor;
  95677. };
  95678. /**
  95679. * Apply a physic impulse to the mesh
  95680. * @param force defines the force to apply
  95681. * @param contactPoint defines where to apply the force
  95682. * @returns the current mesh
  95683. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95684. */
  95685. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  95686. if (!this.physicsImpostor) {
  95687. return this;
  95688. }
  95689. this.physicsImpostor.applyImpulse(force, contactPoint);
  95690. return this;
  95691. };
  95692. /**
  95693. * Creates a physic joint between two meshes
  95694. * @param otherMesh defines the other mesh to use
  95695. * @param pivot1 defines the pivot to use on this mesh
  95696. * @param pivot2 defines the pivot to use on the other mesh
  95697. * @param options defines additional options (can be plugin dependent)
  95698. * @returns the current mesh
  95699. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  95700. */
  95701. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  95702. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  95703. return this;
  95704. }
  95705. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  95706. mainPivot: pivot1,
  95707. connectedPivot: pivot2,
  95708. nativeParams: options
  95709. });
  95710. return this;
  95711. };
  95712. /**
  95713. * Defines the physics engine scene component responsible to manage a physics engine
  95714. */
  95715. var PhysicsEngineSceneComponent = /** @class */ (function () {
  95716. /**
  95717. * Creates a new instance of the component for the given scene
  95718. * @param scene Defines the scene to register the component in
  95719. */
  95720. function PhysicsEngineSceneComponent(scene) {
  95721. var _this = this;
  95722. /**
  95723. * The component name helpful to identify the component in the list of scene components.
  95724. */
  95725. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  95726. this.scene = scene;
  95727. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  95728. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  95729. // Replace the function used to get the deterministic frame time
  95730. this.scene.getDeterministicFrameTime = function () {
  95731. if (_this.scene._physicsEngine) {
  95732. return _this.scene._physicsEngine.getTimeStep() * 1000;
  95733. }
  95734. return 1000.0 / 60.0;
  95735. };
  95736. }
  95737. /**
  95738. * Registers the component in a given scene
  95739. */
  95740. PhysicsEngineSceneComponent.prototype.register = function () {
  95741. };
  95742. /**
  95743. * Rebuilds the elements related to this component in case of
  95744. * context lost for instance.
  95745. */
  95746. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  95747. // Nothing to do for this component
  95748. };
  95749. /**
  95750. * Disposes the component and the associated ressources
  95751. */
  95752. PhysicsEngineSceneComponent.prototype.dispose = function () {
  95753. this.scene.onBeforePhysicsObservable.clear();
  95754. this.scene.onAfterPhysicsObservable.clear();
  95755. if (this.scene._physicsEngine) {
  95756. this.scene.disablePhysicsEngine();
  95757. }
  95758. };
  95759. return PhysicsEngineSceneComponent;
  95760. }());
  95761. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  95762. })(BABYLON || (BABYLON = {}));
  95763. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  95764. var BABYLON;
  95765. (function (BABYLON) {
  95766. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  95767. // All values and structures referenced from:
  95768. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  95769. var DDS_MAGIC = 0x20534444;
  95770. var
  95771. //DDSD_CAPS = 0x1,
  95772. //DDSD_HEIGHT = 0x2,
  95773. //DDSD_WIDTH = 0x4,
  95774. //DDSD_PITCH = 0x8,
  95775. //DDSD_PIXELFORMAT = 0x1000,
  95776. DDSD_MIPMAPCOUNT = 0x20000;
  95777. //DDSD_LINEARSIZE = 0x80000,
  95778. //DDSD_DEPTH = 0x800000;
  95779. // var DDSCAPS_COMPLEX = 0x8,
  95780. // DDSCAPS_MIPMAP = 0x400000,
  95781. // DDSCAPS_TEXTURE = 0x1000;
  95782. var DDSCAPS2_CUBEMAP = 0x200;
  95783. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  95784. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  95785. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  95786. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  95787. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  95788. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  95789. // DDSCAPS2_VOLUME = 0x200000;
  95790. var
  95791. //DDPF_ALPHAPIXELS = 0x1,
  95792. //DDPF_ALPHA = 0x2,
  95793. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  95794. //DDPF_YUV = 0x200,
  95795. DDPF_LUMINANCE = 0x20000;
  95796. function FourCCToInt32(value) {
  95797. return value.charCodeAt(0) +
  95798. (value.charCodeAt(1) << 8) +
  95799. (value.charCodeAt(2) << 16) +
  95800. (value.charCodeAt(3) << 24);
  95801. }
  95802. function Int32ToFourCC(value) {
  95803. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  95804. }
  95805. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  95806. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  95807. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  95808. var FOURCC_DX10 = FourCCToInt32("DX10");
  95809. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  95810. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  95811. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  95812. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  95813. var headerLengthInt = 31; // The header length in 32 bit ints
  95814. // Offsets into the header array
  95815. var off_magic = 0;
  95816. var off_size = 1;
  95817. var off_flags = 2;
  95818. var off_height = 3;
  95819. var off_width = 4;
  95820. var off_mipmapCount = 7;
  95821. var off_pfFlags = 20;
  95822. var off_pfFourCC = 21;
  95823. var off_RGBbpp = 22;
  95824. var off_RMask = 23;
  95825. var off_GMask = 24;
  95826. var off_BMask = 25;
  95827. var off_AMask = 26;
  95828. // var off_caps1 = 27;
  95829. var off_caps2 = 28;
  95830. // var off_caps3 = 29;
  95831. // var off_caps4 = 30;
  95832. var off_dxgiFormat = 32;
  95833. ;
  95834. /**
  95835. * Class used to provide DDS decompression tools
  95836. */
  95837. var DDSTools = /** @class */ (function () {
  95838. function DDSTools() {
  95839. }
  95840. /**
  95841. * Gets DDS information from an array buffer
  95842. * @param arrayBuffer defines the array buffer to read data from
  95843. * @returns the DDS information
  95844. */
  95845. DDSTools.GetDDSInfo = function (arrayBuffer) {
  95846. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  95847. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  95848. var mipmapCount = 1;
  95849. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  95850. mipmapCount = Math.max(1, header[off_mipmapCount]);
  95851. }
  95852. var fourCC = header[off_pfFourCC];
  95853. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  95854. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95855. switch (fourCC) {
  95856. case FOURCC_D3DFMT_R16G16B16A16F:
  95857. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95858. break;
  95859. case FOURCC_D3DFMT_R32G32B32A32F:
  95860. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95861. break;
  95862. case FOURCC_DX10:
  95863. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  95864. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95865. break;
  95866. }
  95867. }
  95868. return {
  95869. width: header[off_width],
  95870. height: header[off_height],
  95871. mipmapCount: mipmapCount,
  95872. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  95873. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  95874. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  95875. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  95876. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  95877. dxgiFormat: dxgiFormat,
  95878. textureType: textureType
  95879. };
  95880. };
  95881. DDSTools._ToHalfFloat = function (value) {
  95882. if (!DDSTools._FloatView) {
  95883. DDSTools._FloatView = new Float32Array(1);
  95884. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  95885. }
  95886. DDSTools._FloatView[0] = value;
  95887. var x = DDSTools._Int32View[0];
  95888. var bits = (x >> 16) & 0x8000; /* Get the sign */
  95889. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  95890. var e = (x >> 23) & 0xff; /* Using int is faster here */
  95891. /* If zero, or denormal, or exponent underflows too much for a denormal
  95892. * half, return signed zero. */
  95893. if (e < 103) {
  95894. return bits;
  95895. }
  95896. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  95897. if (e > 142) {
  95898. bits |= 0x7c00;
  95899. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  95900. * not Inf, so make sure we set one mantissa bit too. */
  95901. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  95902. return bits;
  95903. }
  95904. /* If exponent underflows but not too much, return a denormal */
  95905. if (e < 113) {
  95906. m |= 0x0800;
  95907. /* Extra rounding may overflow and set mantissa to 0 and exponent
  95908. * to 1, which is OK. */
  95909. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  95910. return bits;
  95911. }
  95912. bits |= ((e - 112) << 10) | (m >> 1);
  95913. bits += m & 1;
  95914. return bits;
  95915. };
  95916. DDSTools._FromHalfFloat = function (value) {
  95917. var s = (value & 0x8000) >> 15;
  95918. var e = (value & 0x7C00) >> 10;
  95919. var f = value & 0x03FF;
  95920. if (e === 0) {
  95921. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  95922. }
  95923. else if (e == 0x1F) {
  95924. return f ? NaN : ((s ? -1 : 1) * Infinity);
  95925. }
  95926. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  95927. };
  95928. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95929. var destArray = new Float32Array(dataLength);
  95930. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95931. var index = 0;
  95932. for (var y = 0; y < height; y++) {
  95933. for (var x = 0; x < width; x++) {
  95934. var srcPos = (x + y * width) * 4;
  95935. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  95936. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  95937. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  95938. if (DDSTools.StoreLODInAlphaChannel) {
  95939. destArray[index + 3] = lod;
  95940. }
  95941. else {
  95942. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  95943. }
  95944. index += 4;
  95945. }
  95946. }
  95947. return destArray;
  95948. };
  95949. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95950. if (DDSTools.StoreLODInAlphaChannel) {
  95951. var destArray = new Uint16Array(dataLength);
  95952. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95953. var index = 0;
  95954. for (var y = 0; y < height; y++) {
  95955. for (var x = 0; x < width; x++) {
  95956. var srcPos = (x + y * width) * 4;
  95957. destArray[index] = srcData[srcPos];
  95958. destArray[index + 1] = srcData[srcPos + 1];
  95959. destArray[index + 2] = srcData[srcPos + 2];
  95960. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  95961. index += 4;
  95962. }
  95963. }
  95964. return destArray;
  95965. }
  95966. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  95967. };
  95968. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95969. if (DDSTools.StoreLODInAlphaChannel) {
  95970. var destArray = new Float32Array(dataLength);
  95971. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95972. var index = 0;
  95973. for (var y = 0; y < height; y++) {
  95974. for (var x = 0; x < width; x++) {
  95975. var srcPos = (x + y * width) * 4;
  95976. destArray[index] = srcData[srcPos];
  95977. destArray[index + 1] = srcData[srcPos + 1];
  95978. destArray[index + 2] = srcData[srcPos + 2];
  95979. destArray[index + 3] = lod;
  95980. index += 4;
  95981. }
  95982. }
  95983. return destArray;
  95984. }
  95985. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  95986. };
  95987. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95988. var destArray = new Uint8Array(dataLength);
  95989. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95990. var index = 0;
  95991. for (var y = 0; y < height; y++) {
  95992. for (var x = 0; x < width; x++) {
  95993. var srcPos = (x + y * width) * 4;
  95994. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  95995. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  95996. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  95997. if (DDSTools.StoreLODInAlphaChannel) {
  95998. destArray[index + 3] = lod;
  95999. }
  96000. else {
  96001. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  96002. }
  96003. index += 4;
  96004. }
  96005. }
  96006. return destArray;
  96007. };
  96008. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  96009. var destArray = new Uint8Array(dataLength);
  96010. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  96011. var index = 0;
  96012. for (var y = 0; y < height; y++) {
  96013. for (var x = 0; x < width; x++) {
  96014. var srcPos = (x + y * width) * 4;
  96015. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  96016. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  96017. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  96018. if (DDSTools.StoreLODInAlphaChannel) {
  96019. destArray[index + 3] = lod;
  96020. }
  96021. else {
  96022. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  96023. }
  96024. index += 4;
  96025. }
  96026. }
  96027. return destArray;
  96028. };
  96029. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  96030. var byteArray = new Uint8Array(dataLength);
  96031. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96032. var index = 0;
  96033. for (var y = 0; y < height; y++) {
  96034. for (var x = 0; x < width; x++) {
  96035. var srcPos = (x + y * width) * 4;
  96036. byteArray[index] = srcData[srcPos + rOffset];
  96037. byteArray[index + 1] = srcData[srcPos + gOffset];
  96038. byteArray[index + 2] = srcData[srcPos + bOffset];
  96039. byteArray[index + 3] = srcData[srcPos + aOffset];
  96040. index += 4;
  96041. }
  96042. }
  96043. return byteArray;
  96044. };
  96045. DDSTools._ExtractLongWordOrder = function (value) {
  96046. if (value === 0 || value === 255 || value === -16777216) {
  96047. return 0;
  96048. }
  96049. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  96050. };
  96051. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  96052. var byteArray = new Uint8Array(dataLength);
  96053. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96054. var index = 0;
  96055. for (var y = 0; y < height; y++) {
  96056. for (var x = 0; x < width; x++) {
  96057. var srcPos = (x + y * width) * 3;
  96058. byteArray[index] = srcData[srcPos + rOffset];
  96059. byteArray[index + 1] = srcData[srcPos + gOffset];
  96060. byteArray[index + 2] = srcData[srcPos + bOffset];
  96061. index += 3;
  96062. }
  96063. }
  96064. return byteArray;
  96065. };
  96066. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  96067. var byteArray = new Uint8Array(dataLength);
  96068. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96069. var index = 0;
  96070. for (var y = 0; y < height; y++) {
  96071. for (var x = 0; x < width; x++) {
  96072. var srcPos = (x + y * width);
  96073. byteArray[index] = srcData[srcPos];
  96074. index++;
  96075. }
  96076. }
  96077. return byteArray;
  96078. };
  96079. /**
  96080. * Uploads DDS Levels to a Babylon Texture
  96081. * @hidden
  96082. */
  96083. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  96084. if (lodIndex === void 0) { lodIndex = -1; }
  96085. var sphericalPolynomialFaces = null;
  96086. if (info.sphericalPolynomial) {
  96087. sphericalPolynomialFaces = new Array();
  96088. }
  96089. var ext = engine.getCaps().s3tc;
  96090. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  96091. var fourCC, width, height, dataLength = 0, dataOffset;
  96092. var byteArray, mipmapCount, mip;
  96093. var internalCompressedFormat = 0;
  96094. var blockBytes = 1;
  96095. if (header[off_magic] !== DDS_MAGIC) {
  96096. BABYLON.Tools.Error("Invalid magic number in DDS header");
  96097. return;
  96098. }
  96099. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  96100. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  96101. return;
  96102. }
  96103. if (info.isCompressed && !ext) {
  96104. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  96105. return;
  96106. }
  96107. var bpp = header[off_RGBbpp];
  96108. dataOffset = header[off_size] + 4;
  96109. var computeFormats = false;
  96110. if (info.isFourCC) {
  96111. fourCC = header[off_pfFourCC];
  96112. switch (fourCC) {
  96113. case FOURCC_DXT1:
  96114. blockBytes = 8;
  96115. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  96116. break;
  96117. case FOURCC_DXT3:
  96118. blockBytes = 16;
  96119. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  96120. break;
  96121. case FOURCC_DXT5:
  96122. blockBytes = 16;
  96123. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  96124. break;
  96125. case FOURCC_D3DFMT_R16G16B16A16F:
  96126. computeFormats = true;
  96127. break;
  96128. case FOURCC_D3DFMT_R32G32B32A32F:
  96129. computeFormats = true;
  96130. break;
  96131. case FOURCC_DX10:
  96132. // There is an additionnal header so dataOffset need to be changed
  96133. dataOffset += 5 * 4; // 5 uints
  96134. var supported = false;
  96135. switch (info.dxgiFormat) {
  96136. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  96137. computeFormats = true;
  96138. supported = true;
  96139. break;
  96140. case DXGI_FORMAT_B8G8R8X8_UNORM:
  96141. info.isRGB = true;
  96142. info.isFourCC = false;
  96143. bpp = 32;
  96144. supported = true;
  96145. break;
  96146. }
  96147. if (supported) {
  96148. break;
  96149. }
  96150. default:
  96151. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  96152. return;
  96153. }
  96154. }
  96155. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  96156. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  96157. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  96158. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  96159. if (computeFormats) {
  96160. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  96161. }
  96162. mipmapCount = 1;
  96163. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  96164. mipmapCount = Math.max(1, header[off_mipmapCount]);
  96165. }
  96166. for (var face = 0; face < faces; face++) {
  96167. width = header[off_width];
  96168. height = header[off_height];
  96169. for (mip = 0; mip < mipmapCount; ++mip) {
  96170. if (lodIndex === -1 || lodIndex === mip) {
  96171. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  96172. var i = (lodIndex === -1) ? mip : 0;
  96173. if (!info.isCompressed && info.isFourCC) {
  96174. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96175. dataLength = width * height * 4;
  96176. var floatArray = null;
  96177. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  96178. if (bpp === 128) {
  96179. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96180. if (sphericalPolynomialFaces && i == 0) {
  96181. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96182. }
  96183. }
  96184. else if (bpp === 64) {
  96185. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96186. if (sphericalPolynomialFaces && i == 0) {
  96187. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96188. }
  96189. }
  96190. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96191. }
  96192. else {
  96193. if (bpp === 128) {
  96194. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96195. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96196. if (sphericalPolynomialFaces && i == 0) {
  96197. sphericalPolynomialFaces.push(floatArray);
  96198. }
  96199. }
  96200. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  96201. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96202. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96203. if (sphericalPolynomialFaces && i == 0) {
  96204. sphericalPolynomialFaces.push(floatArray);
  96205. }
  96206. }
  96207. else { // 64
  96208. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96209. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96210. if (sphericalPolynomialFaces && i == 0) {
  96211. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96212. }
  96213. }
  96214. }
  96215. if (floatArray) {
  96216. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  96217. }
  96218. }
  96219. else if (info.isRGB) {
  96220. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96221. if (bpp === 24) {
  96222. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  96223. dataLength = width * height * 3;
  96224. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  96225. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96226. }
  96227. else { // 32
  96228. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96229. dataLength = width * height * 4;
  96230. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  96231. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96232. }
  96233. }
  96234. else if (info.isLuminance) {
  96235. var unpackAlignment = engine._getUnpackAlignement();
  96236. var unpaddedRowSize = width;
  96237. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  96238. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  96239. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  96240. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  96241. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96242. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96243. }
  96244. else {
  96245. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  96246. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  96247. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96248. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  96249. }
  96250. }
  96251. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  96252. width *= 0.5;
  96253. height *= 0.5;
  96254. width = Math.max(1.0, width);
  96255. height = Math.max(1.0, height);
  96256. }
  96257. if (currentFace !== undefined) {
  96258. // Loading a single face
  96259. break;
  96260. }
  96261. }
  96262. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  96263. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  96264. size: header[off_width],
  96265. right: sphericalPolynomialFaces[0],
  96266. left: sphericalPolynomialFaces[1],
  96267. up: sphericalPolynomialFaces[2],
  96268. down: sphericalPolynomialFaces[3],
  96269. front: sphericalPolynomialFaces[4],
  96270. back: sphericalPolynomialFaces[5],
  96271. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  96272. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  96273. gammaSpace: false,
  96274. });
  96275. }
  96276. else {
  96277. info.sphericalPolynomial = undefined;
  96278. }
  96279. };
  96280. /**
  96281. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  96282. */
  96283. DDSTools.StoreLODInAlphaChannel = false;
  96284. return DDSTools;
  96285. }());
  96286. BABYLON.DDSTools = DDSTools;
  96287. })(BABYLON || (BABYLON = {}));
  96288. //# sourceMappingURL=babylon.dds.js.map
  96289. var BABYLON;
  96290. (function (BABYLON) {
  96291. /**
  96292. * Implementation of the DDS Texture Loader.
  96293. */
  96294. var DDSTextureLoader = /** @class */ (function () {
  96295. function DDSTextureLoader() {
  96296. /**
  96297. * Defines wether the loader supports cascade loading the different faces.
  96298. */
  96299. this.supportCascades = true;
  96300. }
  96301. /**
  96302. * This returns if the loader support the current file information.
  96303. * @param extension defines the file extension of the file being loaded
  96304. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96305. * @param fallback defines the fallback internal texture if any
  96306. * @param isBase64 defines whether the texture is encoded as a base64
  96307. * @param isBuffer defines whether the texture data are stored as a buffer
  96308. * @returns true if the loader can load the specified file
  96309. */
  96310. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96311. return extension.indexOf(".dds") === 0;
  96312. };
  96313. /**
  96314. * Transform the url before loading if required.
  96315. * @param rootUrl the url of the texture
  96316. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96317. * @returns the transformed texture
  96318. */
  96319. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96320. return rootUrl;
  96321. };
  96322. /**
  96323. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96324. * @param rootUrl the url of the texture
  96325. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96326. * @returns the fallback texture
  96327. */
  96328. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96329. return null;
  96330. };
  96331. /**
  96332. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96333. * @param data contains the texture data
  96334. * @param texture defines the BabylonJS internal texture
  96335. * @param createPolynomials will be true if polynomials have been requested
  96336. * @param onLoad defines the callback to trigger once the texture is ready
  96337. * @param onError defines the callback to trigger in case of error
  96338. */
  96339. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  96340. var engine = texture.getEngine();
  96341. var info;
  96342. var loadMipmap = false;
  96343. if (Array.isArray(imgs)) {
  96344. for (var index = 0; index < imgs.length; index++) {
  96345. var data_1 = imgs[index];
  96346. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  96347. texture.width = info.width;
  96348. texture.height = info.height;
  96349. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  96350. engine._unpackFlipY(info.isCompressed);
  96351. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  96352. if (!info.isFourCC && info.mipmapCount === 1) {
  96353. engine.generateMipMapsForCubemap(texture);
  96354. }
  96355. }
  96356. }
  96357. else {
  96358. var data = imgs;
  96359. info = BABYLON.DDSTools.GetDDSInfo(data);
  96360. texture.width = info.width;
  96361. texture.height = info.height;
  96362. if (createPolynomials) {
  96363. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  96364. }
  96365. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  96366. engine._unpackFlipY(info.isCompressed);
  96367. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  96368. if (!info.isFourCC && info.mipmapCount === 1) {
  96369. engine.generateMipMapsForCubemap(texture);
  96370. }
  96371. }
  96372. engine._setCubeMapTextureParams(loadMipmap);
  96373. texture.isReady = true;
  96374. if (onLoad) {
  96375. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  96376. }
  96377. };
  96378. /**
  96379. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96380. * @param data contains the texture data
  96381. * @param texture defines the BabylonJS internal texture
  96382. * @param callback defines the method to call once ready to upload
  96383. */
  96384. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  96385. var info = BABYLON.DDSTools.GetDDSInfo(data);
  96386. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  96387. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  96388. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  96389. });
  96390. };
  96391. return DDSTextureLoader;
  96392. }());
  96393. // Register the loader.
  96394. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  96395. })(BABYLON || (BABYLON = {}));
  96396. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  96397. var BABYLON;
  96398. (function (BABYLON) {
  96399. /**
  96400. * Based on jsTGALoader - Javascript loader for TGA file
  96401. * By Vincent Thibault
  96402. * @see http://blog.robrowser.com/javascript-tga-loader.html
  96403. */
  96404. var TGATools = /** @class */ (function () {
  96405. function TGATools() {
  96406. }
  96407. /**
  96408. * Gets the header of a TGA file
  96409. * @param data defines the TGA data
  96410. * @returns the header
  96411. */
  96412. TGATools.GetTGAHeader = function (data) {
  96413. var offset = 0;
  96414. var header = {
  96415. id_length: data[offset++],
  96416. colormap_type: data[offset++],
  96417. image_type: data[offset++],
  96418. colormap_index: data[offset++] | data[offset++] << 8,
  96419. colormap_length: data[offset++] | data[offset++] << 8,
  96420. colormap_size: data[offset++],
  96421. origin: [
  96422. data[offset++] | data[offset++] << 8,
  96423. data[offset++] | data[offset++] << 8
  96424. ],
  96425. width: data[offset++] | data[offset++] << 8,
  96426. height: data[offset++] | data[offset++] << 8,
  96427. pixel_size: data[offset++],
  96428. flags: data[offset++]
  96429. };
  96430. return header;
  96431. };
  96432. /**
  96433. * Uploads TGA content to a Babylon Texture
  96434. * @hidden
  96435. */
  96436. TGATools.UploadContent = function (texture, data) {
  96437. // Not enough data to contain header ?
  96438. if (data.length < 19) {
  96439. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  96440. return;
  96441. }
  96442. // Read Header
  96443. var offset = 18;
  96444. var header = TGATools.GetTGAHeader(data);
  96445. // Assume it's a valid Targa file.
  96446. if (header.id_length + offset > data.length) {
  96447. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  96448. return;
  96449. }
  96450. // Skip not needed data
  96451. offset += header.id_length;
  96452. var use_rle = false;
  96453. var use_pal = false;
  96454. var use_grey = false;
  96455. // Get some informations.
  96456. switch (header.image_type) {
  96457. case TGATools._TYPE_RLE_INDEXED:
  96458. use_rle = true;
  96459. case TGATools._TYPE_INDEXED:
  96460. use_pal = true;
  96461. break;
  96462. case TGATools._TYPE_RLE_RGB:
  96463. use_rle = true;
  96464. case TGATools._TYPE_RGB:
  96465. // use_rgb = true;
  96466. break;
  96467. case TGATools._TYPE_RLE_GREY:
  96468. use_rle = true;
  96469. case TGATools._TYPE_GREY:
  96470. use_grey = true;
  96471. break;
  96472. }
  96473. var pixel_data;
  96474. // var numAlphaBits = header.flags & 0xf;
  96475. var pixel_size = header.pixel_size >> 3;
  96476. var pixel_total = header.width * header.height * pixel_size;
  96477. // Read palettes
  96478. var palettes;
  96479. if (use_pal) {
  96480. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  96481. }
  96482. // Read LRE
  96483. if (use_rle) {
  96484. pixel_data = new Uint8Array(pixel_total);
  96485. var c, count, i;
  96486. var localOffset = 0;
  96487. var pixels = new Uint8Array(pixel_size);
  96488. while (offset < pixel_total && localOffset < pixel_total) {
  96489. c = data[offset++];
  96490. count = (c & 0x7f) + 1;
  96491. // RLE pixels
  96492. if (c & 0x80) {
  96493. // Bind pixel tmp array
  96494. for (i = 0; i < pixel_size; ++i) {
  96495. pixels[i] = data[offset++];
  96496. }
  96497. // Copy pixel array
  96498. for (i = 0; i < count; ++i) {
  96499. pixel_data.set(pixels, localOffset + i * pixel_size);
  96500. }
  96501. localOffset += pixel_size * count;
  96502. }
  96503. // Raw pixels
  96504. else {
  96505. count *= pixel_size;
  96506. for (i = 0; i < count; ++i) {
  96507. pixel_data[localOffset + i] = data[offset++];
  96508. }
  96509. localOffset += count;
  96510. }
  96511. }
  96512. }
  96513. // RAW Pixels
  96514. else {
  96515. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  96516. }
  96517. // Load to texture
  96518. var x_start, y_start, x_step, y_step, y_end, x_end;
  96519. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  96520. default:
  96521. case TGATools._ORIGIN_UL:
  96522. x_start = 0;
  96523. x_step = 1;
  96524. x_end = header.width;
  96525. y_start = 0;
  96526. y_step = 1;
  96527. y_end = header.height;
  96528. break;
  96529. case TGATools._ORIGIN_BL:
  96530. x_start = 0;
  96531. x_step = 1;
  96532. x_end = header.width;
  96533. y_start = header.height - 1;
  96534. y_step = -1;
  96535. y_end = -1;
  96536. break;
  96537. case TGATools._ORIGIN_UR:
  96538. x_start = header.width - 1;
  96539. x_step = -1;
  96540. x_end = -1;
  96541. y_start = 0;
  96542. y_step = 1;
  96543. y_end = header.height;
  96544. break;
  96545. case TGATools._ORIGIN_BR:
  96546. x_start = header.width - 1;
  96547. x_step = -1;
  96548. x_end = -1;
  96549. y_start = header.height - 1;
  96550. y_step = -1;
  96551. y_end = -1;
  96552. break;
  96553. }
  96554. // Load the specify method
  96555. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  96556. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  96557. var engine = texture.getEngine();
  96558. engine._uploadDataToTextureDirectly(texture, imageData);
  96559. };
  96560. /** @hidden */
  96561. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96562. var image = pixel_data, colormap = palettes;
  96563. var width = header.width, height = header.height;
  96564. var color, i = 0, x, y;
  96565. var imageData = new Uint8Array(width * height * 4);
  96566. for (y = y_start; y !== y_end; y += y_step) {
  96567. for (x = x_start; x !== x_end; x += x_step, i++) {
  96568. color = image[i];
  96569. imageData[(x + width * y) * 4 + 3] = 255;
  96570. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  96571. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  96572. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  96573. }
  96574. }
  96575. return imageData;
  96576. };
  96577. /** @hidden */
  96578. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96579. var image = pixel_data;
  96580. var width = header.width, height = header.height;
  96581. var color, i = 0, x, y;
  96582. var imageData = new Uint8Array(width * height * 4);
  96583. for (y = y_start; y !== y_end; y += y_step) {
  96584. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  96585. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  96586. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  96587. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  96588. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  96589. imageData[(x + width * y) * 4 + 0] = r;
  96590. imageData[(x + width * y) * 4 + 1] = g;
  96591. imageData[(x + width * y) * 4 + 2] = b;
  96592. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  96593. }
  96594. }
  96595. return imageData;
  96596. };
  96597. /** @hidden */
  96598. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96599. var image = pixel_data;
  96600. var width = header.width, height = header.height;
  96601. var i = 0, x, y;
  96602. var imageData = new Uint8Array(width * height * 4);
  96603. for (y = y_start; y !== y_end; y += y_step) {
  96604. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  96605. imageData[(x + width * y) * 4 + 3] = 255;
  96606. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96607. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  96608. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  96609. }
  96610. }
  96611. return imageData;
  96612. };
  96613. /** @hidden */
  96614. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96615. var image = pixel_data;
  96616. var width = header.width, height = header.height;
  96617. var i = 0, x, y;
  96618. var imageData = new Uint8Array(width * height * 4);
  96619. for (y = y_start; y !== y_end; y += y_step) {
  96620. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  96621. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96622. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  96623. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  96624. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  96625. }
  96626. }
  96627. return imageData;
  96628. };
  96629. /** @hidden */
  96630. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96631. var image = pixel_data;
  96632. var width = header.width, height = header.height;
  96633. var color, i = 0, x, y;
  96634. var imageData = new Uint8Array(width * height * 4);
  96635. for (y = y_start; y !== y_end; y += y_step) {
  96636. for (x = x_start; x !== x_end; x += x_step, i++) {
  96637. color = image[i];
  96638. imageData[(x + width * y) * 4 + 0] = color;
  96639. imageData[(x + width * y) * 4 + 1] = color;
  96640. imageData[(x + width * y) * 4 + 2] = color;
  96641. imageData[(x + width * y) * 4 + 3] = 255;
  96642. }
  96643. }
  96644. return imageData;
  96645. };
  96646. /** @hidden */
  96647. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96648. var image = pixel_data;
  96649. var width = header.width, height = header.height;
  96650. var i = 0, x, y;
  96651. var imageData = new Uint8Array(width * height * 4);
  96652. for (y = y_start; y !== y_end; y += y_step) {
  96653. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  96654. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  96655. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  96656. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96657. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  96658. }
  96659. }
  96660. return imageData;
  96661. };
  96662. //private static _TYPE_NO_DATA = 0;
  96663. TGATools._TYPE_INDEXED = 1;
  96664. TGATools._TYPE_RGB = 2;
  96665. TGATools._TYPE_GREY = 3;
  96666. TGATools._TYPE_RLE_INDEXED = 9;
  96667. TGATools._TYPE_RLE_RGB = 10;
  96668. TGATools._TYPE_RLE_GREY = 11;
  96669. TGATools._ORIGIN_MASK = 0x30;
  96670. TGATools._ORIGIN_SHIFT = 0x04;
  96671. TGATools._ORIGIN_BL = 0x00;
  96672. TGATools._ORIGIN_BR = 0x01;
  96673. TGATools._ORIGIN_UL = 0x02;
  96674. TGATools._ORIGIN_UR = 0x03;
  96675. return TGATools;
  96676. }());
  96677. BABYLON.TGATools = TGATools;
  96678. })(BABYLON || (BABYLON = {}));
  96679. //# sourceMappingURL=babylon.tga.js.map
  96680. var BABYLON;
  96681. (function (BABYLON) {
  96682. /**
  96683. * Implementation of the TGA Texture Loader.
  96684. */
  96685. var TGATextureLoader = /** @class */ (function () {
  96686. function TGATextureLoader() {
  96687. /**
  96688. * Defines wether the loader supports cascade loading the different faces.
  96689. */
  96690. this.supportCascades = false;
  96691. }
  96692. /**
  96693. * This returns if the loader support the current file information.
  96694. * @param extension defines the file extension of the file being loaded
  96695. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96696. * @param fallback defines the fallback internal texture if any
  96697. * @param isBase64 defines whether the texture is encoded as a base64
  96698. * @param isBuffer defines whether the texture data are stored as a buffer
  96699. * @returns true if the loader can load the specified file
  96700. */
  96701. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96702. return extension.indexOf(".tga") === 0;
  96703. };
  96704. /**
  96705. * Transform the url before loading if required.
  96706. * @param rootUrl the url of the texture
  96707. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96708. * @returns the transformed texture
  96709. */
  96710. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96711. return rootUrl;
  96712. };
  96713. /**
  96714. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96715. * @param rootUrl the url of the texture
  96716. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96717. * @returns the fallback texture
  96718. */
  96719. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96720. return null;
  96721. };
  96722. /**
  96723. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96724. * @param data contains the texture data
  96725. * @param texture defines the BabylonJS internal texture
  96726. * @param createPolynomials will be true if polynomials have been requested
  96727. * @param onLoad defines the callback to trigger once the texture is ready
  96728. * @param onError defines the callback to trigger in case of error
  96729. */
  96730. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96731. throw ".env not supported in Cube.";
  96732. };
  96733. /**
  96734. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96735. * @param data contains the texture data
  96736. * @param texture defines the BabylonJS internal texture
  96737. * @param callback defines the method to call once ready to upload
  96738. */
  96739. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  96740. var uintData = new Uint8Array(data);
  96741. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  96742. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  96743. BABYLON.TGATools.UploadContent(texture, uintData);
  96744. });
  96745. };
  96746. return TGATextureLoader;
  96747. }());
  96748. // Register the loader.
  96749. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  96750. })(BABYLON || (BABYLON = {}));
  96751. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  96752. var BABYLON;
  96753. (function (BABYLON) {
  96754. /**
  96755. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  96756. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  96757. */
  96758. var KhronosTextureContainer = /** @class */ (function () {
  96759. /**
  96760. * Creates a new KhronosTextureContainer
  96761. * @param arrayBuffer contents of the KTX container file
  96762. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  96763. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  96764. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  96765. */
  96766. function KhronosTextureContainer(
  96767. /** contents of the KTX container file */
  96768. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  96769. this.arrayBuffer = arrayBuffer;
  96770. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  96771. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  96772. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  96773. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  96774. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  96775. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  96776. BABYLON.Tools.Error("texture missing KTX identifier");
  96777. return;
  96778. }
  96779. // load the reset of the header in native 32 bit int
  96780. var header = new Int32Array(this.arrayBuffer, 12, 13);
  96781. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  96782. var oppositeEndianess = header[0] === 0x01020304;
  96783. // read all the header elements in order they exist in the file, without modification (sans endainness)
  96784. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  96785. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  96786. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  96787. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  96788. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  96789. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  96790. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  96791. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  96792. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  96793. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  96794. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  96795. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  96796. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  96797. if (this.glType !== 0) {
  96798. BABYLON.Tools.Error("only compressed formats currently supported");
  96799. return;
  96800. }
  96801. else {
  96802. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  96803. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  96804. }
  96805. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  96806. BABYLON.Tools.Error("only 2D textures currently supported");
  96807. return;
  96808. }
  96809. if (this.numberOfArrayElements !== 0) {
  96810. BABYLON.Tools.Error("texture arrays not currently supported");
  96811. return;
  96812. }
  96813. if (this.numberOfFaces !== facesExpected) {
  96814. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  96815. return;
  96816. }
  96817. // we now have a completely validated file, so could use existence of loadType as success
  96818. // would need to make this more elaborate & adjust checks above to support more than one load type
  96819. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  96820. }
  96821. //
  96822. /**
  96823. * Revert the endianness of a value.
  96824. * Not as fast hardware based, but will probably never need to use
  96825. * @param val defines the value to convert
  96826. * @returns the new value
  96827. */
  96828. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  96829. return ((val & 0xFF) << 24)
  96830. | ((val & 0xFF00) << 8)
  96831. | ((val >> 8) & 0xFF00)
  96832. | ((val >> 24) & 0xFF);
  96833. };
  96834. /**
  96835. * Uploads KTX content to a Babylon Texture.
  96836. * It is assumed that the texture has already been created & is currently bound
  96837. * @hidden
  96838. */
  96839. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  96840. switch (this.loadType) {
  96841. case KhronosTextureContainer.COMPRESSED_2D:
  96842. this._upload2DCompressedLevels(texture, loadMipmaps);
  96843. break;
  96844. case KhronosTextureContainer.TEX_2D:
  96845. case KhronosTextureContainer.COMPRESSED_3D:
  96846. case KhronosTextureContainer.TEX_3D:
  96847. }
  96848. };
  96849. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  96850. // initialize width & height for level 1
  96851. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  96852. var width = this.pixelWidth;
  96853. var height = this.pixelHeight;
  96854. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  96855. for (var level = 0; level < mipmapCount; level++) {
  96856. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  96857. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  96858. for (var face = 0; face < this.numberOfFaces; face++) {
  96859. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  96860. var engine = texture.getEngine();
  96861. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  96862. dataOffset += imageSize; // add size of the image for the next face/mipmap
  96863. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  96864. }
  96865. width = Math.max(1.0, width * 0.5);
  96866. height = Math.max(1.0, height * 0.5);
  96867. }
  96868. };
  96869. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  96870. // load types
  96871. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  96872. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  96873. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  96874. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  96875. return KhronosTextureContainer;
  96876. }());
  96877. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  96878. })(BABYLON || (BABYLON = {}));
  96879. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  96880. var BABYLON;
  96881. (function (BABYLON) {
  96882. /**
  96883. * Implementation of the KTX Texture Loader.
  96884. */
  96885. var KTXTextureLoader = /** @class */ (function () {
  96886. function KTXTextureLoader() {
  96887. /**
  96888. * Defines wether the loader supports cascade loading the different faces.
  96889. */
  96890. this.supportCascades = false;
  96891. }
  96892. /**
  96893. * This returns if the loader support the current file information.
  96894. * @param extension defines the file extension of the file being loaded
  96895. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96896. * @param fallback defines the fallback internal texture if any
  96897. * @param isBase64 defines whether the texture is encoded as a base64
  96898. * @param isBuffer defines whether the texture data are stored as a buffer
  96899. * @returns true if the loader can load the specified file
  96900. */
  96901. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96902. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  96903. return true;
  96904. }
  96905. return false;
  96906. };
  96907. /**
  96908. * Transform the url before loading if required.
  96909. * @param rootUrl the url of the texture
  96910. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96911. * @returns the transformed texture
  96912. */
  96913. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96914. var lastDot = rootUrl.lastIndexOf('.');
  96915. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  96916. };
  96917. /**
  96918. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96919. * @param rootUrl the url of the texture
  96920. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96921. * @returns the fallback texture
  96922. */
  96923. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96924. // remove the format appended to the rootUrl in the original createCubeTexture call.
  96925. var exp = new RegExp("" + textureFormatInUse + "$");
  96926. return rootUrl.replace(exp, "");
  96927. };
  96928. /**
  96929. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96930. * @param data contains the texture data
  96931. * @param texture defines the BabylonJS internal texture
  96932. * @param createPolynomials will be true if polynomials have been requested
  96933. * @param onLoad defines the callback to trigger once the texture is ready
  96934. * @param onError defines the callback to trigger in case of error
  96935. */
  96936. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96937. if (Array.isArray(data)) {
  96938. return;
  96939. }
  96940. var engine = texture.getEngine();
  96941. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  96942. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  96943. engine._unpackFlipY(true);
  96944. ktx.uploadLevels(texture, texture.generateMipMaps);
  96945. texture.width = ktx.pixelWidth;
  96946. texture.height = ktx.pixelHeight;
  96947. engine._setCubeMapTextureParams(loadMipmap);
  96948. texture.isReady = true;
  96949. };
  96950. /**
  96951. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96952. * @param data contains the texture data
  96953. * @param texture defines the BabylonJS internal texture
  96954. * @param callback defines the method to call once ready to upload
  96955. */
  96956. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  96957. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  96958. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  96959. ktx.uploadLevels(texture, texture.generateMipMaps);
  96960. });
  96961. };
  96962. return KTXTextureLoader;
  96963. }());
  96964. // Register the loader.
  96965. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  96966. })(BABYLON || (BABYLON = {}));
  96967. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  96968. var BABYLON;
  96969. (function (BABYLON) {
  96970. /**
  96971. * Sets of helpers addressing the serialization and deserialization of environment texture
  96972. * stored in a BabylonJS env file.
  96973. * Those files are usually stored as .env files.
  96974. */
  96975. var EnvironmentTextureTools = /** @class */ (function () {
  96976. function EnvironmentTextureTools() {
  96977. }
  96978. /**
  96979. * Gets the environment info from an env file.
  96980. * @param data The array buffer containing the .env bytes.
  96981. * @returns the environment file info (the json header) if successfully parsed.
  96982. */
  96983. EnvironmentTextureTools.GetEnvInfo = function (data) {
  96984. var dataView = new DataView(data);
  96985. var pos = 0;
  96986. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  96987. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  96988. BABYLON.Tools.Error('Not a babylon environment map');
  96989. return null;
  96990. }
  96991. }
  96992. // Read json manifest - collect characters up to null terminator
  96993. var manifestString = '';
  96994. var charCode = 0x00;
  96995. while ((charCode = dataView.getUint8(pos++))) {
  96996. manifestString += String.fromCharCode(charCode);
  96997. }
  96998. var manifest = JSON.parse(manifestString);
  96999. if (manifest.specular) {
  97000. // Extend the header with the position of the payload.
  97001. manifest.specular.specularDataPosition = pos;
  97002. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  97003. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  97004. }
  97005. return manifest;
  97006. };
  97007. /**
  97008. * Creates an environment texture from a loaded cube texture.
  97009. * @param texture defines the cube texture to convert in env file
  97010. * @return a promise containing the environment data if succesfull.
  97011. */
  97012. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  97013. var _this = this;
  97014. var internalTexture = texture.getInternalTexture();
  97015. if (!internalTexture) {
  97016. return Promise.reject("The cube texture is invalid.");
  97017. }
  97018. if (!texture._prefiltered) {
  97019. return Promise.reject("The cube texture is invalid (not prefiltered).");
  97020. }
  97021. var engine = internalTexture.getEngine();
  97022. if (engine && engine.premultipliedAlpha) {
  97023. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  97024. }
  97025. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  97026. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  97027. }
  97028. var canvas = engine.getRenderingCanvas();
  97029. if (!canvas) {
  97030. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  97031. }
  97032. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97033. if (!engine.getCaps().textureFloatRender) {
  97034. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97035. if (!engine.getCaps().textureHalfFloatRender) {
  97036. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  97037. }
  97038. }
  97039. var cubeWidth = internalTexture.width;
  97040. var hostingScene = new BABYLON.Scene(engine);
  97041. var specularTextures = {};
  97042. var promises = [];
  97043. // Read and collect all mipmaps data from the cube.
  97044. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  97045. mipmapsCount = Math.round(mipmapsCount);
  97046. var _loop_1 = function (i) {
  97047. var faceWidth = Math.pow(2, mipmapsCount - i);
  97048. var _loop_2 = function (face) {
  97049. var data = texture.readPixels(face, i);
  97050. // Creates a temp texture with the face data.
  97051. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  97052. // And rgbdEncode them.
  97053. var promise = new Promise(function (resolve, reject) {
  97054. 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);
  97055. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  97056. rgbdPostProcess.onApply = function (effect) {
  97057. effect._bindTexture("textureSampler", tempTexture);
  97058. };
  97059. // As the process needs to happen on the main canvas, keep track of the current size
  97060. var currentW = engine.getRenderWidth();
  97061. var currentH = engine.getRenderHeight();
  97062. // Set the desired size for the texture
  97063. engine.setSize(faceWidth, faceWidth);
  97064. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  97065. // Reading datas from WebGL
  97066. BABYLON.Tools.ToBlob(canvas, function (blob) {
  97067. var fileReader = new FileReader();
  97068. fileReader.onload = function (event) {
  97069. var arrayBuffer = event.target.result;
  97070. specularTextures[i * 6 + face] = arrayBuffer;
  97071. resolve();
  97072. };
  97073. fileReader.readAsArrayBuffer(blob);
  97074. });
  97075. // Reapply the previous canvas size
  97076. engine.setSize(currentW, currentH);
  97077. });
  97078. });
  97079. promises.push(promise);
  97080. };
  97081. // All faces of the cube.
  97082. for (var face = 0; face < 6; face++) {
  97083. _loop_2(face);
  97084. }
  97085. };
  97086. for (var i = 0; i <= mipmapsCount; i++) {
  97087. _loop_1(i);
  97088. }
  97089. // Once all the textures haves been collected as RGBD stored in PNGs
  97090. return Promise.all(promises).then(function () {
  97091. // We can delete the hosting scene keeping track of all the creation objects
  97092. hostingScene.dispose();
  97093. // Creates the json header for the env texture
  97094. var info = {
  97095. version: 1,
  97096. width: cubeWidth,
  97097. irradiance: _this._CreateEnvTextureIrradiance(texture),
  97098. specular: {
  97099. mipmaps: [],
  97100. lodGenerationScale: texture.lodGenerationScale
  97101. }
  97102. };
  97103. // Sets the specular image data information
  97104. var position = 0;
  97105. for (var i = 0; i <= mipmapsCount; i++) {
  97106. for (var face = 0; face < 6; face++) {
  97107. var byteLength = specularTextures[i * 6 + face].byteLength;
  97108. info.specular.mipmaps.push({
  97109. length: byteLength,
  97110. position: position
  97111. });
  97112. position += byteLength;
  97113. }
  97114. }
  97115. // Encode the JSON as an array buffer
  97116. var infoString = JSON.stringify(info);
  97117. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  97118. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  97119. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  97120. infoView[i] = infoString.charCodeAt(i);
  97121. }
  97122. // Ends up with a null terminator for easier parsing
  97123. infoView[infoString.length] = 0x00;
  97124. // Computes the final required size and creates the storage
  97125. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  97126. var finalBuffer = new ArrayBuffer(totalSize);
  97127. var finalBufferView = new Uint8Array(finalBuffer);
  97128. var dataView = new DataView(finalBuffer);
  97129. // Copy the magic bytes identifying the file in
  97130. var pos = 0;
  97131. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  97132. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  97133. }
  97134. // Add the json info
  97135. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  97136. pos += infoBuffer.byteLength;
  97137. // Finally inserts the texture data
  97138. for (var i = 0; i <= mipmapsCount; i++) {
  97139. for (var face = 0; face < 6; face++) {
  97140. var dataBuffer = specularTextures[i * 6 + face];
  97141. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  97142. pos += dataBuffer.byteLength;
  97143. }
  97144. }
  97145. // Voila
  97146. return finalBuffer;
  97147. });
  97148. };
  97149. /**
  97150. * Creates a JSON representation of the spherical data.
  97151. * @param texture defines the texture containing the polynomials
  97152. * @return the JSON representation of the spherical info
  97153. */
  97154. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  97155. var polynmials = texture.sphericalPolynomial;
  97156. if (polynmials == null) {
  97157. return null;
  97158. }
  97159. return {
  97160. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  97161. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  97162. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  97163. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  97164. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  97165. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  97166. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  97167. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  97168. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  97169. };
  97170. };
  97171. /**
  97172. * Uploads the texture info contained in the env file to the GPU.
  97173. * @param texture defines the internal texture to upload to
  97174. * @param arrayBuffer defines the buffer cotaining the data to load
  97175. * @param info defines the texture info retrieved through the GetEnvInfo method
  97176. * @returns a promise
  97177. */
  97178. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  97179. if (info.version !== 1) {
  97180. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  97181. }
  97182. var specularInfo = info.specular;
  97183. if (!specularInfo) {
  97184. // Nothing else parsed so far
  97185. return Promise.resolve();
  97186. }
  97187. // Double checks the enclosed info
  97188. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  97189. mipmapsCount = Math.round(mipmapsCount) + 1;
  97190. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  97191. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  97192. }
  97193. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  97194. var imageData = new Array(mipmapsCount);
  97195. for (var i = 0; i < mipmapsCount; i++) {
  97196. imageData[i] = new Array(6);
  97197. for (var face = 0; face < 6; face++) {
  97198. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  97199. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  97200. }
  97201. }
  97202. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  97203. };
  97204. /**
  97205. * Uploads the levels of image data to the GPU.
  97206. * @param texture defines the internal texture to upload to
  97207. * @param imageData defines the array buffer views of image data [mipmap][face]
  97208. * @returns a promise
  97209. */
  97210. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  97211. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  97212. throw new Error("Texture size must be a power of two");
  97213. }
  97214. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  97215. // Gets everything ready.
  97216. var engine = texture.getEngine();
  97217. var expandTexture = false;
  97218. var generateNonLODTextures = false;
  97219. var rgbdPostProcess = null;
  97220. var cubeRtt = null;
  97221. var lodTextures = null;
  97222. var caps = engine.getCaps();
  97223. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97224. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97225. texture.generateMipMaps = true;
  97226. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  97227. // Add extra process if texture lod is not supported
  97228. if (!caps.textureLOD) {
  97229. expandTexture = false;
  97230. generateNonLODTextures = true;
  97231. lodTextures = {};
  97232. }
  97233. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  97234. else if (engine.webGLVersion < 2) {
  97235. expandTexture = false;
  97236. }
  97237. // If half float available we can uncompress the texture
  97238. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  97239. expandTexture = true;
  97240. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97241. }
  97242. // If full float available we can uncompress the texture
  97243. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  97244. expandTexture = true;
  97245. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97246. }
  97247. // Expand the texture if possible
  97248. if (expandTexture) {
  97249. // Simply run through the decode PP
  97250. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  97251. texture._isRGBD = false;
  97252. texture.invertY = false;
  97253. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  97254. generateDepthBuffer: false,
  97255. generateMipMaps: true,
  97256. generateStencilBuffer: false,
  97257. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  97258. type: texture.type,
  97259. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  97260. });
  97261. }
  97262. else {
  97263. texture._isRGBD = true;
  97264. texture.invertY = true;
  97265. // In case of missing support, applies the same patch than DDS files.
  97266. if (generateNonLODTextures) {
  97267. var mipSlices = 3;
  97268. var scale = texture._lodGenerationScale;
  97269. var offset = texture._lodGenerationOffset;
  97270. for (var i = 0; i < mipSlices; i++) {
  97271. //compute LOD from even spacing in smoothness (matching shader calculation)
  97272. var smoothness = i / (mipSlices - 1);
  97273. var roughness = 1 - smoothness;
  97274. var minLODIndex = offset; // roughness = 0
  97275. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  97276. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  97277. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  97278. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  97279. glTextureFromLod.isCube = true;
  97280. glTextureFromLod.invertY = true;
  97281. glTextureFromLod.generateMipMaps = false;
  97282. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  97283. // Wrap in a base texture for easy binding.
  97284. var lodTexture = new BABYLON.BaseTexture(null);
  97285. lodTexture.isCube = true;
  97286. lodTexture._texture = glTextureFromLod;
  97287. lodTextures[mipmapIndex] = lodTexture;
  97288. switch (i) {
  97289. case 0:
  97290. texture._lodTextureLow = lodTexture;
  97291. break;
  97292. case 1:
  97293. texture._lodTextureMid = lodTexture;
  97294. break;
  97295. case 2:
  97296. texture._lodTextureHigh = lodTexture;
  97297. break;
  97298. }
  97299. }
  97300. }
  97301. }
  97302. var promises = [];
  97303. var _loop_3 = function (i) {
  97304. var _loop_4 = function (face) {
  97305. // Constructs an image element from image data
  97306. var bytes = imageData[i][face];
  97307. var blob = new Blob([bytes], { type: 'image/png' });
  97308. var url = URL.createObjectURL(blob);
  97309. var image = new Image();
  97310. image.src = url;
  97311. // Enqueue promise to upload to the texture.
  97312. var promise = new Promise(function (resolve, reject) {
  97313. image.onload = function () {
  97314. if (expandTexture) {
  97315. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  97316. reject(message);
  97317. }, image);
  97318. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  97319. // Uncompress the data to a RTT
  97320. rgbdPostProcess.onApply = function (effect) {
  97321. effect._bindTexture("textureSampler", tempTexture_1);
  97322. effect.setFloat2("scale", 1, 1);
  97323. };
  97324. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  97325. // Cleanup
  97326. engine.restoreDefaultFramebuffer();
  97327. tempTexture_1.dispose();
  97328. window.URL.revokeObjectURL(url);
  97329. resolve();
  97330. });
  97331. }
  97332. else {
  97333. engine._uploadImageToTexture(texture, image, face, i);
  97334. // Upload the face to the non lod texture support
  97335. if (generateNonLODTextures) {
  97336. var lodTexture = lodTextures[i];
  97337. if (lodTexture) {
  97338. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  97339. }
  97340. }
  97341. resolve();
  97342. }
  97343. };
  97344. image.onerror = function (error) {
  97345. reject(error);
  97346. };
  97347. });
  97348. promises.push(promise);
  97349. };
  97350. // All faces
  97351. for (var face = 0; face < 6; face++) {
  97352. _loop_4(face);
  97353. }
  97354. };
  97355. // All mipmaps up to provided number of images
  97356. for (var i = 0; i < imageData.length; i++) {
  97357. _loop_3(i);
  97358. }
  97359. // Fill remaining mipmaps with black textures.
  97360. if (imageData.length < mipmapsCount) {
  97361. var data = void 0;
  97362. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  97363. var dataLength = size * size * 4;
  97364. switch (texture.type) {
  97365. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  97366. data = new Uint8Array(dataLength);
  97367. break;
  97368. }
  97369. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  97370. data = new Uint16Array(dataLength);
  97371. break;
  97372. }
  97373. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  97374. data = new Float32Array(dataLength);
  97375. break;
  97376. }
  97377. }
  97378. for (var i = imageData.length; i < mipmapsCount; i++) {
  97379. for (var face = 0; face < 6; face++) {
  97380. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  97381. }
  97382. }
  97383. }
  97384. // Once all done, finishes the cleanup and return
  97385. return Promise.all(promises).then(function () {
  97386. // Release temp RTT.
  97387. if (cubeRtt) {
  97388. engine._releaseFramebufferObjects(cubeRtt);
  97389. cubeRtt._swapAndDie(texture);
  97390. }
  97391. // Release temp Post Process.
  97392. if (rgbdPostProcess) {
  97393. rgbdPostProcess.dispose();
  97394. }
  97395. // Flag internal texture as ready in case they are in use.
  97396. if (generateNonLODTextures) {
  97397. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  97398. texture._lodTextureHigh._texture.isReady = true;
  97399. }
  97400. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  97401. texture._lodTextureMid._texture.isReady = true;
  97402. }
  97403. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  97404. texture._lodTextureLow._texture.isReady = true;
  97405. }
  97406. }
  97407. });
  97408. };
  97409. /**
  97410. * Uploads spherical polynomials information to the texture.
  97411. * @param texture defines the texture we are trying to upload the information to
  97412. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  97413. */
  97414. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  97415. if (info.version !== 1) {
  97416. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  97417. }
  97418. var irradianceInfo = info.irradiance;
  97419. if (!irradianceInfo) {
  97420. return;
  97421. }
  97422. var sp = new BABYLON.SphericalPolynomial();
  97423. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  97424. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  97425. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  97426. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  97427. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  97428. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  97429. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  97430. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  97431. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  97432. texture._sphericalPolynomial = sp;
  97433. };
  97434. /**
  97435. * Magic number identifying the env file.
  97436. */
  97437. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  97438. return EnvironmentTextureTools;
  97439. }());
  97440. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  97441. })(BABYLON || (BABYLON = {}));
  97442. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  97443. var BABYLON;
  97444. (function (BABYLON) {
  97445. /**
  97446. * Implementation of the ENV Texture Loader.
  97447. */
  97448. var ENVTextureLoader = /** @class */ (function () {
  97449. function ENVTextureLoader() {
  97450. /**
  97451. * Defines wether the loader supports cascade loading the different faces.
  97452. */
  97453. this.supportCascades = false;
  97454. }
  97455. /**
  97456. * This returns if the loader support the current file information.
  97457. * @param extension defines the file extension of the file being loaded
  97458. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97459. * @param fallback defines the fallback internal texture if any
  97460. * @param isBase64 defines whether the texture is encoded as a base64
  97461. * @param isBuffer defines whether the texture data are stored as a buffer
  97462. * @returns true if the loader can load the specified file
  97463. */
  97464. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  97465. return extension.indexOf(".env") === 0;
  97466. };
  97467. /**
  97468. * Transform the url before loading if required.
  97469. * @param rootUrl the url of the texture
  97470. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97471. * @returns the transformed texture
  97472. */
  97473. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  97474. return rootUrl;
  97475. };
  97476. /**
  97477. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  97478. * @param rootUrl the url of the texture
  97479. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97480. * @returns the fallback texture
  97481. */
  97482. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  97483. return null;
  97484. };
  97485. /**
  97486. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  97487. * @param data contains the texture data
  97488. * @param texture defines the BabylonJS internal texture
  97489. * @param createPolynomials will be true if polynomials have been requested
  97490. * @param onLoad defines the callback to trigger once the texture is ready
  97491. * @param onError defines the callback to trigger in case of error
  97492. */
  97493. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  97494. if (Array.isArray(data)) {
  97495. return;
  97496. }
  97497. data = data;
  97498. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  97499. if (info) {
  97500. texture.width = info.width;
  97501. texture.height = info.width;
  97502. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  97503. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  97504. texture.isReady = true;
  97505. if (onLoad) {
  97506. onLoad();
  97507. }
  97508. });
  97509. }
  97510. else if (onError) {
  97511. onError("Can not parse the environment file", null);
  97512. }
  97513. };
  97514. /**
  97515. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  97516. * @param data contains the texture data
  97517. * @param texture defines the BabylonJS internal texture
  97518. * @param callback defines the method to call once ready to upload
  97519. */
  97520. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  97521. throw ".env not supported in 2d.";
  97522. };
  97523. return ENVTextureLoader;
  97524. }());
  97525. // Register the loader.
  97526. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  97527. })(BABYLON || (BABYLON = {}));
  97528. //# sourceMappingURL=babylon.envTextureLoader.js.map
  97529. var BABYLON;
  97530. (function (BABYLON) {
  97531. /**
  97532. * Renders a layer on top of an existing scene
  97533. */
  97534. var UtilityLayerRenderer = /** @class */ (function () {
  97535. /**
  97536. * Instantiates a UtilityLayerRenderer
  97537. * @param originalScene the original scene that will be rendered on top of
  97538. */
  97539. function UtilityLayerRenderer(
  97540. /** the original scene that will be rendered on top of */
  97541. originalScene) {
  97542. var _this = this;
  97543. this.originalScene = originalScene;
  97544. this._pointerCaptures = {};
  97545. this._lastPointerEvents = {};
  97546. /**
  97547. * If the utility layer should automatically be rendered on top of existing scene
  97548. */
  97549. this.shouldRender = true;
  97550. /**
  97551. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  97552. */
  97553. this.onlyCheckPointerDownEvents = true;
  97554. /**
  97555. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  97556. */
  97557. this.processAllEvents = false;
  97558. /**
  97559. * Observable raised when the pointer move from the utility layer scene to the main scene
  97560. */
  97561. this.onPointerOutObservable = new BABYLON.Observable();
  97562. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  97563. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  97564. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  97565. this.utilityLayerScene._allowPostProcessClearColor = false;
  97566. originalScene.getEngine().scenes.pop();
  97567. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  97568. this.utilityLayerScene.detachControl();
  97569. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  97570. if (!_this.processAllEvents) {
  97571. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  97572. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  97573. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  97574. return;
  97575. }
  97576. }
  97577. var pointerEvent = (prePointerInfo.event);
  97578. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  97579. _this._pointerCaptures[pointerEvent.pointerId] = false;
  97580. return;
  97581. }
  97582. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  97583. if (!prePointerInfo.ray && utilityScenePick) {
  97584. prePointerInfo.ray = utilityScenePick.ray;
  97585. }
  97586. // always fire the prepointer oversvable
  97587. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  97588. // allow every non pointer down event to flow to the utility layer
  97589. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  97590. if (!prePointerInfo.skipOnPointerObservable) {
  97591. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  97592. }
  97593. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  97594. _this._pointerCaptures[pointerEvent.pointerId] = false;
  97595. }
  97596. return;
  97597. }
  97598. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  97599. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  97600. if (utilityScenePick && utilityScenePick.hit) {
  97601. if (!prePointerInfo.skipOnPointerObservable) {
  97602. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  97603. }
  97604. prePointerInfo.skipOnPointerObservable = true;
  97605. }
  97606. }
  97607. else {
  97608. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  97609. var pointerEvent_1 = (prePointerInfo.event);
  97610. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  97611. if (originalScenePick && utilityScenePick) {
  97612. // No pick in utility scene
  97613. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  97614. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  97615. // We touched an utility mesh present in the main scene
  97616. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  97617. prePointerInfo.skipOnPointerObservable = true;
  97618. }
  97619. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97620. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  97621. }
  97622. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  97623. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  97624. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  97625. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  97626. }
  97627. }
  97628. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  97629. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  97630. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  97631. // If a previous utility layer set this, do not unset this
  97632. if (!prePointerInfo.skipOnPointerObservable) {
  97633. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  97634. }
  97635. }
  97636. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  97637. // We have a pick in both scenes but main is closer than utility
  97638. // We touched an utility mesh present in the main scene
  97639. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  97640. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  97641. prePointerInfo.skipOnPointerObservable = true;
  97642. }
  97643. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  97644. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  97645. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  97646. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  97647. }
  97648. }
  97649. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  97650. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  97651. }
  97652. }
  97653. }
  97654. });
  97655. // Render directly on top of existing scene without clearing
  97656. this.utilityLayerScene.autoClear = false;
  97657. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  97658. if (_this.shouldRender) {
  97659. _this.render();
  97660. }
  97661. });
  97662. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  97663. _this.dispose();
  97664. });
  97665. this._updateCamera();
  97666. }
  97667. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  97668. /**
  97669. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  97670. */
  97671. get: function () {
  97672. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  97673. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  97674. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  97675. UtilityLayerRenderer._DefaultUtilityLayer = null;
  97676. });
  97677. }
  97678. return UtilityLayerRenderer._DefaultUtilityLayer;
  97679. },
  97680. enumerable: true,
  97681. configurable: true
  97682. });
  97683. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  97684. /**
  97685. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  97686. */
  97687. get: function () {
  97688. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  97689. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  97690. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  97691. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  97692. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  97693. });
  97694. }
  97695. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  97696. },
  97697. enumerable: true,
  97698. configurable: true
  97699. });
  97700. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  97701. if (!prePointerInfo.skipOnPointerObservable) {
  97702. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  97703. this._lastPointerEvents[pointerEvent.pointerId] = true;
  97704. }
  97705. };
  97706. /**
  97707. * Renders the utility layers scene on top of the original scene
  97708. */
  97709. UtilityLayerRenderer.prototype.render = function () {
  97710. this._updateCamera();
  97711. if (this.utilityLayerScene.activeCamera) {
  97712. // Set the camera's scene to utility layers scene
  97713. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  97714. var camera = this.utilityLayerScene.activeCamera;
  97715. camera._scene = this.utilityLayerScene;
  97716. if (camera.leftCamera) {
  97717. camera.leftCamera._scene = this.utilityLayerScene;
  97718. }
  97719. if (camera.rightCamera) {
  97720. camera.rightCamera._scene = this.utilityLayerScene;
  97721. }
  97722. this.utilityLayerScene.render(false);
  97723. // Reset camera's scene back to original
  97724. camera._scene = oldScene;
  97725. if (camera.leftCamera) {
  97726. camera.leftCamera._scene = oldScene;
  97727. }
  97728. if (camera.rightCamera) {
  97729. camera.rightCamera._scene = oldScene;
  97730. }
  97731. }
  97732. };
  97733. /**
  97734. * Disposes of the renderer
  97735. */
  97736. UtilityLayerRenderer.prototype.dispose = function () {
  97737. this.onPointerOutObservable.clear();
  97738. if (this._afterRenderObserver) {
  97739. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  97740. }
  97741. if (this._sceneDisposeObserver) {
  97742. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  97743. }
  97744. if (this._originalPointerObserver) {
  97745. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  97746. }
  97747. this.utilityLayerScene.dispose();
  97748. };
  97749. UtilityLayerRenderer.prototype._updateCamera = function () {
  97750. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  97751. };
  97752. UtilityLayerRenderer._DefaultUtilityLayer = null;
  97753. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  97754. return UtilityLayerRenderer;
  97755. }());
  97756. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  97757. })(BABYLON || (BABYLON = {}));
  97758. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  97759. //# sourceMappingURL=babylon.behavior.js.map
  97760. var BABYLON;
  97761. (function (BABYLON) {
  97762. /**
  97763. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  97764. */
  97765. var PointerDragBehavior = /** @class */ (function () {
  97766. /**
  97767. * Creates a pointer drag behavior that can be attached to a mesh
  97768. * @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)
  97769. */
  97770. function PointerDragBehavior(options) {
  97771. /**
  97772. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  97773. */
  97774. this.maxDragAngle = 0;
  97775. /**
  97776. * @hidden
  97777. */
  97778. this._useAlternatePickedPointAboveMaxDragAngle = false;
  97779. /**
  97780. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  97781. */
  97782. this.currentDraggingPointerID = -1;
  97783. /**
  97784. * If the behavior is currently in a dragging state
  97785. */
  97786. this.dragging = false;
  97787. /**
  97788. * 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)
  97789. */
  97790. this.dragDeltaRatio = 0.2;
  97791. /**
  97792. * If the drag plane orientation should be updated during the dragging (Default: true)
  97793. */
  97794. this.updateDragPlane = true;
  97795. // Debug mode will display drag planes to help visualize behavior
  97796. this._debugMode = false;
  97797. this._moving = false;
  97798. /**
  97799. * Fires each time the attached mesh is dragged with the pointer
  97800. * * delta between last drag position and current drag position in world space
  97801. * * dragDistance along the drag axis
  97802. * * dragPlaneNormal normal of the current drag plane used during the drag
  97803. * * dragPlanePoint in world space where the drag intersects the drag plane
  97804. */
  97805. this.onDragObservable = new BABYLON.Observable();
  97806. /**
  97807. * Fires each time a drag begins (eg. mouse down on mesh)
  97808. */
  97809. this.onDragStartObservable = new BABYLON.Observable();
  97810. /**
  97811. * Fires each time a drag ends (eg. mouse release after drag)
  97812. */
  97813. this.onDragEndObservable = new BABYLON.Observable();
  97814. /**
  97815. * If the attached mesh should be moved when dragged
  97816. */
  97817. this.moveAttached = true;
  97818. /**
  97819. * If the drag behavior will react to drag events (Default: true)
  97820. */
  97821. this.enabled = true;
  97822. /**
  97823. * If camera controls should be detached during the drag
  97824. */
  97825. this.detachCameraControls = true;
  97826. /**
  97827. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  97828. */
  97829. this.useObjectOrienationForDragging = true;
  97830. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97831. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  97832. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  97833. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  97834. this._attachedElement = null;
  97835. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97836. this._lastPointerRay = {};
  97837. this._dragDelta = new BABYLON.Vector3();
  97838. // Variables to avoid instantiation in the below method
  97839. this._pointA = new BABYLON.Vector3(0, 0, 0);
  97840. this._pointB = new BABYLON.Vector3(0, 0, 0);
  97841. this._pointC = new BABYLON.Vector3(0, 0, 0);
  97842. this._lineA = new BABYLON.Vector3(0, 0, 0);
  97843. this._lineB = new BABYLON.Vector3(0, 0, 0);
  97844. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  97845. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  97846. this._options = options ? options : {};
  97847. var optionCount = 0;
  97848. if (this._options.dragAxis) {
  97849. optionCount++;
  97850. }
  97851. if (this._options.dragPlaneNormal) {
  97852. optionCount++;
  97853. }
  97854. if (optionCount > 1) {
  97855. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  97856. }
  97857. }
  97858. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  97859. /**
  97860. * The name of the behavior
  97861. */
  97862. get: function () {
  97863. return "PointerDrag";
  97864. },
  97865. enumerable: true,
  97866. configurable: true
  97867. });
  97868. /**
  97869. * Initializes the behavior
  97870. */
  97871. PointerDragBehavior.prototype.init = function () { };
  97872. /**
  97873. * Attaches the drag behavior the passed in mesh
  97874. * @param ownerNode The mesh that will be dragged around once attached
  97875. */
  97876. PointerDragBehavior.prototype.attach = function (ownerNode) {
  97877. var _this = this;
  97878. this._scene = ownerNode.getScene();
  97879. this._attachedNode = ownerNode;
  97880. // Initialize drag plane to not interfere with existing scene
  97881. if (!PointerDragBehavior._planeScene) {
  97882. if (this._debugMode) {
  97883. PointerDragBehavior._planeScene = this._scene;
  97884. }
  97885. else {
  97886. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  97887. PointerDragBehavior._planeScene.detachControl();
  97888. this._scene.getEngine().scenes.pop();
  97889. this._scene.onDisposeObservable.addOnce(function () {
  97890. PointerDragBehavior._planeScene.dispose();
  97891. PointerDragBehavior._planeScene = null;
  97892. });
  97893. }
  97894. }
  97895. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  97896. // State of the drag
  97897. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  97898. var pickPredicate = function (m) {
  97899. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  97900. };
  97901. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  97902. if (!_this.enabled) {
  97903. return;
  97904. }
  97905. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97906. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  97907. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  97908. }
  97909. }
  97910. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  97911. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  97912. _this.releaseDrag();
  97913. }
  97914. }
  97915. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  97916. var pointerId = pointerInfo.event.pointerId;
  97917. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  97918. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  97919. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  97920. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  97921. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  97922. }
  97923. _this.currentDraggingPointerID = pointerId;
  97924. }
  97925. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  97926. if (!_this._lastPointerRay[pointerId]) {
  97927. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97928. }
  97929. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  97930. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  97931. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  97932. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  97933. _this._moveDrag(pointerInfo.pickInfo.ray);
  97934. }
  97935. }
  97936. }
  97937. });
  97938. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  97939. if (_this._moving && _this.moveAttached) {
  97940. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  97941. // Slowly move mesh to avoid jitter
  97942. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  97943. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  97944. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  97945. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  97946. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  97947. }
  97948. });
  97949. };
  97950. /**
  97951. * Force relase the drag action by code.
  97952. */
  97953. PointerDragBehavior.prototype.releaseDrag = function () {
  97954. this.dragging = false;
  97955. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  97956. this.currentDraggingPointerID = -1;
  97957. this._moving = false;
  97958. // Reattach camera controls
  97959. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  97960. this._scene.activeCamera.attachControl(this._attachedElement, true);
  97961. }
  97962. };
  97963. /**
  97964. * Simulates the start of a pointer drag event on the behavior
  97965. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  97966. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  97967. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  97968. */
  97969. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  97970. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  97971. this._startDrag(pointerId, fromRay, startPickedPoint);
  97972. var lastRay = this._lastPointerRay[pointerId];
  97973. if (pointerId === PointerDragBehavior._AnyMouseID) {
  97974. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  97975. }
  97976. if (lastRay) {
  97977. // if there was a last pointer ray drag the object there
  97978. this._moveDrag(lastRay);
  97979. }
  97980. };
  97981. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  97982. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  97983. return;
  97984. }
  97985. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  97986. // Create start ray from the camera to the object
  97987. if (fromRay) {
  97988. this._startDragRay.direction.copyFrom(fromRay.direction);
  97989. this._startDragRay.origin.copyFrom(fromRay.origin);
  97990. }
  97991. else {
  97992. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  97993. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  97994. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  97995. }
  97996. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  97997. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  97998. if (pickedPoint) {
  97999. this.dragging = true;
  98000. this.currentDraggingPointerID = pointerId;
  98001. this.lastDragPosition.copyFrom(pickedPoint);
  98002. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  98003. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  98004. // Detatch camera controls
  98005. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  98006. if (this._scene.activeCamera.inputs.attachedElement) {
  98007. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  98008. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  98009. }
  98010. else {
  98011. this._attachedElement = null;
  98012. }
  98013. }
  98014. }
  98015. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  98016. };
  98017. PointerDragBehavior.prototype._moveDrag = function (ray) {
  98018. this._moving = true;
  98019. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  98020. if (pickedPoint) {
  98021. if (this.updateDragPlane) {
  98022. this._updateDragPlanePosition(ray, pickedPoint);
  98023. }
  98024. var dragLength = 0;
  98025. // depending on the drag mode option drag accordingly
  98026. if (this._options.dragAxis) {
  98027. // Convert local drag axis to world
  98028. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  98029. // Project delta drag from the drag plane onto the drag axis
  98030. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  98031. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  98032. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  98033. }
  98034. else {
  98035. dragLength = this._dragDelta.length();
  98036. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  98037. }
  98038. this._targetPosition.addInPlace(this._dragDelta);
  98039. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  98040. this.lastDragPosition.copyFrom(pickedPoint);
  98041. }
  98042. };
  98043. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  98044. var _this = this;
  98045. if (!ray) {
  98046. return null;
  98047. }
  98048. // Calculate angle between plane normal and ray
  98049. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  98050. // Correct if ray is casted from oposite side
  98051. if (angle > Math.PI / 2) {
  98052. angle = Math.PI - angle;
  98053. }
  98054. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  98055. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  98056. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  98057. // Invert ray direction along the towards object axis
  98058. this._tmpVector.copyFrom(ray.direction);
  98059. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  98060. this._alternatePickedPoint.normalize();
  98061. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  98062. this._tmpVector.addInPlace(this._alternatePickedPoint);
  98063. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  98064. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  98065. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  98066. this._alternatePickedPoint.addInPlace(this._tmpVector);
  98067. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  98068. return this._alternatePickedPoint;
  98069. }
  98070. else {
  98071. return null;
  98072. }
  98073. }
  98074. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  98075. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  98076. return pickResult.pickedPoint;
  98077. }
  98078. else {
  98079. return null;
  98080. }
  98081. };
  98082. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  98083. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  98084. this._pointA.copyFrom(dragPlanePosition);
  98085. if (this._options.dragAxis) {
  98086. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  98087. // Calculate plane normal in direction of camera but perpendicular to drag axis
  98088. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  98089. ray.origin.subtractToRef(this._pointA, this._pointC);
  98090. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  98091. // Get perpendicular line from direction to camera and drag axis
  98092. this._pointB.subtractToRef(this._pointA, this._lineA);
  98093. this._pointC.subtractToRef(this._pointA, this._lineB);
  98094. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  98095. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  98096. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  98097. this._lookAt.normalize();
  98098. this._dragPlane.position.copyFrom(this._pointA);
  98099. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  98100. this._dragPlane.lookAt(this._lookAt);
  98101. }
  98102. else if (this._options.dragPlaneNormal) {
  98103. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  98104. this._dragPlane.position.copyFrom(this._pointA);
  98105. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  98106. this._dragPlane.lookAt(this._lookAt);
  98107. }
  98108. else {
  98109. this._dragPlane.position.copyFrom(this._pointA);
  98110. this._dragPlane.lookAt(ray.origin);
  98111. }
  98112. this._dragPlane.computeWorldMatrix(true);
  98113. };
  98114. /**
  98115. * Detaches the behavior from the mesh
  98116. */
  98117. PointerDragBehavior.prototype.detach = function () {
  98118. if (this._pointerObserver) {
  98119. this._scene.onPointerObservable.remove(this._pointerObserver);
  98120. }
  98121. if (this._beforeRenderObserver) {
  98122. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98123. }
  98124. };
  98125. PointerDragBehavior._AnyMouseID = -2;
  98126. return PointerDragBehavior;
  98127. }());
  98128. BABYLON.PointerDragBehavior = PointerDragBehavior;
  98129. })(BABYLON || (BABYLON = {}));
  98130. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  98131. var BABYLON;
  98132. (function (BABYLON) {
  98133. /**
  98134. * A behavior that when attached to a mesh will allow the mesh to be scaled
  98135. */
  98136. var MultiPointerScaleBehavior = /** @class */ (function () {
  98137. /**
  98138. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  98139. */
  98140. function MultiPointerScaleBehavior() {
  98141. this._startDistance = 0;
  98142. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  98143. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  98144. this._sceneRenderObserver = null;
  98145. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  98146. this._dragBehaviorA.moveAttached = false;
  98147. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  98148. this._dragBehaviorB.moveAttached = false;
  98149. }
  98150. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  98151. /**
  98152. * The name of the behavior
  98153. */
  98154. get: function () {
  98155. return "MultiPointerScale";
  98156. },
  98157. enumerable: true,
  98158. configurable: true
  98159. });
  98160. /**
  98161. * Initializes the behavior
  98162. */
  98163. MultiPointerScaleBehavior.prototype.init = function () { };
  98164. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  98165. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  98166. };
  98167. /**
  98168. * Attaches the scale behavior the passed in mesh
  98169. * @param ownerNode The mesh that will be scaled around once attached
  98170. */
  98171. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  98172. var _this = this;
  98173. this._ownerNode = ownerNode;
  98174. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  98175. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  98176. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98177. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  98178. _this._dragBehaviorA.releaseDrag();
  98179. }
  98180. else {
  98181. _this._initialScale.copyFrom(ownerNode.scaling);
  98182. _this._startDistance = _this._getCurrentDistance();
  98183. }
  98184. }
  98185. });
  98186. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  98187. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98188. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  98189. _this._dragBehaviorB.releaseDrag();
  98190. }
  98191. else {
  98192. _this._initialScale.copyFrom(ownerNode.scaling);
  98193. _this._startDistance = _this._getCurrentDistance();
  98194. }
  98195. }
  98196. });
  98197. // Once both drag behaviors are active scale based on the distance between the two pointers
  98198. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  98199. behavior.onDragObservable.add(function () {
  98200. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98201. var ratio = _this._getCurrentDistance() / _this._startDistance;
  98202. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  98203. }
  98204. });
  98205. });
  98206. ownerNode.addBehavior(this._dragBehaviorA);
  98207. ownerNode.addBehavior(this._dragBehaviorB);
  98208. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  98209. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  98210. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98211. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  98212. if (change.length() > 0.01) {
  98213. ownerNode.scaling.addInPlace(change);
  98214. }
  98215. }
  98216. });
  98217. };
  98218. /**
  98219. * Detaches the behavior from the mesh
  98220. */
  98221. MultiPointerScaleBehavior.prototype.detach = function () {
  98222. var _this = this;
  98223. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  98224. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  98225. behavior.onDragStartObservable.clear();
  98226. behavior.onDragObservable.clear();
  98227. _this._ownerNode.removeBehavior(behavior);
  98228. });
  98229. };
  98230. return MultiPointerScaleBehavior;
  98231. }());
  98232. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  98233. })(BABYLON || (BABYLON = {}));
  98234. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  98235. var BABYLON;
  98236. (function (BABYLON) {
  98237. /**
  98238. * 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
  98239. */
  98240. var SixDofDragBehavior = /** @class */ (function () {
  98241. /**
  98242. * Instantiates 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
  98243. */
  98244. function SixDofDragBehavior() {
  98245. this._sceneRenderObserver = null;
  98246. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  98247. this._moving = false;
  98248. this._startingOrientation = new BABYLON.Quaternion();
  98249. /**
  98250. * 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: 3)
  98251. */
  98252. this.zDragFactor = 3;
  98253. /**
  98254. * If the behavior is currently in a dragging state
  98255. */
  98256. this.dragging = false;
  98257. /**
  98258. * 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)
  98259. */
  98260. this.dragDeltaRatio = 0.2;
  98261. /**
  98262. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  98263. */
  98264. this.currentDraggingPointerID = -1;
  98265. /**
  98266. * If camera controls should be detached during the drag
  98267. */
  98268. this.detachCameraControls = true;
  98269. /**
  98270. * Fires each time a drag starts
  98271. */
  98272. this.onDragStartObservable = new BABYLON.Observable();
  98273. /**
  98274. * Fires each time a drag ends (eg. mouse release after drag)
  98275. */
  98276. this.onDragEndObservable = new BABYLON.Observable();
  98277. }
  98278. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  98279. /**
  98280. * The name of the behavior
  98281. */
  98282. get: function () {
  98283. return "SixDofDrag";
  98284. },
  98285. enumerable: true,
  98286. configurable: true
  98287. });
  98288. /**
  98289. * Initializes the behavior
  98290. */
  98291. SixDofDragBehavior.prototype.init = function () { };
  98292. /**
  98293. * Attaches the scale behavior the passed in mesh
  98294. * @param ownerNode The mesh that will be scaled around once attached
  98295. */
  98296. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  98297. var _this = this;
  98298. this._ownerNode = ownerNode;
  98299. this._scene = this._ownerNode.getScene();
  98300. if (!SixDofDragBehavior._virtualScene) {
  98301. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  98302. this._scene.getEngine().scenes.pop();
  98303. }
  98304. var pickedMesh = null;
  98305. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  98306. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  98307. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  98308. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  98309. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  98310. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  98311. var pickPredicate = function (m) {
  98312. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  98313. };
  98314. var attachedElement = null;
  98315. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  98316. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  98317. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  98318. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  98319. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  98320. }
  98321. pickedMesh = _this._ownerNode;
  98322. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  98323. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  98324. // Set position and orientation of the controller
  98325. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  98326. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  98327. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  98328. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98329. pickedMesh.computeWorldMatrix();
  98330. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  98331. if (!pickedMesh.rotationQuaternion) {
  98332. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  98333. }
  98334. var oldParent = pickedMesh.parent;
  98335. pickedMesh.setParent(null);
  98336. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  98337. pickedMesh.setParent(oldParent);
  98338. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  98339. // Update state
  98340. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  98341. _this.dragging = true;
  98342. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  98343. // Detatch camera controls
  98344. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  98345. if (_this._scene.activeCamera.inputs.attachedElement) {
  98346. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  98347. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  98348. }
  98349. else {
  98350. attachedElement = null;
  98351. }
  98352. }
  98353. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  98354. _this.onDragStartObservable.notifyObservers({});
  98355. }
  98356. }
  98357. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  98358. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  98359. _this.dragging = false;
  98360. _this._moving = false;
  98361. _this.currentDraggingPointerID = -1;
  98362. pickedMesh = null;
  98363. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98364. // Reattach camera controls
  98365. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  98366. _this._scene.activeCamera.attachControl(attachedElement, true);
  98367. }
  98368. _this.onDragEndObservable.notifyObservers({});
  98369. }
  98370. }
  98371. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  98372. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  98373. var zDragFactor = _this.zDragFactor;
  98374. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  98375. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  98376. zDragFactor = 0;
  98377. }
  98378. // Calculate controller drag distance in controller space
  98379. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  98380. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  98381. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  98382. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  98383. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  98384. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  98385. if (_this._virtualDragMesh.position.z < 0) {
  98386. _this._virtualDragMesh.position.z = 0;
  98387. }
  98388. // Update the controller position
  98389. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  98390. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  98391. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98392. // Move the virtualObjectsPosition into the picked mesh's space if needed
  98393. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  98394. if (pickedMesh.parent) {
  98395. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  98396. }
  98397. if (!_this._moving) {
  98398. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  98399. }
  98400. _this._moving = true;
  98401. }
  98402. }
  98403. });
  98404. var tmpQuaternion = new BABYLON.Quaternion();
  98405. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  98406. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  98407. if (_this.dragging && _this._moving && pickedMesh) {
  98408. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  98409. // Slowly move mesh to avoid jitter
  98410. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  98411. // Get change in rotation
  98412. tmpQuaternion.copyFrom(_this._startingOrientation);
  98413. tmpQuaternion.x = -tmpQuaternion.x;
  98414. tmpQuaternion.y = -tmpQuaternion.y;
  98415. tmpQuaternion.z = -tmpQuaternion.z;
  98416. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  98417. // Convert change in rotation to only y axis rotation
  98418. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  98419. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  98420. // Slowly move mesh to avoid jitter
  98421. var oldParent = pickedMesh.parent;
  98422. pickedMesh.setParent(null);
  98423. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  98424. pickedMesh.setParent(oldParent);
  98425. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  98426. }
  98427. });
  98428. };
  98429. /**
  98430. * Detaches the behavior from the mesh
  98431. */
  98432. SixDofDragBehavior.prototype.detach = function () {
  98433. if (this._scene) {
  98434. this._scene.onPointerObservable.remove(this._pointerObserver);
  98435. }
  98436. if (this._ownerNode) {
  98437. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  98438. }
  98439. if (this._virtualOriginMesh) {
  98440. this._virtualOriginMesh.dispose();
  98441. }
  98442. if (this._virtualDragMesh) {
  98443. this._virtualDragMesh.dispose();
  98444. }
  98445. this.onDragEndObservable.clear();
  98446. this.onDragStartObservable.clear();
  98447. };
  98448. return SixDofDragBehavior;
  98449. }());
  98450. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  98451. })(BABYLON || (BABYLON = {}));
  98452. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  98453. var BABYLON;
  98454. (function (BABYLON) {
  98455. /**
  98456. * @hidden
  98457. */
  98458. var FaceDirectionInfo = /** @class */ (function () {
  98459. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  98460. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  98461. if (diff === void 0) { diff = 0; }
  98462. if (ignore === void 0) { ignore = false; }
  98463. this.direction = direction;
  98464. this.rotatedDirection = rotatedDirection;
  98465. this.diff = diff;
  98466. this.ignore = ignore;
  98467. }
  98468. return FaceDirectionInfo;
  98469. }());
  98470. /**
  98471. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  98472. */
  98473. var AttachToBoxBehavior = /** @class */ (function () {
  98474. /**
  98475. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  98476. * @param ui The transform node that should be attched to the mesh
  98477. */
  98478. function AttachToBoxBehavior(ui) {
  98479. this.ui = ui;
  98480. /**
  98481. * The name of the behavior
  98482. */
  98483. this.name = "AttachToBoxBehavior";
  98484. /**
  98485. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  98486. */
  98487. this.distanceAwayFromFace = 0.15;
  98488. /**
  98489. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  98490. */
  98491. this.distanceAwayFromBottomOfFace = 0.15;
  98492. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  98493. this._tmpMatrix = new BABYLON.Matrix();
  98494. this._tmpVector = new BABYLON.Vector3();
  98495. this._zeroVector = BABYLON.Vector3.Zero();
  98496. this._lookAtTmpMatrix = new BABYLON.Matrix();
  98497. /* Does nothing */
  98498. }
  98499. /**
  98500. * Initializes the behavior
  98501. */
  98502. AttachToBoxBehavior.prototype.init = function () {
  98503. /* Does nothing */
  98504. };
  98505. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  98506. var _this = this;
  98507. // Go over each face and calculate the angle between the face's normal and targetDirection
  98508. this._faceVectors.forEach(function (v) {
  98509. if (!_this._target.rotationQuaternion) {
  98510. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  98511. }
  98512. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  98513. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  98514. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  98515. });
  98516. // Return the face information of the one with the normal closeset to target direction
  98517. return this._faceVectors.reduce(function (min, p) {
  98518. if (min.ignore) {
  98519. return p;
  98520. }
  98521. else if (p.ignore) {
  98522. return min;
  98523. }
  98524. else {
  98525. return min.diff < p.diff ? min : p;
  98526. }
  98527. }, this._faceVectors[0]);
  98528. };
  98529. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  98530. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  98531. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  98532. this._lookAtTmpMatrix.invert();
  98533. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  98534. };
  98535. /**
  98536. * Attaches the AttachToBoxBehavior to the passed in mesh
  98537. * @param target The mesh that the specified node will be attached to
  98538. */
  98539. AttachToBoxBehavior.prototype.attach = function (target) {
  98540. var _this = this;
  98541. this._target = target;
  98542. this._scene = this._target.getScene();
  98543. // Every frame, update the app bars position
  98544. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  98545. if (!_this._scene.activeCamera) {
  98546. return;
  98547. }
  98548. // Find the face closest to the cameras position
  98549. var cameraPos = _this._scene.activeCamera.position;
  98550. if (_this._scene.activeCamera.devicePosition) {
  98551. cameraPos = _this._scene.activeCamera.devicePosition;
  98552. }
  98553. var facing = _this._closestFace(cameraPos.subtract(target.position));
  98554. if (_this._scene.activeCamera.leftCamera) {
  98555. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  98556. }
  98557. else {
  98558. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  98559. }
  98560. // Get camera up direction
  98561. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  98562. // Ignore faces to not select a parrelel face for the up vector of the UI
  98563. _this._faceVectors.forEach(function (v) {
  98564. if (facing.direction.x && v.direction.x) {
  98565. v.ignore = true;
  98566. }
  98567. if (facing.direction.y && v.direction.y) {
  98568. v.ignore = true;
  98569. }
  98570. if (facing.direction.z && v.direction.z) {
  98571. v.ignore = true;
  98572. }
  98573. });
  98574. var facingUp = _this._closestFace(_this._tmpVector);
  98575. // Unignore faces
  98576. _this._faceVectors.forEach(function (v) {
  98577. v.ignore = false;
  98578. });
  98579. // Position the app bar on that face
  98580. _this.ui.position.copyFrom(target.position);
  98581. if (facing.direction.x) {
  98582. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98583. _this.ui.position.addInPlace(_this._tmpVector);
  98584. }
  98585. if (facing.direction.y) {
  98586. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98587. _this.ui.position.addInPlace(_this._tmpVector);
  98588. }
  98589. if (facing.direction.z) {
  98590. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98591. _this.ui.position.addInPlace(_this._tmpVector);
  98592. }
  98593. // Rotate to be oriented properly to the camera
  98594. if (!_this.ui.rotationQuaternion) {
  98595. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  98596. }
  98597. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  98598. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  98599. // Place ui the correct distance from the bottom of the mesh
  98600. if (facingUp.direction.x) {
  98601. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  98602. }
  98603. if (facingUp.direction.y) {
  98604. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  98605. }
  98606. if (facingUp.direction.z) {
  98607. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  98608. }
  98609. _this.ui.position.addInPlace(_this._tmpVector);
  98610. });
  98611. };
  98612. /**
  98613. * Detaches the behavior from the mesh
  98614. */
  98615. AttachToBoxBehavior.prototype.detach = function () {
  98616. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  98617. };
  98618. return AttachToBoxBehavior;
  98619. }());
  98620. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  98621. })(BABYLON || (BABYLON = {}));
  98622. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  98623. var BABYLON;
  98624. (function (BABYLON) {
  98625. /**
  98626. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  98627. */
  98628. var FadeInOutBehavior = /** @class */ (function () {
  98629. /**
  98630. * Instatiates the FadeInOutBehavior
  98631. */
  98632. function FadeInOutBehavior() {
  98633. var _this = this;
  98634. /**
  98635. * Time in milliseconds to delay before fading in (Default: 0)
  98636. */
  98637. this.delay = 0;
  98638. /**
  98639. * Time in milliseconds for the mesh to fade in (Default: 300)
  98640. */
  98641. this.fadeInTime = 300;
  98642. this._millisecondsPerFrame = 1000 / 60;
  98643. this._hovered = false;
  98644. this._hoverValue = 0;
  98645. this._ownerNode = null;
  98646. this._update = function () {
  98647. if (_this._ownerNode) {
  98648. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  98649. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  98650. if (_this._ownerNode.visibility > 1) {
  98651. _this._setAllVisibility(_this._ownerNode, 1);
  98652. _this._hoverValue = _this.fadeInTime + _this.delay;
  98653. return;
  98654. }
  98655. else if (_this._ownerNode.visibility < 0) {
  98656. _this._setAllVisibility(_this._ownerNode, 0);
  98657. if (_this._hoverValue < 0) {
  98658. _this._hoverValue = 0;
  98659. return;
  98660. }
  98661. }
  98662. setTimeout(_this._update, _this._millisecondsPerFrame);
  98663. }
  98664. };
  98665. }
  98666. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  98667. /**
  98668. * The name of the behavior
  98669. */
  98670. get: function () {
  98671. return "FadeInOut";
  98672. },
  98673. enumerable: true,
  98674. configurable: true
  98675. });
  98676. /**
  98677. * Initializes the behavior
  98678. */
  98679. FadeInOutBehavior.prototype.init = function () {
  98680. };
  98681. /**
  98682. * Attaches the fade behavior on the passed in mesh
  98683. * @param ownerNode The mesh that will be faded in/out once attached
  98684. */
  98685. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  98686. this._ownerNode = ownerNode;
  98687. this._setAllVisibility(this._ownerNode, 0);
  98688. };
  98689. /**
  98690. * Detaches the behavior from the mesh
  98691. */
  98692. FadeInOutBehavior.prototype.detach = function () {
  98693. this._ownerNode = null;
  98694. };
  98695. /**
  98696. * Triggers the mesh to begin fading in or out
  98697. * @param value if the object should fade in or out (true to fade in)
  98698. */
  98699. FadeInOutBehavior.prototype.fadeIn = function (value) {
  98700. this._hovered = value;
  98701. this._update();
  98702. };
  98703. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  98704. var _this = this;
  98705. mesh.visibility = value;
  98706. mesh.getChildMeshes().forEach(function (c) {
  98707. _this._setAllVisibility(c, value);
  98708. });
  98709. };
  98710. return FadeInOutBehavior;
  98711. }());
  98712. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  98713. })(BABYLON || (BABYLON = {}));
  98714. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  98715. var BABYLON;
  98716. (function (BABYLON) {
  98717. /**
  98718. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  98719. */
  98720. var Gizmo = /** @class */ (function () {
  98721. /**
  98722. * Creates a gizmo
  98723. * @param gizmoLayer The utility layer the gizmo will be added to
  98724. */
  98725. function Gizmo(
  98726. /** The utility layer the gizmo will be added to */
  98727. gizmoLayer) {
  98728. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98729. var _this = this;
  98730. this.gizmoLayer = gizmoLayer;
  98731. /**
  98732. * Ratio for the scale of the gizmo (Default: 1)
  98733. */
  98734. this.scaleRatio = 1;
  98735. this._tmpMatrix = new BABYLON.Matrix();
  98736. /**
  98737. * If a custom mesh has been set (Default: false)
  98738. */
  98739. this._customMeshSet = false;
  98740. /**
  98741. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  98742. */
  98743. this.updateGizmoRotationToMatchAttachedMesh = true;
  98744. /**
  98745. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  98746. */
  98747. this.updateGizmoPositionToMatchAttachedMesh = true;
  98748. /**
  98749. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  98750. */
  98751. this._updateScale = true;
  98752. this._interactionsEnabled = true;
  98753. this._tempVector = new BABYLON.Vector3();
  98754. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  98755. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  98756. _this._update();
  98757. });
  98758. this.attachedMesh = null;
  98759. }
  98760. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  98761. /**
  98762. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  98763. * * When set, interactions will be enabled
  98764. */
  98765. get: function () {
  98766. return this._attachedMesh;
  98767. },
  98768. set: function (value) {
  98769. this._attachedMesh = value;
  98770. this._rootMesh.setEnabled(value ? true : false);
  98771. this._attachedMeshChanged(value);
  98772. },
  98773. enumerable: true,
  98774. configurable: true
  98775. });
  98776. /**
  98777. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  98778. * @param mesh The mesh to replace the default mesh of the gizmo
  98779. */
  98780. Gizmo.prototype.setCustomMesh = function (mesh) {
  98781. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  98782. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  98783. }
  98784. this._rootMesh.getChildMeshes().forEach(function (c) {
  98785. c.dispose();
  98786. });
  98787. mesh.parent = this._rootMesh;
  98788. this._customMeshSet = true;
  98789. };
  98790. Gizmo.prototype._attachedMeshChanged = function (value) {
  98791. };
  98792. /**
  98793. * @hidden
  98794. * Updates the gizmo to match the attached mesh's position/rotation
  98795. */
  98796. Gizmo.prototype._update = function () {
  98797. if (this.attachedMesh) {
  98798. if (this.updateGizmoRotationToMatchAttachedMesh) {
  98799. if (!this._rootMesh.rotationQuaternion) {
  98800. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  98801. }
  98802. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  98803. this._tempVector.copyFrom(this.attachedMesh.scaling);
  98804. if (this.attachedMesh.scaling.x < 0) {
  98805. this.attachedMesh.scaling.x *= -1;
  98806. }
  98807. if (this.attachedMesh.scaling.y < 0) {
  98808. this.attachedMesh.scaling.y *= -1;
  98809. }
  98810. if (this.attachedMesh.scaling.z < 0) {
  98811. this.attachedMesh.scaling.z *= -1;
  98812. }
  98813. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  98814. this.attachedMesh.scaling.copyFrom(this._tempVector);
  98815. this.attachedMesh.computeWorldMatrix();
  98816. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  98817. }
  98818. else if (this._rootMesh.rotationQuaternion) {
  98819. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  98820. }
  98821. if (this.updateGizmoPositionToMatchAttachedMesh) {
  98822. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  98823. }
  98824. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  98825. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  98826. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  98827. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  98828. }
  98829. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  98830. var dist = this._tempVector.length() * this.scaleRatio;
  98831. this._rootMesh.scaling.set(dist, dist, dist);
  98832. }
  98833. }
  98834. };
  98835. /**
  98836. * Disposes of the gizmo
  98837. */
  98838. Gizmo.prototype.dispose = function () {
  98839. this._rootMesh.dispose();
  98840. if (this._beforeRenderObserver) {
  98841. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98842. }
  98843. };
  98844. return Gizmo;
  98845. }());
  98846. BABYLON.Gizmo = Gizmo;
  98847. })(BABYLON || (BABYLON = {}));
  98848. //# sourceMappingURL=babylon.gizmo.js.map
  98849. var BABYLON;
  98850. (function (BABYLON) {
  98851. /**
  98852. * Single axis drag gizmo
  98853. */
  98854. var AxisDragGizmo = /** @class */ (function (_super) {
  98855. __extends(AxisDragGizmo, _super);
  98856. /**
  98857. * Creates an AxisDragGizmo
  98858. * @param gizmoLayer The utility layer the gizmo will be added to
  98859. * @param dragAxis The axis which the gizmo will be able to drag on
  98860. * @param color The color of the gizmo
  98861. */
  98862. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  98863. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98864. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98865. var _this = _super.call(this, gizmoLayer) || this;
  98866. _this._pointerObserver = null;
  98867. /**
  98868. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98869. */
  98870. _this.snapDistance = 0;
  98871. /**
  98872. * Event that fires each time the gizmo snaps to a new location.
  98873. * * snapDistance is the the change in distance
  98874. */
  98875. _this.onSnapObservable = new BABYLON.Observable();
  98876. // Create Material
  98877. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98878. coloredMaterial.disableLighting = true;
  98879. coloredMaterial.emissiveColor = color;
  98880. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98881. hoverMaterial.disableLighting = true;
  98882. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98883. // Build mesh on root node
  98884. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98885. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  98886. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98887. arrowTail.color = coloredMaterial.emissiveColor;
  98888. arrow.addChild(arrowMesh);
  98889. arrow.addChild(arrowTail);
  98890. // Position arrow pointing in its drag axis
  98891. arrowMesh.scaling.scaleInPlace(0.05);
  98892. arrowMesh.material = coloredMaterial;
  98893. arrowMesh.rotation.x = Math.PI / 2;
  98894. arrowMesh.position.z += 0.3;
  98895. arrowTail.scaling.scaleInPlace(0.26);
  98896. arrowTail.rotation.x = Math.PI / 2;
  98897. arrowTail.material = coloredMaterial;
  98898. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  98899. arrow.scaling.scaleInPlace(1 / 3);
  98900. _this._rootMesh.addChild(arrow);
  98901. var currentSnapDragDistance = 0;
  98902. var tmpVector = new BABYLON.Vector3();
  98903. var tmpSnapEvent = { snapDistance: 0 };
  98904. // Add drag behavior to handle events when the gizmo is dragged
  98905. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98906. _this.dragBehavior.moveAttached = false;
  98907. _this._rootMesh.addBehavior(_this.dragBehavior);
  98908. var localDelta = new BABYLON.Vector3();
  98909. var tmpMatrix = new BABYLON.Matrix();
  98910. _this.dragBehavior.onDragObservable.add(function (event) {
  98911. if (_this.attachedMesh) {
  98912. // Convert delta to local translation if it has a parent
  98913. if (_this.attachedMesh.parent) {
  98914. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  98915. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  98916. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  98917. }
  98918. else {
  98919. localDelta.copyFrom(event.delta);
  98920. }
  98921. // Snapping logic
  98922. if (_this.snapDistance == 0) {
  98923. _this.attachedMesh.position.addInPlace(localDelta);
  98924. }
  98925. else {
  98926. currentSnapDragDistance += event.dragDistance;
  98927. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98928. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  98929. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98930. localDelta.normalizeToRef(tmpVector);
  98931. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  98932. _this.attachedMesh.position.addInPlace(tmpVector);
  98933. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  98934. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98935. }
  98936. }
  98937. }
  98938. });
  98939. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98940. if (_this._customMeshSet) {
  98941. return;
  98942. }
  98943. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98944. var material = isHovered ? hoverMaterial : coloredMaterial;
  98945. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98946. m.material = material;
  98947. if (m.color) {
  98948. m.color = material.emissiveColor;
  98949. }
  98950. });
  98951. });
  98952. return _this;
  98953. }
  98954. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  98955. if (this.dragBehavior) {
  98956. this.dragBehavior.enabled = value ? true : false;
  98957. }
  98958. };
  98959. /**
  98960. * Disposes of the gizmo
  98961. */
  98962. AxisDragGizmo.prototype.dispose = function () {
  98963. this.onSnapObservable.clear();
  98964. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98965. this.dragBehavior.detach();
  98966. _super.prototype.dispose.call(this);
  98967. };
  98968. return AxisDragGizmo;
  98969. }(BABYLON.Gizmo));
  98970. BABYLON.AxisDragGizmo = AxisDragGizmo;
  98971. })(BABYLON || (BABYLON = {}));
  98972. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  98973. var BABYLON;
  98974. (function (BABYLON) {
  98975. /**
  98976. * Single axis scale gizmo
  98977. */
  98978. var AxisScaleGizmo = /** @class */ (function (_super) {
  98979. __extends(AxisScaleGizmo, _super);
  98980. /**
  98981. * Creates an AxisScaleGizmo
  98982. * @param gizmoLayer The utility layer the gizmo will be added to
  98983. * @param dragAxis The axis which the gizmo will be able to scale on
  98984. * @param color The color of the gizmo
  98985. */
  98986. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  98987. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98988. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98989. var _this = _super.call(this, gizmoLayer) || this;
  98990. _this._pointerObserver = null;
  98991. /**
  98992. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98993. */
  98994. _this.snapDistance = 0;
  98995. /**
  98996. * Event that fires each time the gizmo snaps to a new location.
  98997. * * snapDistance is the the change in distance
  98998. */
  98999. _this.onSnapObservable = new BABYLON.Observable();
  99000. /**
  99001. * If the scaling operation should be done on all axis (default: false)
  99002. */
  99003. _this.uniformScaling = false;
  99004. // Create Material
  99005. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99006. _this._coloredMaterial.disableLighting = true;
  99007. _this._coloredMaterial.emissiveColor = color;
  99008. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99009. hoverMaterial.disableLighting = true;
  99010. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99011. // Build mesh on root node
  99012. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99013. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  99014. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  99015. arrowTail.color = _this._coloredMaterial.emissiveColor;
  99016. arrow.addChild(arrowMesh);
  99017. arrow.addChild(arrowTail);
  99018. // Position arrow pointing in its drag axis
  99019. arrowMesh.scaling.scaleInPlace(0.1);
  99020. arrowMesh.material = _this._coloredMaterial;
  99021. arrowMesh.rotation.x = Math.PI / 2;
  99022. arrowMesh.position.z += 0.3;
  99023. arrowTail.scaling.scaleInPlace(0.26);
  99024. arrowTail.rotation.x = Math.PI / 2;
  99025. arrowTail.material = _this._coloredMaterial;
  99026. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  99027. _this._rootMesh.addChild(arrow);
  99028. arrow.scaling.scaleInPlace(1 / 3);
  99029. // Add drag behavior to handle events when the gizmo is dragged
  99030. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99031. _this.dragBehavior.moveAttached = false;
  99032. _this._rootMesh.addBehavior(_this.dragBehavior);
  99033. var currentSnapDragDistance = 0;
  99034. var tmpVector = new BABYLON.Vector3();
  99035. var tmpSnapEvent = { snapDistance: 0 };
  99036. _this.dragBehavior.onDragObservable.add(function (event) {
  99037. if (_this.attachedMesh) {
  99038. // Snapping logic
  99039. var snapped = false;
  99040. var dragSteps = 0;
  99041. if (_this.uniformScaling) {
  99042. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  99043. if (tmpVector.y < 0) {
  99044. tmpVector.scaleInPlace(-1);
  99045. }
  99046. }
  99047. else {
  99048. tmpVector.copyFrom(dragAxis);
  99049. }
  99050. if (_this.snapDistance == 0) {
  99051. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  99052. }
  99053. else {
  99054. currentSnapDragDistance += event.dragDistance;
  99055. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  99056. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  99057. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  99058. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  99059. snapped = true;
  99060. }
  99061. else {
  99062. tmpVector.scaleInPlace(0);
  99063. }
  99064. }
  99065. _this.attachedMesh.scaling.addInPlace(tmpVector);
  99066. if (snapped) {
  99067. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  99068. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  99069. }
  99070. }
  99071. });
  99072. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99073. if (_this._customMeshSet) {
  99074. return;
  99075. }
  99076. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  99077. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  99078. _this._rootMesh.getChildMeshes().forEach(function (m) {
  99079. m.material = material;
  99080. if (m.color) {
  99081. m.color = material.emissiveColor;
  99082. }
  99083. });
  99084. });
  99085. return _this;
  99086. }
  99087. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  99088. if (this.dragBehavior) {
  99089. this.dragBehavior.enabled = value ? true : false;
  99090. }
  99091. };
  99092. /**
  99093. * Disposes of the gizmo
  99094. */
  99095. AxisScaleGizmo.prototype.dispose = function () {
  99096. this.onSnapObservable.clear();
  99097. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99098. this.dragBehavior.detach();
  99099. _super.prototype.dispose.call(this);
  99100. };
  99101. /**
  99102. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  99103. * @param mesh The mesh to replace the default mesh of the gizmo
  99104. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  99105. */
  99106. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  99107. var _this = this;
  99108. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  99109. _super.prototype.setCustomMesh.call(this, mesh);
  99110. if (useGizmoMaterial) {
  99111. this._rootMesh.getChildMeshes().forEach(function (m) {
  99112. m.material = _this._coloredMaterial;
  99113. if (m.color) {
  99114. m.color = _this._coloredMaterial.emissiveColor;
  99115. }
  99116. });
  99117. this._customMeshSet = false;
  99118. }
  99119. };
  99120. return AxisScaleGizmo;
  99121. }(BABYLON.Gizmo));
  99122. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  99123. })(BABYLON || (BABYLON = {}));
  99124. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  99125. var BABYLON;
  99126. (function (BABYLON) {
  99127. /**
  99128. * Single plane rotation gizmo
  99129. */
  99130. var PlaneRotationGizmo = /** @class */ (function (_super) {
  99131. __extends(PlaneRotationGizmo, _super);
  99132. /**
  99133. * Creates a PlaneRotationGizmo
  99134. * @param gizmoLayer The utility layer the gizmo will be added to
  99135. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  99136. * @param color The color of the gizmo
  99137. */
  99138. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  99139. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99140. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99141. var _this = _super.call(this, gizmoLayer) || this;
  99142. _this._pointerObserver = null;
  99143. /**
  99144. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  99145. */
  99146. _this.snapDistance = 0;
  99147. /**
  99148. * Event that fires each time the gizmo snaps to a new location.
  99149. * * snapDistance is the the change in distance
  99150. */
  99151. _this.onSnapObservable = new BABYLON.Observable();
  99152. // Create Material
  99153. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99154. coloredMaterial.disableLighting = true;
  99155. coloredMaterial.emissiveColor = color;
  99156. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99157. hoverMaterial.disableLighting = true;
  99158. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99159. // Build mesh on root node
  99160. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99161. // Create circle out of lines
  99162. var tessellation = 20;
  99163. var radius = 0.8;
  99164. var points = new Array();
  99165. for (var i = 0; i < tessellation; i++) {
  99166. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  99167. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  99168. }
  99169. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  99170. rotationMesh.color = coloredMaterial.emissiveColor;
  99171. // Position arrow pointing in its drag axis
  99172. rotationMesh.scaling.scaleInPlace(0.26);
  99173. rotationMesh.material = coloredMaterial;
  99174. rotationMesh.rotation.x = Math.PI / 2;
  99175. parentMesh.addChild(rotationMesh);
  99176. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  99177. _this._rootMesh.addChild(parentMesh);
  99178. parentMesh.scaling.scaleInPlace(1 / 3);
  99179. // Add drag behavior to handle events when the gizmo is dragged
  99180. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  99181. _this.dragBehavior.moveAttached = false;
  99182. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  99183. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  99184. _this._rootMesh.addBehavior(_this.dragBehavior);
  99185. var lastDragPosition = new BABYLON.Vector3();
  99186. _this.dragBehavior.onDragStartObservable.add(function (e) {
  99187. if (_this.attachedMesh) {
  99188. lastDragPosition.copyFrom(e.dragPlanePoint);
  99189. }
  99190. });
  99191. var rotationMatrix = new BABYLON.Matrix();
  99192. var planeNormalTowardsCamera = new BABYLON.Vector3();
  99193. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  99194. var tmpSnapEvent = { snapDistance: 0 };
  99195. var currentSnapDragDistance = 0;
  99196. var tmpMatrix = new BABYLON.Matrix();
  99197. var tmpVector = new BABYLON.Vector3();
  99198. var amountToRotate = new BABYLON.Quaternion();
  99199. _this.dragBehavior.onDragObservable.add(function (event) {
  99200. if (_this.attachedMesh) {
  99201. if (!_this.attachedMesh.rotationQuaternion) {
  99202. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  99203. }
  99204. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  99205. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  99206. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  99207. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  99208. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  99209. var angle = Math.atan2(cross.length(), dot);
  99210. planeNormalTowardsCamera.copyFrom(planeNormal);
  99211. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  99212. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  99213. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  99214. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  99215. }
  99216. // Flip up vector depending on which side the camera is on
  99217. if (gizmoLayer.utilityLayerScene.activeCamera) {
  99218. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  99219. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  99220. planeNormalTowardsCamera.scaleInPlace(-1);
  99221. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  99222. }
  99223. }
  99224. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  99225. if (halfCircleSide)
  99226. angle = -angle;
  99227. // Snapping logic
  99228. var snapped = false;
  99229. if (_this.snapDistance != 0) {
  99230. currentSnapDragDistance += angle;
  99231. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  99232. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  99233. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  99234. angle = _this.snapDistance * dragSteps;
  99235. snapped = true;
  99236. }
  99237. else {
  99238. angle = 0;
  99239. }
  99240. }
  99241. // If the mesh has a parent, convert needed world rotation to local rotation
  99242. tmpMatrix.reset();
  99243. if (_this.attachedMesh.parent) {
  99244. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  99245. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  99246. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  99247. }
  99248. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  99249. var quaternionCoefficient = Math.sin(angle / 2);
  99250. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  99251. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  99252. if (tmpMatrix.determinant() > 0) {
  99253. amountToRotate.toEulerAnglesToRef(tmpVector);
  99254. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  99255. }
  99256. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  99257. // Rotate selected mesh quaternion over fixed axis
  99258. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  99259. }
  99260. else {
  99261. // Rotate selected mesh quaternion over rotated axis
  99262. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  99263. }
  99264. lastDragPosition.copyFrom(event.dragPlanePoint);
  99265. if (snapped) {
  99266. tmpSnapEvent.snapDistance = angle;
  99267. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  99268. }
  99269. }
  99270. });
  99271. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99272. if (_this._customMeshSet) {
  99273. return;
  99274. }
  99275. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  99276. var material = isHovered ? hoverMaterial : coloredMaterial;
  99277. _this._rootMesh.getChildMeshes().forEach(function (m) {
  99278. m.material = material;
  99279. if (m.color) {
  99280. m.color = material.emissiveColor;
  99281. }
  99282. });
  99283. });
  99284. return _this;
  99285. }
  99286. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  99287. if (this.dragBehavior) {
  99288. this.dragBehavior.enabled = value ? true : false;
  99289. }
  99290. };
  99291. /**
  99292. * Disposes of the gizmo
  99293. */
  99294. PlaneRotationGizmo.prototype.dispose = function () {
  99295. this.onSnapObservable.clear();
  99296. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99297. this.dragBehavior.detach();
  99298. _super.prototype.dispose.call(this);
  99299. };
  99300. return PlaneRotationGizmo;
  99301. }(BABYLON.Gizmo));
  99302. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  99303. })(BABYLON || (BABYLON = {}));
  99304. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  99305. var BABYLON;
  99306. (function (BABYLON) {
  99307. /**
  99308. * Gizmo that enables dragging a mesh along 3 axis
  99309. */
  99310. var PositionGizmo = /** @class */ (function (_super) {
  99311. __extends(PositionGizmo, _super);
  99312. /**
  99313. * Creates a PositionGizmo
  99314. * @param gizmoLayer The utility layer the gizmo will be added to
  99315. */
  99316. function PositionGizmo(gizmoLayer) {
  99317. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99318. var _this = _super.call(this, gizmoLayer) || this;
  99319. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99320. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99321. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99322. _this.attachedMesh = null;
  99323. return _this;
  99324. }
  99325. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  99326. set: function (mesh) {
  99327. if (this.xGizmo) {
  99328. this.xGizmo.attachedMesh = mesh;
  99329. this.yGizmo.attachedMesh = mesh;
  99330. this.zGizmo.attachedMesh = mesh;
  99331. }
  99332. },
  99333. enumerable: true,
  99334. configurable: true
  99335. });
  99336. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99337. get: function () {
  99338. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99339. },
  99340. set: function (value) {
  99341. if (this.xGizmo) {
  99342. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99343. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99344. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99345. }
  99346. },
  99347. enumerable: true,
  99348. configurable: true
  99349. });
  99350. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  99351. get: function () {
  99352. return this.xGizmo.snapDistance;
  99353. },
  99354. /**
  99355. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99356. */
  99357. set: function (value) {
  99358. if (this.xGizmo) {
  99359. this.xGizmo.snapDistance = value;
  99360. this.yGizmo.snapDistance = value;
  99361. this.zGizmo.snapDistance = value;
  99362. }
  99363. },
  99364. enumerable: true,
  99365. configurable: true
  99366. });
  99367. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  99368. get: function () {
  99369. return this.xGizmo.scaleRatio;
  99370. },
  99371. /**
  99372. * Ratio for the scale of the gizmo (Default: 1)
  99373. */
  99374. set: function (value) {
  99375. if (this.xGizmo) {
  99376. this.xGizmo.scaleRatio = value;
  99377. this.yGizmo.scaleRatio = value;
  99378. this.zGizmo.scaleRatio = value;
  99379. }
  99380. },
  99381. enumerable: true,
  99382. configurable: true
  99383. });
  99384. /**
  99385. * Disposes of the gizmo
  99386. */
  99387. PositionGizmo.prototype.dispose = function () {
  99388. this.xGizmo.dispose();
  99389. this.yGizmo.dispose();
  99390. this.zGizmo.dispose();
  99391. };
  99392. /**
  99393. * CustomMeshes are not supported by this gizmo
  99394. * @param mesh The mesh to replace the default mesh of the gizmo
  99395. */
  99396. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  99397. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  99398. };
  99399. return PositionGizmo;
  99400. }(BABYLON.Gizmo));
  99401. BABYLON.PositionGizmo = PositionGizmo;
  99402. })(BABYLON || (BABYLON = {}));
  99403. //# sourceMappingURL=babylon.positionGizmo.js.map
  99404. var BABYLON;
  99405. (function (BABYLON) {
  99406. /**
  99407. * Gizmo that enables rotating a mesh along 3 axis
  99408. */
  99409. var RotationGizmo = /** @class */ (function (_super) {
  99410. __extends(RotationGizmo, _super);
  99411. /**
  99412. * Creates a RotationGizmo
  99413. * @param gizmoLayer The utility layer the gizmo will be added to
  99414. */
  99415. function RotationGizmo(gizmoLayer) {
  99416. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99417. var _this = _super.call(this, gizmoLayer) || this;
  99418. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99419. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99420. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99421. _this.attachedMesh = null;
  99422. return _this;
  99423. }
  99424. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  99425. set: function (mesh) {
  99426. if (this.xGizmo) {
  99427. this.xGizmo.attachedMesh = mesh;
  99428. this.yGizmo.attachedMesh = mesh;
  99429. this.zGizmo.attachedMesh = mesh;
  99430. }
  99431. },
  99432. enumerable: true,
  99433. configurable: true
  99434. });
  99435. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99436. get: function () {
  99437. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99438. },
  99439. set: function (value) {
  99440. if (this.xGizmo) {
  99441. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99442. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99443. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99444. }
  99445. },
  99446. enumerable: true,
  99447. configurable: true
  99448. });
  99449. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  99450. get: function () {
  99451. return this.xGizmo.snapDistance;
  99452. },
  99453. /**
  99454. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99455. */
  99456. set: function (value) {
  99457. if (this.xGizmo) {
  99458. this.xGizmo.snapDistance = value;
  99459. this.yGizmo.snapDistance = value;
  99460. this.zGizmo.snapDistance = value;
  99461. }
  99462. },
  99463. enumerable: true,
  99464. configurable: true
  99465. });
  99466. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  99467. get: function () {
  99468. return this.xGizmo.scaleRatio;
  99469. },
  99470. /**
  99471. * Ratio for the scale of the gizmo (Default: 1)
  99472. */
  99473. set: function (value) {
  99474. if (this.xGizmo) {
  99475. this.xGizmo.scaleRatio = value;
  99476. this.yGizmo.scaleRatio = value;
  99477. this.zGizmo.scaleRatio = value;
  99478. }
  99479. },
  99480. enumerable: true,
  99481. configurable: true
  99482. });
  99483. /**
  99484. * Disposes of the gizmo
  99485. */
  99486. RotationGizmo.prototype.dispose = function () {
  99487. this.xGizmo.dispose();
  99488. this.yGizmo.dispose();
  99489. this.zGizmo.dispose();
  99490. };
  99491. /**
  99492. * CustomMeshes are not supported by this gizmo
  99493. * @param mesh The mesh to replace the default mesh of the gizmo
  99494. */
  99495. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  99496. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  99497. };
  99498. return RotationGizmo;
  99499. }(BABYLON.Gizmo));
  99500. BABYLON.RotationGizmo = RotationGizmo;
  99501. })(BABYLON || (BABYLON = {}));
  99502. //# sourceMappingURL=babylon.rotationGizmo.js.map
  99503. var BABYLON;
  99504. (function (BABYLON) {
  99505. /**
  99506. * Gizmo that enables scaling a mesh along 3 axis
  99507. */
  99508. var ScaleGizmo = /** @class */ (function (_super) {
  99509. __extends(ScaleGizmo, _super);
  99510. /**
  99511. * Creates a ScaleGizmo
  99512. * @param gizmoLayer The utility layer the gizmo will be added to
  99513. */
  99514. function ScaleGizmo(gizmoLayer) {
  99515. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99516. var _this = _super.call(this, gizmoLayer) || this;
  99517. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99518. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99519. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99520. // Create uniform scale gizmo
  99521. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  99522. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  99523. _this.uniformScaleGizmo.uniformScaling = true;
  99524. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  99525. octahedron.scaling.scaleInPlace(0.007);
  99526. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  99527. _this.attachedMesh = null;
  99528. return _this;
  99529. }
  99530. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  99531. set: function (mesh) {
  99532. if (this.xGizmo) {
  99533. this.xGizmo.attachedMesh = mesh;
  99534. this.yGizmo.attachedMesh = mesh;
  99535. this.zGizmo.attachedMesh = mesh;
  99536. this.uniformScaleGizmo.attachedMesh = mesh;
  99537. }
  99538. },
  99539. enumerable: true,
  99540. configurable: true
  99541. });
  99542. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99543. get: function () {
  99544. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99545. },
  99546. set: function (value) {
  99547. if (this.xGizmo) {
  99548. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99549. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99550. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99551. }
  99552. },
  99553. enumerable: true,
  99554. configurable: true
  99555. });
  99556. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  99557. get: function () {
  99558. return this.xGizmo.snapDistance;
  99559. },
  99560. /**
  99561. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99562. */
  99563. set: function (value) {
  99564. if (this.xGizmo) {
  99565. this.xGizmo.snapDistance = value;
  99566. this.yGizmo.snapDistance = value;
  99567. this.zGizmo.snapDistance = value;
  99568. this.uniformScaleGizmo.snapDistance = value;
  99569. }
  99570. },
  99571. enumerable: true,
  99572. configurable: true
  99573. });
  99574. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  99575. get: function () {
  99576. return this.xGizmo.scaleRatio;
  99577. },
  99578. /**
  99579. * Ratio for the scale of the gizmo (Default: 1)
  99580. */
  99581. set: function (value) {
  99582. if (this.xGizmo) {
  99583. this.xGizmo.scaleRatio = value;
  99584. this.yGizmo.scaleRatio = value;
  99585. this.zGizmo.scaleRatio = value;
  99586. this.uniformScaleGizmo.scaleRatio = value;
  99587. }
  99588. },
  99589. enumerable: true,
  99590. configurable: true
  99591. });
  99592. /**
  99593. * Disposes of the gizmo
  99594. */
  99595. ScaleGizmo.prototype.dispose = function () {
  99596. this.xGizmo.dispose();
  99597. this.yGizmo.dispose();
  99598. this.zGizmo.dispose();
  99599. this.uniformScaleGizmo.dispose();
  99600. };
  99601. return ScaleGizmo;
  99602. }(BABYLON.Gizmo));
  99603. BABYLON.ScaleGizmo = ScaleGizmo;
  99604. })(BABYLON || (BABYLON = {}));
  99605. //# sourceMappingURL=babylon.scaleGizmo.js.map
  99606. var BABYLON;
  99607. (function (BABYLON) {
  99608. /**
  99609. * Bounding box gizmo
  99610. */
  99611. var BoundingBoxGizmo = /** @class */ (function (_super) {
  99612. __extends(BoundingBoxGizmo, _super);
  99613. /**
  99614. * Creates an BoundingBoxGizmo
  99615. * @param gizmoLayer The utility layer the gizmo will be added to
  99616. * @param color The color of the gizmo
  99617. */
  99618. function BoundingBoxGizmo(color, gizmoLayer) {
  99619. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99620. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  99621. var _this = _super.call(this, gizmoLayer) || this;
  99622. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  99623. _this._renderObserver = null;
  99624. _this._pointerObserver = null;
  99625. _this._scaleDragSpeed = 0.2;
  99626. _this._tmpQuaternion = new BABYLON.Quaternion();
  99627. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99628. _this._tmpRotationMatrix = new BABYLON.Matrix();
  99629. /**
  99630. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  99631. */
  99632. _this.ignoreChildren = false;
  99633. /**
  99634. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  99635. */
  99636. _this.includeChildPredicate = null;
  99637. /**
  99638. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  99639. */
  99640. _this.rotationSphereSize = 0.1;
  99641. /**
  99642. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  99643. */
  99644. _this.scaleBoxSize = 0.1;
  99645. /**
  99646. * 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)
  99647. */
  99648. _this.fixedDragMeshScreenSize = false;
  99649. /**
  99650. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  99651. */
  99652. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  99653. /**
  99654. * Fired when a rotation sphere or scale box is dragged
  99655. */
  99656. _this.onDragStartObservable = new BABYLON.Observable();
  99657. /**
  99658. * Fired when a scale box is dragged
  99659. */
  99660. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  99661. /**
  99662. * Fired when a scale box drag is ended
  99663. */
  99664. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  99665. /**
  99666. * Fired when a rotation sphere is dragged
  99667. */
  99668. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  99669. /**
  99670. * Fired when a rotation sphere drag is ended
  99671. */
  99672. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  99673. /**
  99674. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  99675. */
  99676. _this.scalePivot = null;
  99677. _this._existingMeshScale = new BABYLON.Vector3();
  99678. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  99679. _this._updateScale = false;
  99680. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  99681. // Create Materials
  99682. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99683. coloredMaterial.disableLighting = true;
  99684. coloredMaterial.emissiveColor = color;
  99685. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99686. hoverColoredMaterial.disableLighting = true;
  99687. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99688. // Build bounding box out of lines
  99689. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99690. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  99691. var lines = [];
  99692. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  99693. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  99694. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  99695. 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));
  99696. 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));
  99697. 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));
  99698. 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));
  99699. 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));
  99700. 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));
  99701. 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));
  99702. 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));
  99703. 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));
  99704. lines.forEach(function (l) {
  99705. l.color = color;
  99706. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  99707. l.isPickable = false;
  99708. _this._lineBoundingBox.addChild(l);
  99709. });
  99710. _this._rootMesh.addChild(_this._lineBoundingBox);
  99711. // Create rotation spheres
  99712. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99713. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  99714. var _loop_1 = function (i_1) {
  99715. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  99716. sphere.rotationQuaternion = new BABYLON.Quaternion();
  99717. sphere.material = coloredMaterial;
  99718. // Drag behavior
  99719. _dragBehavior = new BABYLON.PointerDragBehavior({});
  99720. _dragBehavior.moveAttached = false;
  99721. _dragBehavior.updateDragPlane = false;
  99722. sphere.addBehavior(_dragBehavior);
  99723. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  99724. var totalTurnAmountOfDrag = 0;
  99725. _dragBehavior.onDragStartObservable.add(function (event) {
  99726. startingTurnDirection.copyFrom(sphere.forward);
  99727. totalTurnAmountOfDrag = 0;
  99728. });
  99729. _dragBehavior.onDragObservable.add(function (event) {
  99730. _this.onRotationSphereDragObservable.notifyObservers({});
  99731. if (_this.attachedMesh) {
  99732. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99733. var worldDragDirection = startingTurnDirection;
  99734. // Project the world right on to the drag plane
  99735. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  99736. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  99737. // project drag delta on to the resulting drag axis and rotate based on that
  99738. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  99739. // Make rotation relative to size of mesh.
  99740. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99741. // Rotate based on axis
  99742. if (!_this.attachedMesh.rotationQuaternion) {
  99743. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  99744. }
  99745. if (!_this._anchorMesh.rotationQuaternion) {
  99746. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  99747. }
  99748. // Do not allow the object to turn more than a full circle
  99749. totalTurnAmountOfDrag += projectDist;
  99750. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  99751. if (i_1 >= 8) {
  99752. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  99753. }
  99754. else if (i_1 >= 4) {
  99755. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  99756. }
  99757. else {
  99758. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  99759. }
  99760. // Rotate around center of bounding box
  99761. _this._anchorMesh.addChild(_this.attachedMesh);
  99762. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  99763. _this._anchorMesh.removeChild(_this.attachedMesh);
  99764. }
  99765. _this.updateBoundingBox();
  99766. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99767. }
  99768. });
  99769. // Selection/deselection
  99770. _dragBehavior.onDragStartObservable.add(function () {
  99771. _this.onDragStartObservable.notifyObservers({});
  99772. _this._selectNode(sphere);
  99773. });
  99774. _dragBehavior.onDragEndObservable.add(function () {
  99775. _this.onRotationSphereDragEndObservable.notifyObservers({});
  99776. _this._selectNode(null);
  99777. });
  99778. this_1._rotateSpheresParent.addChild(sphere);
  99779. };
  99780. var this_1 = this, _dragBehavior;
  99781. for (var i_1 = 0; i_1 < 12; i_1++) {
  99782. _loop_1(i_1);
  99783. }
  99784. _this._rootMesh.addChild(_this._rotateSpheresParent);
  99785. // Create scale cubes
  99786. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99787. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  99788. for (var i = 0; i < 2; i++) {
  99789. for (var j = 0; j < 2; j++) {
  99790. var _loop_2 = function () {
  99791. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  99792. box.material = coloredMaterial;
  99793. // Dragging logic
  99794. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  99795. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99796. _dragBehavior.moveAttached = false;
  99797. box.addBehavior(_dragBehavior);
  99798. _dragBehavior.onDragObservable.add(function (event) {
  99799. _this.onScaleBoxDragObservable.notifyObservers({});
  99800. if (_this.attachedMesh) {
  99801. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99802. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99803. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  99804. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  99805. _this.updateBoundingBox();
  99806. if (_this.scalePivot) {
  99807. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  99808. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  99809. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  99810. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99811. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99812. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  99813. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99814. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  99815. }
  99816. else {
  99817. // Scale from the position of the opposite corner
  99818. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  99819. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99820. }
  99821. _this._anchorMesh.addChild(_this.attachedMesh);
  99822. _this._anchorMesh.scaling.addInPlace(deltaScale);
  99823. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  99824. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  99825. }
  99826. _this._anchorMesh.removeChild(_this.attachedMesh);
  99827. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99828. }
  99829. });
  99830. // Selection/deselection
  99831. _dragBehavior.onDragStartObservable.add(function () {
  99832. _this.onDragStartObservable.notifyObservers({});
  99833. _this._selectNode(box);
  99834. });
  99835. _dragBehavior.onDragEndObservable.add(function () {
  99836. _this.onScaleBoxDragEndObservable.notifyObservers({});
  99837. _this._selectNode(null);
  99838. });
  99839. this_2._scaleBoxesParent.addChild(box);
  99840. };
  99841. var this_2 = this, _dragBehavior;
  99842. for (var k = 0; k < 2; k++) {
  99843. _loop_2();
  99844. }
  99845. }
  99846. }
  99847. _this._rootMesh.addChild(_this._scaleBoxesParent);
  99848. // Hover color change
  99849. var pointerIds = new Array();
  99850. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99851. if (!pointerIds[pointerInfo.event.pointerId]) {
  99852. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  99853. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  99854. pointerIds[pointerInfo.event.pointerId] = mesh;
  99855. mesh.material = hoverColoredMaterial;
  99856. }
  99857. });
  99858. }
  99859. else {
  99860. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  99861. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  99862. delete pointerIds[pointerInfo.event.pointerId];
  99863. }
  99864. }
  99865. });
  99866. // Update bounding box positions
  99867. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  99868. // Only update the bouding box if scaling has changed
  99869. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  99870. _this.updateBoundingBox();
  99871. }
  99872. });
  99873. _this.updateBoundingBox();
  99874. return _this;
  99875. }
  99876. /** @hidden */
  99877. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  99878. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  99879. // Save old pivot and set pivot to 0,0,0
  99880. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  99881. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  99882. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  99883. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  99884. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99885. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99886. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99887. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  99888. }
  99889. }
  99890. BoundingBoxGizmo._PivotCached++;
  99891. };
  99892. /** @hidden */
  99893. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  99894. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  99895. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  99896. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99897. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99898. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99899. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  99900. }
  99901. this._PivotCached--;
  99902. };
  99903. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  99904. if (value) {
  99905. // Reset anchor mesh to match attached mesh's scale
  99906. // This is needed to avoid invalid box/sphere position on first drag
  99907. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  99908. this._anchorMesh.addChild(value);
  99909. this._anchorMesh.removeChild(value);
  99910. BoundingBoxGizmo._RestorePivotPoint(value);
  99911. this.updateBoundingBox();
  99912. }
  99913. };
  99914. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  99915. this._rotateSpheresParent.getChildMeshes()
  99916. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  99917. m.isVisible = (!selectedMesh || m == selectedMesh);
  99918. });
  99919. };
  99920. /**
  99921. * Updates the bounding box information for the Gizmo
  99922. */
  99923. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  99924. if (this.attachedMesh) {
  99925. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  99926. this._update();
  99927. // Rotate based on axis
  99928. if (!this.attachedMesh.rotationQuaternion) {
  99929. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  99930. }
  99931. if (!this._anchorMesh.rotationQuaternion) {
  99932. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  99933. }
  99934. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99935. // Store original position and reset mesh to origin before computing the bounding box
  99936. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99937. this._tmpVector.copyFrom(this.attachedMesh.position);
  99938. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  99939. this.attachedMesh.position.set(0, 0, 0);
  99940. // Update bounding dimensions/positions
  99941. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  99942. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  99943. // Update gizmo to match bounding box scaling and rotation
  99944. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  99945. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  99946. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  99947. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  99948. this._lineBoundingBox.computeWorldMatrix();
  99949. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  99950. // restore position/rotation values
  99951. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  99952. this.attachedMesh.position.copyFrom(this._tmpVector);
  99953. }
  99954. // Update rotation sphere locations
  99955. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  99956. for (var i = 0; i < 3; i++) {
  99957. for (var j = 0; j < 2; j++) {
  99958. for (var k = 0; k < 2; k++) {
  99959. var index = ((i * 4) + (j * 2)) + k;
  99960. if (i == 0) {
  99961. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99962. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99963. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99964. }
  99965. if (i == 1) {
  99966. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  99967. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99968. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99969. }
  99970. if (i == 2) {
  99971. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  99972. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99973. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99974. }
  99975. if (this.fixedDragMeshScreenSize) {
  99976. this._rootMesh.computeWorldMatrix();
  99977. this._rotateSpheresParent.computeWorldMatrix();
  99978. rotateSpheres[index].computeWorldMatrix();
  99979. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  99980. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  99981. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  99982. }
  99983. else {
  99984. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  99985. }
  99986. }
  99987. }
  99988. }
  99989. // Update scale box locations
  99990. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  99991. for (var i = 0; i < 2; i++) {
  99992. for (var j = 0; j < 2; j++) {
  99993. for (var k = 0; k < 2; k++) {
  99994. var index = ((i * 4) + (j * 2)) + k;
  99995. if (scaleBoxes[index]) {
  99996. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99997. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99998. if (this.fixedDragMeshScreenSize) {
  99999. this._rootMesh.computeWorldMatrix();
  100000. this._scaleBoxesParent.computeWorldMatrix();
  100001. scaleBoxes[index].computeWorldMatrix();
  100002. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  100003. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  100004. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  100005. }
  100006. else {
  100007. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  100008. }
  100009. }
  100010. }
  100011. }
  100012. }
  100013. if (this.attachedMesh) {
  100014. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  100015. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  100016. }
  100017. };
  100018. /**
  100019. * Enables rotation on the specified axis and disables rotation on the others
  100020. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  100021. */
  100022. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  100023. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  100024. if (i < 4) {
  100025. m.setEnabled(axis.indexOf("x") != -1);
  100026. }
  100027. else if (i < 8) {
  100028. m.setEnabled(axis.indexOf("y") != -1);
  100029. }
  100030. else {
  100031. m.setEnabled(axis.indexOf("z") != -1);
  100032. }
  100033. });
  100034. };
  100035. /**
  100036. * Disposes of the gizmo
  100037. */
  100038. BoundingBoxGizmo.prototype.dispose = function () {
  100039. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100040. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  100041. this._lineBoundingBox.dispose();
  100042. this._rotateSpheresParent.dispose();
  100043. this._scaleBoxesParent.dispose();
  100044. _super.prototype.dispose.call(this);
  100045. };
  100046. /**
  100047. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  100048. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  100049. * @returns the bounding box mesh with the passed in mesh as a child
  100050. */
  100051. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  100052. var makeNotPickable = function (root) {
  100053. root.isPickable = false;
  100054. root.getChildMeshes().forEach(function (c) {
  100055. makeNotPickable(c);
  100056. });
  100057. };
  100058. makeNotPickable(mesh);
  100059. // Reset position to get boudning box from origin with no rotation
  100060. if (!mesh.rotationQuaternion) {
  100061. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  100062. }
  100063. var oldPos = mesh.position.clone();
  100064. var oldRot = mesh.rotationQuaternion.clone();
  100065. mesh.rotationQuaternion.set(0, 0, 0, 1);
  100066. mesh.position.set(0, 0, 0);
  100067. // Update bounding dimensions/positions
  100068. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  100069. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  100070. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  100071. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  100072. // Restore original positions
  100073. mesh.addChild(box);
  100074. mesh.rotationQuaternion.copyFrom(oldRot);
  100075. mesh.position.copyFrom(oldPos);
  100076. // Reverse parenting
  100077. mesh.removeChild(box);
  100078. box.addChild(mesh);
  100079. box.visibility = 0;
  100080. return box;
  100081. };
  100082. /**
  100083. * CustomMeshes are not supported by this gizmo
  100084. * @param mesh The mesh to replace the default mesh of the gizmo
  100085. */
  100086. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  100087. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  100088. };
  100089. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  100090. // store/remove pivot point should only be applied during their outermost calls
  100091. BoundingBoxGizmo._PivotCached = 0;
  100092. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  100093. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  100094. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  100095. return BoundingBoxGizmo;
  100096. }(BABYLON.Gizmo));
  100097. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  100098. })(BABYLON || (BABYLON = {}));
  100099. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  100100. var BABYLON;
  100101. (function (BABYLON) {
  100102. /**
  100103. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  100104. */
  100105. var GizmoManager = /** @class */ (function () {
  100106. /**
  100107. * Instatiates a gizmo manager
  100108. * @param scene the scene to overlay the gizmos on top of
  100109. */
  100110. function GizmoManager(scene) {
  100111. var _this = this;
  100112. this.scene = scene;
  100113. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  100114. this._pointerObserver = null;
  100115. this._attachedMesh = null;
  100116. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  100117. /**
  100118. * When bounding box gizmo is enabled, this can be used to track drag/end events
  100119. */
  100120. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  100121. /**
  100122. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  100123. */
  100124. this.attachableMeshes = null;
  100125. /**
  100126. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  100127. */
  100128. this.usePointerToAttachGizmos = true;
  100129. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  100130. // Instatiate/dispose gizmos based on pointer actions
  100131. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  100132. if (!_this.usePointerToAttachGizmos) {
  100133. return;
  100134. }
  100135. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100136. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  100137. var node = pointerInfo.pickInfo.pickedMesh;
  100138. if (_this.attachableMeshes == null) {
  100139. // Attach to the most parent node
  100140. while (node && node.parent != null) {
  100141. node = node.parent;
  100142. }
  100143. }
  100144. else {
  100145. // Attach to the parent node that is an attachableMesh
  100146. var found = false;
  100147. _this.attachableMeshes.forEach(function (mesh) {
  100148. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  100149. node = mesh;
  100150. found = true;
  100151. }
  100152. });
  100153. if (!found) {
  100154. node = null;
  100155. }
  100156. }
  100157. if (node instanceof BABYLON.AbstractMesh) {
  100158. _this.attachToMesh(node);
  100159. }
  100160. else {
  100161. _this.attachToMesh(null);
  100162. }
  100163. }
  100164. else {
  100165. _this.attachToMesh(null);
  100166. }
  100167. }
  100168. });
  100169. }
  100170. /**
  100171. * Attaches a set of gizmos to the specified mesh
  100172. * @param mesh The mesh the gizmo's should be attached to
  100173. */
  100174. GizmoManager.prototype.attachToMesh = function (mesh) {
  100175. if (this._attachedMesh) {
  100176. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  100177. }
  100178. this._attachedMesh = mesh;
  100179. for (var key in this.gizmos) {
  100180. var gizmo = (this.gizmos[key]);
  100181. if (gizmo && this._gizmosEnabled[key]) {
  100182. gizmo.attachedMesh = mesh;
  100183. }
  100184. }
  100185. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  100186. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  100187. }
  100188. };
  100189. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  100190. get: function () {
  100191. return this._gizmosEnabled.positionGizmo;
  100192. },
  100193. /**
  100194. * If the position gizmo is enabled
  100195. */
  100196. set: function (value) {
  100197. if (value) {
  100198. if (!this.gizmos.positionGizmo) {
  100199. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  100200. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100201. }
  100202. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  100203. }
  100204. else if (this.gizmos.positionGizmo) {
  100205. this.gizmos.positionGizmo.attachedMesh = null;
  100206. }
  100207. this._gizmosEnabled.positionGizmo = value;
  100208. },
  100209. enumerable: true,
  100210. configurable: true
  100211. });
  100212. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  100213. get: function () {
  100214. return this._gizmosEnabled.rotationGizmo;
  100215. },
  100216. /**
  100217. * If the rotation gizmo is enabled
  100218. */
  100219. set: function (value) {
  100220. if (value) {
  100221. if (!this.gizmos.rotationGizmo) {
  100222. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  100223. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100224. }
  100225. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  100226. }
  100227. else if (this.gizmos.rotationGizmo) {
  100228. this.gizmos.rotationGizmo.attachedMesh = null;
  100229. }
  100230. this._gizmosEnabled.rotationGizmo = value;
  100231. },
  100232. enumerable: true,
  100233. configurable: true
  100234. });
  100235. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  100236. get: function () {
  100237. return this._gizmosEnabled.scaleGizmo;
  100238. },
  100239. /**
  100240. * If the scale gizmo is enabled
  100241. */
  100242. set: function (value) {
  100243. if (value) {
  100244. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  100245. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  100246. }
  100247. else if (this.gizmos.scaleGizmo) {
  100248. this.gizmos.scaleGizmo.attachedMesh = null;
  100249. }
  100250. this._gizmosEnabled.scaleGizmo = value;
  100251. },
  100252. enumerable: true,
  100253. configurable: true
  100254. });
  100255. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  100256. get: function () {
  100257. return this._gizmosEnabled.boundingBoxGizmo;
  100258. },
  100259. /**
  100260. * If the boundingBox gizmo is enabled
  100261. */
  100262. set: function (value) {
  100263. if (value) {
  100264. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  100265. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  100266. if (this._attachedMesh) {
  100267. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  100268. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  100269. }
  100270. }
  100271. else if (this.gizmos.boundingBoxGizmo) {
  100272. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  100273. }
  100274. this._gizmosEnabled.boundingBoxGizmo = value;
  100275. },
  100276. enumerable: true,
  100277. configurable: true
  100278. });
  100279. /**
  100280. * Disposes of the gizmo manager
  100281. */
  100282. GizmoManager.prototype.dispose = function () {
  100283. this.scene.onPointerObservable.remove(this._pointerObserver);
  100284. for (var key in this.gizmos) {
  100285. var gizmo = (this.gizmos[key]);
  100286. if (gizmo) {
  100287. gizmo.dispose();
  100288. }
  100289. }
  100290. this.boundingBoxDragBehavior.detach();
  100291. };
  100292. return GizmoManager;
  100293. }());
  100294. BABYLON.GizmoManager = GizmoManager;
  100295. })(BABYLON || (BABYLON = {}));
  100296. //# sourceMappingURL=babylon.gizmoManager.js.map
  100297. var BABYLON;
  100298. (function (BABYLON) {
  100299. /**
  100300. * Defines a target to use with MorphTargetManager
  100301. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  100302. */
  100303. var MorphTarget = /** @class */ (function () {
  100304. /**
  100305. * Creates a new MorphTarget
  100306. * @param name defines the name of the target
  100307. * @param influence defines the influence to use
  100308. */
  100309. function MorphTarget(
  100310. /** defines the name of the target */
  100311. name, influence, scene) {
  100312. if (influence === void 0) { influence = 0; }
  100313. if (scene === void 0) { scene = null; }
  100314. this.name = name;
  100315. /**
  100316. * Gets or sets the list of animations
  100317. */
  100318. this.animations = new Array();
  100319. this._positions = null;
  100320. this._normals = null;
  100321. this._tangents = null;
  100322. /**
  100323. * Observable raised when the influence changes
  100324. */
  100325. this.onInfluenceChanged = new BABYLON.Observable();
  100326. this._animationPropertiesOverride = null;
  100327. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100328. this.influence = influence;
  100329. }
  100330. Object.defineProperty(MorphTarget.prototype, "influence", {
  100331. /**
  100332. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  100333. */
  100334. get: function () {
  100335. return this._influence;
  100336. },
  100337. set: function (influence) {
  100338. if (this._influence === influence) {
  100339. return;
  100340. }
  100341. var previous = this._influence;
  100342. this._influence = influence;
  100343. if (this.onInfluenceChanged.hasObservers) {
  100344. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  100345. }
  100346. },
  100347. enumerable: true,
  100348. configurable: true
  100349. });
  100350. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  100351. /**
  100352. * Gets or sets the animation properties override
  100353. */
  100354. get: function () {
  100355. if (!this._animationPropertiesOverride && this._scene) {
  100356. return this._scene.animationPropertiesOverride;
  100357. }
  100358. return this._animationPropertiesOverride;
  100359. },
  100360. set: function (value) {
  100361. this._animationPropertiesOverride = value;
  100362. },
  100363. enumerable: true,
  100364. configurable: true
  100365. });
  100366. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  100367. /**
  100368. * Gets a boolean defining if the target contains position data
  100369. */
  100370. get: function () {
  100371. return !!this._positions;
  100372. },
  100373. enumerable: true,
  100374. configurable: true
  100375. });
  100376. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  100377. /**
  100378. * Gets a boolean defining if the target contains normal data
  100379. */
  100380. get: function () {
  100381. return !!this._normals;
  100382. },
  100383. enumerable: true,
  100384. configurable: true
  100385. });
  100386. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  100387. /**
  100388. * Gets a boolean defining if the target contains tangent data
  100389. */
  100390. get: function () {
  100391. return !!this._tangents;
  100392. },
  100393. enumerable: true,
  100394. configurable: true
  100395. });
  100396. /**
  100397. * Affects position data to this target
  100398. * @param data defines the position data to use
  100399. */
  100400. MorphTarget.prototype.setPositions = function (data) {
  100401. this._positions = data;
  100402. };
  100403. /**
  100404. * Gets the position data stored in this target
  100405. * @returns a FloatArray containing the position data (or null if not present)
  100406. */
  100407. MorphTarget.prototype.getPositions = function () {
  100408. return this._positions;
  100409. };
  100410. /**
  100411. * Affects normal data to this target
  100412. * @param data defines the normal data to use
  100413. */
  100414. MorphTarget.prototype.setNormals = function (data) {
  100415. this._normals = data;
  100416. };
  100417. /**
  100418. * Gets the normal data stored in this target
  100419. * @returns a FloatArray containing the normal data (or null if not present)
  100420. */
  100421. MorphTarget.prototype.getNormals = function () {
  100422. return this._normals;
  100423. };
  100424. /**
  100425. * Affects tangent data to this target
  100426. * @param data defines the tangent data to use
  100427. */
  100428. MorphTarget.prototype.setTangents = function (data) {
  100429. this._tangents = data;
  100430. };
  100431. /**
  100432. * Gets the tangent data stored in this target
  100433. * @returns a FloatArray containing the tangent data (or null if not present)
  100434. */
  100435. MorphTarget.prototype.getTangents = function () {
  100436. return this._tangents;
  100437. };
  100438. /**
  100439. * Serializes the current target into a Serialization object
  100440. * @returns the serialized object
  100441. */
  100442. MorphTarget.prototype.serialize = function () {
  100443. var serializationObject = {};
  100444. serializationObject.name = this.name;
  100445. serializationObject.influence = this.influence;
  100446. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  100447. if (this.hasNormals) {
  100448. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  100449. }
  100450. if (this.hasTangents) {
  100451. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  100452. }
  100453. // Animations
  100454. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  100455. return serializationObject;
  100456. };
  100457. // Statics
  100458. /**
  100459. * Creates a new target from serialized data
  100460. * @param serializationObject defines the serialized data to use
  100461. * @returns a new MorphTarget
  100462. */
  100463. MorphTarget.Parse = function (serializationObject) {
  100464. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  100465. result.setPositions(serializationObject.positions);
  100466. if (serializationObject.normals) {
  100467. result.setNormals(serializationObject.normals);
  100468. }
  100469. if (serializationObject.tangents) {
  100470. result.setTangents(serializationObject.tangents);
  100471. }
  100472. // Animations
  100473. if (serializationObject.animations) {
  100474. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  100475. var parsedAnimation = serializationObject.animations[animationIndex];
  100476. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  100477. }
  100478. }
  100479. return result;
  100480. };
  100481. /**
  100482. * Creates a MorphTarget from mesh data
  100483. * @param mesh defines the source mesh
  100484. * @param name defines the name to use for the new target
  100485. * @param influence defines the influence to attach to the target
  100486. * @returns a new MorphTarget
  100487. */
  100488. MorphTarget.FromMesh = function (mesh, name, influence) {
  100489. if (!name) {
  100490. name = mesh.name;
  100491. }
  100492. var result = new MorphTarget(name, influence, mesh.getScene());
  100493. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  100494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100495. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  100496. }
  100497. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  100498. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  100499. }
  100500. return result;
  100501. };
  100502. return MorphTarget;
  100503. }());
  100504. BABYLON.MorphTarget = MorphTarget;
  100505. })(BABYLON || (BABYLON = {}));
  100506. //# sourceMappingURL=babylon.morphTarget.js.map
  100507. var BABYLON;
  100508. (function (BABYLON) {
  100509. /**
  100510. * This class is used to deform meshes using morphing between different targets
  100511. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  100512. */
  100513. var MorphTargetManager = /** @class */ (function () {
  100514. /**
  100515. * Creates a new MorphTargetManager
  100516. * @param scene defines the current scene
  100517. */
  100518. function MorphTargetManager(scene) {
  100519. if (scene === void 0) { scene = null; }
  100520. this._targets = new Array();
  100521. this._targetObservable = new Array();
  100522. this._activeTargets = new BABYLON.SmartArray(16);
  100523. this._supportsNormals = false;
  100524. this._supportsTangents = false;
  100525. this._vertexCount = 0;
  100526. this._uniqueId = 0;
  100527. this._tempInfluences = new Array();
  100528. if (!scene) {
  100529. scene = BABYLON.Engine.LastCreatedScene;
  100530. }
  100531. this._scene = scene;
  100532. if (this._scene) {
  100533. this._scene.morphTargetManagers.push(this);
  100534. this._uniqueId = this._scene.getUniqueId();
  100535. }
  100536. }
  100537. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  100538. /**
  100539. * Gets the unique ID of this manager
  100540. */
  100541. get: function () {
  100542. return this._uniqueId;
  100543. },
  100544. enumerable: true,
  100545. configurable: true
  100546. });
  100547. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  100548. /**
  100549. * Gets the number of vertices handled by this manager
  100550. */
  100551. get: function () {
  100552. return this._vertexCount;
  100553. },
  100554. enumerable: true,
  100555. configurable: true
  100556. });
  100557. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  100558. /**
  100559. * Gets a boolean indicating if this manager supports morphing of normals
  100560. */
  100561. get: function () {
  100562. return this._supportsNormals;
  100563. },
  100564. enumerable: true,
  100565. configurable: true
  100566. });
  100567. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  100568. /**
  100569. * Gets a boolean indicating if this manager supports morphing of tangents
  100570. */
  100571. get: function () {
  100572. return this._supportsTangents;
  100573. },
  100574. enumerable: true,
  100575. configurable: true
  100576. });
  100577. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  100578. /**
  100579. * Gets the number of targets stored in this manager
  100580. */
  100581. get: function () {
  100582. return this._targets.length;
  100583. },
  100584. enumerable: true,
  100585. configurable: true
  100586. });
  100587. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  100588. /**
  100589. * Gets the number of influencers (ie. the number of targets with influences > 0)
  100590. */
  100591. get: function () {
  100592. return this._activeTargets.length;
  100593. },
  100594. enumerable: true,
  100595. configurable: true
  100596. });
  100597. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  100598. /**
  100599. * Gets the list of influences (one per target)
  100600. */
  100601. get: function () {
  100602. return this._influences;
  100603. },
  100604. enumerable: true,
  100605. configurable: true
  100606. });
  100607. /**
  100608. * Gets the active target at specified index. An active target is a target with an influence > 0
  100609. * @param index defines the index to check
  100610. * @returns the requested target
  100611. */
  100612. MorphTargetManager.prototype.getActiveTarget = function (index) {
  100613. return this._activeTargets.data[index];
  100614. };
  100615. /**
  100616. * Gets the target at specified index
  100617. * @param index defines the index to check
  100618. * @returns the requested target
  100619. */
  100620. MorphTargetManager.prototype.getTarget = function (index) {
  100621. return this._targets[index];
  100622. };
  100623. /**
  100624. * Add a new target to this manager
  100625. * @param target defines the target to add
  100626. */
  100627. MorphTargetManager.prototype.addTarget = function (target) {
  100628. var _this = this;
  100629. this._targets.push(target);
  100630. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  100631. _this._syncActiveTargets(needUpdate);
  100632. }));
  100633. this._syncActiveTargets(true);
  100634. };
  100635. /**
  100636. * Removes a target from the manager
  100637. * @param target defines the target to remove
  100638. */
  100639. MorphTargetManager.prototype.removeTarget = function (target) {
  100640. var index = this._targets.indexOf(target);
  100641. if (index >= 0) {
  100642. this._targets.splice(index, 1);
  100643. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  100644. this._syncActiveTargets(true);
  100645. }
  100646. };
  100647. /**
  100648. * Serializes the current manager into a Serialization object
  100649. * @returns the serialized object
  100650. */
  100651. MorphTargetManager.prototype.serialize = function () {
  100652. var serializationObject = {};
  100653. serializationObject.id = this.uniqueId;
  100654. serializationObject.targets = [];
  100655. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  100656. var target = _a[_i];
  100657. serializationObject.targets.push(target.serialize());
  100658. }
  100659. return serializationObject;
  100660. };
  100661. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  100662. var influenceCount = 0;
  100663. this._activeTargets.reset();
  100664. this._supportsNormals = true;
  100665. this._supportsTangents = true;
  100666. this._vertexCount = 0;
  100667. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  100668. var target = _a[_i];
  100669. this._activeTargets.push(target);
  100670. this._tempInfluences[influenceCount++] = target.influence;
  100671. var positions = target.getPositions();
  100672. if (positions) {
  100673. this._supportsNormals = this._supportsNormals && target.hasNormals;
  100674. this._supportsTangents = this._supportsTangents && target.hasTangents;
  100675. var vertexCount = positions.length / 3;
  100676. if (this._vertexCount === 0) {
  100677. this._vertexCount = vertexCount;
  100678. }
  100679. else if (this._vertexCount !== vertexCount) {
  100680. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  100681. return;
  100682. }
  100683. }
  100684. }
  100685. if (!this._influences || this._influences.length !== influenceCount) {
  100686. this._influences = new Float32Array(influenceCount);
  100687. }
  100688. for (var index = 0; index < influenceCount; index++) {
  100689. this._influences[index] = this._tempInfluences[index];
  100690. }
  100691. if (needUpdate) {
  100692. this.synchronize();
  100693. }
  100694. };
  100695. /**
  100696. * Syncrhonize the targets with all the meshes using this morph target manager
  100697. */
  100698. MorphTargetManager.prototype.synchronize = function () {
  100699. if (!this._scene) {
  100700. return;
  100701. }
  100702. // Flag meshes as dirty to resync with the active targets
  100703. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  100704. var mesh = _a[_i];
  100705. if (mesh.morphTargetManager === this) {
  100706. mesh._syncGeometryWithMorphTargetManager();
  100707. }
  100708. }
  100709. };
  100710. // Statics
  100711. /**
  100712. * Creates a new MorphTargetManager from serialized data
  100713. * @param serializationObject defines the serialized data
  100714. * @param scene defines the hosting scene
  100715. * @returns the new MorphTargetManager
  100716. */
  100717. MorphTargetManager.Parse = function (serializationObject, scene) {
  100718. var result = new MorphTargetManager(scene);
  100719. result._uniqueId = serializationObject.id;
  100720. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  100721. var targetData = _a[_i];
  100722. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  100723. }
  100724. return result;
  100725. };
  100726. return MorphTargetManager;
  100727. }());
  100728. BABYLON.MorphTargetManager = MorphTargetManager;
  100729. })(BABYLON || (BABYLON = {}));
  100730. //# sourceMappingURL=babylon.morphTargetManager.js.map
  100731. var BABYLON;
  100732. (function (BABYLON) {
  100733. /**
  100734. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  100735. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100736. */
  100737. var Octree = /** @class */ (function () {
  100738. /**
  100739. * Creates a octree
  100740. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100741. * @param creationFunc function to be used to instatiate the octree
  100742. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  100743. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  100744. */
  100745. function Octree(creationFunc, maxBlockCapacity,
  100746. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  100747. maxDepth) {
  100748. if (maxDepth === void 0) { maxDepth = 2; }
  100749. this.maxDepth = maxDepth;
  100750. /**
  100751. * Content stored in the octree
  100752. */
  100753. this.dynamicContent = new Array();
  100754. this._maxBlockCapacity = maxBlockCapacity || 64;
  100755. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  100756. this._creationFunc = creationFunc;
  100757. }
  100758. // Methods
  100759. /**
  100760. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  100761. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100762. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100763. * @param entries meshes to be added to the octree blocks
  100764. */
  100765. Octree.prototype.update = function (worldMin, worldMax, entries) {
  100766. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  100767. };
  100768. /**
  100769. * Adds a mesh to the octree
  100770. * @param entry Mesh to add to the octree
  100771. */
  100772. Octree.prototype.addMesh = function (entry) {
  100773. for (var index = 0; index < this.blocks.length; index++) {
  100774. var block = this.blocks[index];
  100775. block.addEntry(entry);
  100776. }
  100777. };
  100778. /**
  100779. * Selects an array of meshes within the frustum
  100780. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  100781. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  100782. * @returns array of meshes within the frustum
  100783. */
  100784. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  100785. this._selectionContent.reset();
  100786. for (var index = 0; index < this.blocks.length; index++) {
  100787. var block = this.blocks[index];
  100788. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  100789. }
  100790. if (allowDuplicate) {
  100791. this._selectionContent.concat(this.dynamicContent);
  100792. }
  100793. else {
  100794. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100795. }
  100796. return this._selectionContent;
  100797. };
  100798. /**
  100799. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  100800. * @param sphereCenter defines the bounding sphere center
  100801. * @param sphereRadius defines the bounding sphere radius
  100802. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100803. * @returns an array of objects that intersect the sphere
  100804. */
  100805. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  100806. this._selectionContent.reset();
  100807. for (var index = 0; index < this.blocks.length; index++) {
  100808. var block = this.blocks[index];
  100809. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  100810. }
  100811. if (allowDuplicate) {
  100812. this._selectionContent.concat(this.dynamicContent);
  100813. }
  100814. else {
  100815. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100816. }
  100817. return this._selectionContent;
  100818. };
  100819. /**
  100820. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  100821. * @param ray defines the ray to test with
  100822. * @returns array of intersected objects
  100823. */
  100824. Octree.prototype.intersectsRay = function (ray) {
  100825. this._selectionContent.reset();
  100826. for (var index = 0; index < this.blocks.length; index++) {
  100827. var block = this.blocks[index];
  100828. block.intersectsRay(ray, this._selectionContent);
  100829. }
  100830. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100831. return this._selectionContent;
  100832. };
  100833. /**
  100834. * @hidden
  100835. */
  100836. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  100837. target.blocks = new Array();
  100838. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100839. // Segmenting space
  100840. for (var x = 0; x < 2; x++) {
  100841. for (var y = 0; y < 2; y++) {
  100842. for (var z = 0; z < 2; z++) {
  100843. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  100844. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  100845. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  100846. block.addEntries(entries);
  100847. target.blocks.push(block);
  100848. }
  100849. }
  100850. }
  100851. };
  100852. /**
  100853. * Adds a mesh into the octree block if it intersects the block
  100854. */
  100855. Octree.CreationFuncForMeshes = function (entry, block) {
  100856. var boundingInfo = entry.getBoundingInfo();
  100857. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100858. block.entries.push(entry);
  100859. }
  100860. };
  100861. /**
  100862. * Adds a submesh into the octree block if it intersects the block
  100863. */
  100864. Octree.CreationFuncForSubMeshes = function (entry, block) {
  100865. var boundingInfo = entry.getBoundingInfo();
  100866. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100867. block.entries.push(entry);
  100868. }
  100869. };
  100870. return Octree;
  100871. }());
  100872. BABYLON.Octree = Octree;
  100873. })(BABYLON || (BABYLON = {}));
  100874. //# sourceMappingURL=babylon.octree.js.map
  100875. var BABYLON;
  100876. (function (BABYLON) {
  100877. /**
  100878. * Class used to store a cell in an octree
  100879. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100880. */
  100881. var OctreeBlock = /** @class */ (function () {
  100882. /**
  100883. * Creates a new block
  100884. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  100885. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  100886. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100887. * @param depth defines the current depth of this block in the octree
  100888. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  100889. * @param creationFunc defines a callback to call when an element is added to the block
  100890. */
  100891. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  100892. /**
  100893. * Gets the content of the current block
  100894. */
  100895. this.entries = new Array();
  100896. this._boundingVectors = new Array();
  100897. this._capacity = capacity;
  100898. this._depth = depth;
  100899. this._maxDepth = maxDepth;
  100900. this._creationFunc = creationFunc;
  100901. this._minPoint = minPoint;
  100902. this._maxPoint = maxPoint;
  100903. this._boundingVectors.push(minPoint.clone());
  100904. this._boundingVectors.push(maxPoint.clone());
  100905. this._boundingVectors.push(minPoint.clone());
  100906. this._boundingVectors[2].x = maxPoint.x;
  100907. this._boundingVectors.push(minPoint.clone());
  100908. this._boundingVectors[3].y = maxPoint.y;
  100909. this._boundingVectors.push(minPoint.clone());
  100910. this._boundingVectors[4].z = maxPoint.z;
  100911. this._boundingVectors.push(maxPoint.clone());
  100912. this._boundingVectors[5].z = minPoint.z;
  100913. this._boundingVectors.push(maxPoint.clone());
  100914. this._boundingVectors[6].x = minPoint.x;
  100915. this._boundingVectors.push(maxPoint.clone());
  100916. this._boundingVectors[7].y = minPoint.y;
  100917. }
  100918. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  100919. // Property
  100920. /**
  100921. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100922. */
  100923. get: function () {
  100924. return this._capacity;
  100925. },
  100926. enumerable: true,
  100927. configurable: true
  100928. });
  100929. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  100930. /**
  100931. * Gets the minimum vector (in world space) of the block's bounding box
  100932. */
  100933. get: function () {
  100934. return this._minPoint;
  100935. },
  100936. enumerable: true,
  100937. configurable: true
  100938. });
  100939. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  100940. /**
  100941. * Gets the maximum vector (in world space) of the block's bounding box
  100942. */
  100943. get: function () {
  100944. return this._maxPoint;
  100945. },
  100946. enumerable: true,
  100947. configurable: true
  100948. });
  100949. // Methods
  100950. /**
  100951. * Add a new element to this block
  100952. * @param entry defines the element to add
  100953. */
  100954. OctreeBlock.prototype.addEntry = function (entry) {
  100955. if (this.blocks) {
  100956. for (var index = 0; index < this.blocks.length; index++) {
  100957. var block = this.blocks[index];
  100958. block.addEntry(entry);
  100959. }
  100960. return;
  100961. }
  100962. this._creationFunc(entry, this);
  100963. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  100964. this.createInnerBlocks();
  100965. }
  100966. };
  100967. /**
  100968. * Add an array of elements to this block
  100969. * @param entries defines the array of elements to add
  100970. */
  100971. OctreeBlock.prototype.addEntries = function (entries) {
  100972. for (var index = 0; index < entries.length; index++) {
  100973. var mesh = entries[index];
  100974. this.addEntry(mesh);
  100975. }
  100976. };
  100977. /**
  100978. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  100979. * @param frustumPlanes defines the frustum planes to test
  100980. * @param selection defines the array to store current content if selection is positive
  100981. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100982. */
  100983. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  100984. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  100985. if (this.blocks) {
  100986. for (var index = 0; index < this.blocks.length; index++) {
  100987. var block = this.blocks[index];
  100988. block.select(frustumPlanes, selection, allowDuplicate);
  100989. }
  100990. return;
  100991. }
  100992. if (allowDuplicate) {
  100993. selection.concat(this.entries);
  100994. }
  100995. else {
  100996. selection.concatWithNoDuplicate(this.entries);
  100997. }
  100998. }
  100999. };
  101000. /**
  101001. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  101002. * @param sphereCenter defines the bounding sphere center
  101003. * @param sphereRadius defines the bounding sphere radius
  101004. * @param selection defines the array to store current content if selection is positive
  101005. * @param allowDuplicate defines if the selection array can contains duplicated entries
  101006. */
  101007. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  101008. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  101009. if (this.blocks) {
  101010. for (var index = 0; index < this.blocks.length; index++) {
  101011. var block = this.blocks[index];
  101012. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  101013. }
  101014. return;
  101015. }
  101016. if (allowDuplicate) {
  101017. selection.concat(this.entries);
  101018. }
  101019. else {
  101020. selection.concatWithNoDuplicate(this.entries);
  101021. }
  101022. }
  101023. };
  101024. /**
  101025. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  101026. * @param ray defines the ray to test with
  101027. * @param selection defines the array to store current content if selection is positive
  101028. */
  101029. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  101030. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  101031. if (this.blocks) {
  101032. for (var index = 0; index < this.blocks.length; index++) {
  101033. var block = this.blocks[index];
  101034. block.intersectsRay(ray, selection);
  101035. }
  101036. return;
  101037. }
  101038. selection.concatWithNoDuplicate(this.entries);
  101039. }
  101040. };
  101041. /**
  101042. * Subdivide the content into child blocks (this block will then be empty)
  101043. */
  101044. OctreeBlock.prototype.createInnerBlocks = function () {
  101045. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  101046. };
  101047. return OctreeBlock;
  101048. }());
  101049. BABYLON.OctreeBlock = OctreeBlock;
  101050. })(BABYLON || (BABYLON = {}));
  101051. //# sourceMappingURL=babylon.octreeBlock.js.map
  101052. var BABYLON;
  101053. (function (BABYLON) {
  101054. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  101055. if (maxCapacity === void 0) { maxCapacity = 64; }
  101056. if (maxDepth === void 0) { maxDepth = 2; }
  101057. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  101058. if (!component) {
  101059. component = new OctreeSceneComponent(this);
  101060. this._addComponent(component);
  101061. }
  101062. if (!this._selectionOctree) {
  101063. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  101064. }
  101065. var worldExtends = this.getWorldExtends();
  101066. // Update octree
  101067. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  101068. return this._selectionOctree;
  101069. };
  101070. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  101071. get: function () {
  101072. return this._selectionOctree;
  101073. },
  101074. enumerable: true,
  101075. configurable: true
  101076. });
  101077. /**
  101078. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  101079. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  101080. * @param maxCapacity defines the maximum size of each block (64 by default)
  101081. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  101082. * @returns the new octree
  101083. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  101084. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  101085. */
  101086. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  101087. if (maxCapacity === void 0) { maxCapacity = 64; }
  101088. if (maxDepth === void 0) { maxDepth = 2; }
  101089. var scene = this.getScene();
  101090. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  101091. if (!component) {
  101092. component = new OctreeSceneComponent(scene);
  101093. scene._addComponent(component);
  101094. }
  101095. if (!this._submeshesOctree) {
  101096. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  101097. }
  101098. this.computeWorldMatrix(true);
  101099. var boundingInfo = this.getBoundingInfo();
  101100. // Update octree
  101101. var bbox = boundingInfo.boundingBox;
  101102. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  101103. return this._submeshesOctree;
  101104. };
  101105. /**
  101106. * Defines the octree scene component responsible to manage any octrees
  101107. * in a given scene.
  101108. */
  101109. var OctreeSceneComponent = /** @class */ (function () {
  101110. /**
  101111. * Creates a new instance of the component for the given scene
  101112. * @param scene Defines the scene to register the component in
  101113. */
  101114. function OctreeSceneComponent(scene) {
  101115. /**
  101116. * The component name helpfull to identify the component in the list of scene components.
  101117. */
  101118. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  101119. /**
  101120. * Indicates if the meshes have been checked to make sure they are isEnabled()
  101121. */
  101122. this.checksIsEnabled = true;
  101123. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  101124. this.scene = scene;
  101125. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  101126. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  101127. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  101128. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  101129. }
  101130. /**
  101131. * Registers the component in a given scene
  101132. */
  101133. OctreeSceneComponent.prototype.register = function () {
  101134. var _this = this;
  101135. this.scene.onMeshRemovedObservable.add(function (mesh) {
  101136. var sceneOctree = _this.scene.selectionOctree;
  101137. if (sceneOctree !== undefined && sceneOctree !== null) {
  101138. var index = sceneOctree.dynamicContent.indexOf(mesh);
  101139. if (index !== -1) {
  101140. sceneOctree.dynamicContent.splice(index, 1);
  101141. }
  101142. }
  101143. });
  101144. this.scene.onMeshImportedObservable.add(function (mesh) {
  101145. var sceneOctree = _this.scene.selectionOctree;
  101146. if (sceneOctree !== undefined && sceneOctree !== null) {
  101147. sceneOctree.addMesh(mesh);
  101148. }
  101149. });
  101150. };
  101151. /**
  101152. * Return the list of active meshes
  101153. * @returns the list of active meshes
  101154. */
  101155. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  101156. if (this.scene._selectionOctree) {
  101157. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  101158. return selection;
  101159. }
  101160. return this.scene._getDefaultMeshCandidates();
  101161. };
  101162. /**
  101163. * Return the list of active sub meshes
  101164. * @param mesh The mesh to get the candidates sub meshes from
  101165. * @returns the list of active sub meshes
  101166. */
  101167. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  101168. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  101169. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  101170. return intersections;
  101171. }
  101172. return this.scene._getDefaultSubMeshCandidates(mesh);
  101173. };
  101174. /**
  101175. * Return the list of sub meshes intersecting with a given local ray
  101176. * @param mesh defines the mesh to find the submesh for
  101177. * @param localRay defines the ray in local space
  101178. * @returns the list of intersecting sub meshes
  101179. */
  101180. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  101181. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  101182. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  101183. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  101184. return intersections;
  101185. }
  101186. return this.scene._getDefaultSubMeshCandidates(mesh);
  101187. };
  101188. /**
  101189. * Return the list of sub meshes colliding with a collider
  101190. * @param mesh defines the mesh to find the submesh for
  101191. * @param collider defines the collider to evaluate the collision against
  101192. * @returns the list of colliding sub meshes
  101193. */
  101194. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  101195. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  101196. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  101197. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  101198. return intersections;
  101199. }
  101200. return this.scene._getDefaultSubMeshCandidates(mesh);
  101201. };
  101202. /**
  101203. * Rebuilds the elements related to this component in case of
  101204. * context lost for instance.
  101205. */
  101206. OctreeSceneComponent.prototype.rebuild = function () {
  101207. // Nothing to do here.
  101208. };
  101209. /**
  101210. * Disposes the component and the associated ressources.
  101211. */
  101212. OctreeSceneComponent.prototype.dispose = function () {
  101213. // Nothing to do here.
  101214. };
  101215. return OctreeSceneComponent;
  101216. }());
  101217. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  101218. })(BABYLON || (BABYLON = {}));
  101219. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  101220. var BABYLON;
  101221. (function (BABYLON) {
  101222. /**
  101223. * Postprocess used to generate anaglyphic rendering
  101224. */
  101225. var AnaglyphPostProcess = /** @class */ (function (_super) {
  101226. __extends(AnaglyphPostProcess, _super);
  101227. /**
  101228. * Creates a new AnaglyphPostProcess
  101229. * @param name defines postprocess name
  101230. * @param options defines creation options or target ratio scale
  101231. * @param rigCameras defines cameras using this postprocess
  101232. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  101233. * @param engine defines hosting engine
  101234. * @param reusable defines if the postprocess will be reused multiple times per frame
  101235. */
  101236. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  101237. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  101238. _this._passedProcess = rigCameras[0]._rigPostProcess;
  101239. _this.onApplyObservable.add(function (effect) {
  101240. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  101241. });
  101242. return _this;
  101243. }
  101244. return AnaglyphPostProcess;
  101245. }(BABYLON.PostProcess));
  101246. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  101247. })(BABYLON || (BABYLON = {}));
  101248. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  101249. var BABYLON;
  101250. (function (BABYLON) {
  101251. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  101252. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101253. });
  101254. /**
  101255. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  101256. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101257. */
  101258. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  101259. __extends(AnaglyphArcRotateCamera, _super);
  101260. /**
  101261. * Creates a new AnaglyphArcRotateCamera
  101262. * @param name defines camera name
  101263. * @param alpha defines alpha angle (in radians)
  101264. * @param beta defines beta angle (in radians)
  101265. * @param radius defines radius
  101266. * @param target defines camera target
  101267. * @param interaxialDistance defines distance between each color axis
  101268. * @param scene defines the hosting scene
  101269. */
  101270. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  101271. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101272. _this.interaxialDistance = interaxialDistance;
  101273. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101274. return _this;
  101275. }
  101276. /**
  101277. * Gets camera class name
  101278. * @returns AnaglyphArcRotateCamera
  101279. */
  101280. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  101281. return "AnaglyphArcRotateCamera";
  101282. };
  101283. return AnaglyphArcRotateCamera;
  101284. }(BABYLON.ArcRotateCamera));
  101285. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  101286. })(BABYLON || (BABYLON = {}));
  101287. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  101288. var BABYLON;
  101289. (function (BABYLON) {
  101290. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  101291. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101292. });
  101293. /**
  101294. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  101295. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101296. */
  101297. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  101298. __extends(AnaglyphFreeCamera, _super);
  101299. /**
  101300. * Creates a new AnaglyphFreeCamera
  101301. * @param name defines camera name
  101302. * @param position defines initial position
  101303. * @param interaxialDistance defines distance between each color axis
  101304. * @param scene defines the hosting scene
  101305. */
  101306. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  101307. var _this = _super.call(this, name, position, scene) || this;
  101308. _this.interaxialDistance = interaxialDistance;
  101309. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101310. return _this;
  101311. }
  101312. /**
  101313. * Gets camera class name
  101314. * @returns AnaglyphFreeCamera
  101315. */
  101316. AnaglyphFreeCamera.prototype.getClassName = function () {
  101317. return "AnaglyphFreeCamera";
  101318. };
  101319. return AnaglyphFreeCamera;
  101320. }(BABYLON.FreeCamera));
  101321. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  101322. })(BABYLON || (BABYLON = {}));
  101323. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  101324. var BABYLON;
  101325. (function (BABYLON) {
  101326. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  101327. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101328. });
  101329. /**
  101330. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  101331. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101332. */
  101333. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  101334. __extends(AnaglyphGamepadCamera, _super);
  101335. /**
  101336. * Creates a new AnaglyphGamepadCamera
  101337. * @param name defines camera name
  101338. * @param position defines initial position
  101339. * @param interaxialDistance defines distance between each color axis
  101340. * @param scene defines the hosting scene
  101341. */
  101342. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  101343. var _this = _super.call(this, name, position, scene) || this;
  101344. _this.interaxialDistance = interaxialDistance;
  101345. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101346. return _this;
  101347. }
  101348. /**
  101349. * Gets camera class name
  101350. * @returns AnaglyphGamepadCamera
  101351. */
  101352. AnaglyphGamepadCamera.prototype.getClassName = function () {
  101353. return "AnaglyphGamepadCamera";
  101354. };
  101355. return AnaglyphGamepadCamera;
  101356. }(BABYLON.GamepadCamera));
  101357. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  101358. })(BABYLON || (BABYLON = {}));
  101359. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  101360. var BABYLON;
  101361. (function (BABYLON) {
  101362. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  101363. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101364. });
  101365. /**
  101366. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  101367. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101368. */
  101369. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  101370. __extends(AnaglyphUniversalCamera, _super);
  101371. /**
  101372. * Creates a new AnaglyphUniversalCamera
  101373. * @param name defines camera name
  101374. * @param position defines initial position
  101375. * @param interaxialDistance defines distance between each color axis
  101376. * @param scene defines the hosting scene
  101377. */
  101378. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  101379. var _this = _super.call(this, name, position, scene) || this;
  101380. _this.interaxialDistance = interaxialDistance;
  101381. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101382. return _this;
  101383. }
  101384. /**
  101385. * Gets camera class name
  101386. * @returns AnaglyphUniversalCamera
  101387. */
  101388. AnaglyphUniversalCamera.prototype.getClassName = function () {
  101389. return "AnaglyphUniversalCamera";
  101390. };
  101391. return AnaglyphUniversalCamera;
  101392. }(BABYLON.UniversalCamera));
  101393. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  101394. })(BABYLON || (BABYLON = {}));
  101395. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  101396. var BABYLON;
  101397. (function (BABYLON) {
  101398. /**
  101399. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  101400. */
  101401. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  101402. __extends(StereoscopicInterlacePostProcess, _super);
  101403. /**
  101404. * Initializes a StereoscopicInterlacePostProcess
  101405. * @param name The name of the effect.
  101406. * @param rigCameras The rig cameras to be appled to the post process
  101407. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  101408. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  101409. * @param engine The engine which the post process will be applied. (default: current engine)
  101410. * @param reusable If the post process can be reused on the same frame. (default: false)
  101411. */
  101412. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  101413. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  101414. _this._passedProcess = rigCameras[0]._rigPostProcess;
  101415. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  101416. _this.onSizeChangedObservable.add(function () {
  101417. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  101418. });
  101419. _this.onApplyObservable.add(function (effect) {
  101420. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  101421. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  101422. });
  101423. return _this;
  101424. }
  101425. return StereoscopicInterlacePostProcess;
  101426. }(BABYLON.PostProcess));
  101427. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  101428. })(BABYLON || (BABYLON = {}));
  101429. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  101430. var BABYLON;
  101431. (function (BABYLON) {
  101432. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  101433. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101434. });
  101435. /**
  101436. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  101437. * @see http://doc.babylonjs.com/features/cameras
  101438. */
  101439. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  101440. __extends(StereoscopicArcRotateCamera, _super);
  101441. /**
  101442. * Creates a new StereoscopicArcRotateCamera
  101443. * @param name defines camera name
  101444. * @param alpha defines alpha angle (in radians)
  101445. * @param beta defines beta angle (in radians)
  101446. * @param radius defines radius
  101447. * @param target defines camera target
  101448. * @param interaxialDistance defines distance between each color axis
  101449. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101450. * @param scene defines the hosting scene
  101451. */
  101452. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  101453. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101454. _this.interaxialDistance = interaxialDistance;
  101455. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101456. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101457. return _this;
  101458. }
  101459. /**
  101460. * Gets camera class name
  101461. * @returns StereoscopicArcRotateCamera
  101462. */
  101463. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  101464. return "StereoscopicArcRotateCamera";
  101465. };
  101466. return StereoscopicArcRotateCamera;
  101467. }(BABYLON.ArcRotateCamera));
  101468. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  101469. })(BABYLON || (BABYLON = {}));
  101470. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  101471. var BABYLON;
  101472. (function (BABYLON) {
  101473. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  101474. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101475. });
  101476. /**
  101477. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  101478. * @see http://doc.babylonjs.com/features/cameras
  101479. */
  101480. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  101481. __extends(StereoscopicFreeCamera, _super);
  101482. /**
  101483. * Creates a new StereoscopicFreeCamera
  101484. * @param name defines camera name
  101485. * @param position defines initial position
  101486. * @param interaxialDistance defines distance between each color axis
  101487. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101488. * @param scene defines the hosting scene
  101489. */
  101490. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101491. var _this = _super.call(this, name, position, scene) || this;
  101492. _this.interaxialDistance = interaxialDistance;
  101493. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101494. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101495. return _this;
  101496. }
  101497. /**
  101498. * Gets camera class name
  101499. * @returns StereoscopicFreeCamera
  101500. */
  101501. StereoscopicFreeCamera.prototype.getClassName = function () {
  101502. return "StereoscopicFreeCamera";
  101503. };
  101504. return StereoscopicFreeCamera;
  101505. }(BABYLON.FreeCamera));
  101506. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  101507. })(BABYLON || (BABYLON = {}));
  101508. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  101509. var BABYLON;
  101510. (function (BABYLON) {
  101511. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  101512. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101513. });
  101514. /**
  101515. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  101516. * @see http://doc.babylonjs.com/features/cameras
  101517. */
  101518. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  101519. __extends(StereoscopicGamepadCamera, _super);
  101520. /**
  101521. * Creates a new StereoscopicGamepadCamera
  101522. * @param name defines camera name
  101523. * @param position defines initial position
  101524. * @param interaxialDistance defines distance between each color axis
  101525. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101526. * @param scene defines the hosting scene
  101527. */
  101528. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101529. var _this = _super.call(this, name, position, scene) || this;
  101530. _this.interaxialDistance = interaxialDistance;
  101531. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101532. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101533. return _this;
  101534. }
  101535. /**
  101536. * Gets camera class name
  101537. * @returns StereoscopicGamepadCamera
  101538. */
  101539. StereoscopicGamepadCamera.prototype.getClassName = function () {
  101540. return "StereoscopicGamepadCamera";
  101541. };
  101542. return StereoscopicGamepadCamera;
  101543. }(BABYLON.GamepadCamera));
  101544. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  101545. })(BABYLON || (BABYLON = {}));
  101546. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  101547. var BABYLON;
  101548. (function (BABYLON) {
  101549. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  101550. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101551. });
  101552. /**
  101553. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  101554. * @see http://doc.babylonjs.com/features/cameras
  101555. */
  101556. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  101557. __extends(StereoscopicUniversalCamera, _super);
  101558. /**
  101559. * Creates a new StereoscopicUniversalCamera
  101560. * @param name defines camera name
  101561. * @param position defines initial position
  101562. * @param interaxialDistance defines distance between each color axis
  101563. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101564. * @param scene defines the hosting scene
  101565. */
  101566. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101567. var _this = _super.call(this, name, position, scene) || this;
  101568. _this.interaxialDistance = interaxialDistance;
  101569. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101570. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101571. return _this;
  101572. }
  101573. /**
  101574. * Gets camera class name
  101575. * @returns StereoscopicUniversalCamera
  101576. */
  101577. StereoscopicUniversalCamera.prototype.getClassName = function () {
  101578. return "StereoscopicUniversalCamera";
  101579. };
  101580. return StereoscopicUniversalCamera;
  101581. }(BABYLON.UniversalCamera));
  101582. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  101583. })(BABYLON || (BABYLON = {}));
  101584. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  101585. var BABYLON;
  101586. (function (BABYLON) {
  101587. /**
  101588. * VRDistortionCorrectionPostProcess used for mobile VR
  101589. */
  101590. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  101591. __extends(VRDistortionCorrectionPostProcess, _super);
  101592. /**
  101593. * Initializes the VRDistortionCorrectionPostProcess
  101594. * @param name The name of the effect.
  101595. * @param camera The camera to apply the render pass to.
  101596. * @param isRightEye If this is for the right eye distortion
  101597. * @param vrMetrics All the required metrics for the VR camera
  101598. */
  101599. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  101600. var _this = _super.call(this, name, "vrDistortionCorrection", [
  101601. 'LensCenter',
  101602. 'Scale',
  101603. 'ScaleIn',
  101604. 'HmdWarpParam'
  101605. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  101606. _this._isRightEye = isRightEye;
  101607. _this._distortionFactors = vrMetrics.distortionK;
  101608. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  101609. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  101610. _this.adaptScaleToCurrentViewport = true;
  101611. _this.onSizeChangedObservable.add(function () {
  101612. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  101613. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  101614. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  101615. });
  101616. _this.onApplyObservable.add(function (effect) {
  101617. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  101618. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  101619. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  101620. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  101621. });
  101622. return _this;
  101623. }
  101624. return VRDistortionCorrectionPostProcess;
  101625. }(BABYLON.PostProcess));
  101626. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  101627. })(BABYLON || (BABYLON = {}));
  101628. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  101629. var BABYLON;
  101630. (function (BABYLON) {
  101631. /**
  101632. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  101633. * Screen rotation is taken into account.
  101634. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101635. */
  101636. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  101637. /**
  101638. * Instantiates a new input
  101639. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101640. */
  101641. function FreeCameraDeviceOrientationInput() {
  101642. var _this = this;
  101643. this._screenOrientationAngle = 0;
  101644. this._screenQuaternion = new BABYLON.Quaternion();
  101645. this._alpha = 0;
  101646. this._beta = 0;
  101647. this._gamma = 0;
  101648. this._orientationChanged = function () {
  101649. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  101650. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  101651. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  101652. };
  101653. this._deviceOrientation = function (evt) {
  101654. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  101655. _this._beta = evt.beta !== null ? evt.beta : 0;
  101656. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  101657. };
  101658. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  101659. this._orientationChanged();
  101660. }
  101661. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  101662. /**
  101663. * Define the camera controlled by the input.
  101664. */
  101665. get: function () {
  101666. return this._camera;
  101667. },
  101668. set: function (camera) {
  101669. this._camera = camera;
  101670. if (this._camera != null && !this._camera.rotationQuaternion) {
  101671. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  101672. }
  101673. },
  101674. enumerable: true,
  101675. configurable: true
  101676. });
  101677. /**
  101678. * Attach the input controls to a specific dom element to get the input from.
  101679. * @param element Defines the element the controls should be listened from
  101680. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101681. */
  101682. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  101683. window.addEventListener("orientationchange", this._orientationChanged);
  101684. window.addEventListener("deviceorientation", this._deviceOrientation);
  101685. //In certain cases, the attach control is called AFTER orientation was changed,
  101686. //So this is needed.
  101687. this._orientationChanged();
  101688. };
  101689. /**
  101690. * Detach the current controls from the specified dom element.
  101691. * @param element Defines the element to stop listening the inputs from
  101692. */
  101693. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  101694. window.removeEventListener("orientationchange", this._orientationChanged);
  101695. window.removeEventListener("deviceorientation", this._deviceOrientation);
  101696. };
  101697. /**
  101698. * Update the current camera state depending on the inputs that have been used this frame.
  101699. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101700. */
  101701. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  101702. //if no device orientation provided, don't update the rotation.
  101703. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  101704. if (!this._alpha)
  101705. return;
  101706. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  101707. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  101708. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  101709. //Mirror on XY Plane
  101710. this._camera.rotationQuaternion.z *= -1;
  101711. this._camera.rotationQuaternion.w *= -1;
  101712. };
  101713. /**
  101714. * Gets the class name of the current intput.
  101715. * @returns the class name
  101716. */
  101717. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  101718. return "FreeCameraDeviceOrientationInput";
  101719. };
  101720. /**
  101721. * Get the friendly name associated with the input class.
  101722. * @returns the input friendly name
  101723. */
  101724. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  101725. return "deviceOrientation";
  101726. };
  101727. return FreeCameraDeviceOrientationInput;
  101728. }());
  101729. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  101730. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  101731. })(BABYLON || (BABYLON = {}));
  101732. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  101733. var BABYLON;
  101734. (function (BABYLON) {
  101735. /**
  101736. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  101737. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101738. */
  101739. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  101740. /**
  101741. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  101742. */
  101743. function ArcRotateCameraVRDeviceOrientationInput() {
  101744. /**
  101745. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  101746. */
  101747. this.alphaCorrection = 1;
  101748. /**
  101749. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  101750. */
  101751. this.betaCorrection = 1;
  101752. /**
  101753. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  101754. */
  101755. this.gammaCorrection = 1;
  101756. this._alpha = 0;
  101757. this._gamma = 0;
  101758. this._dirty = false;
  101759. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  101760. }
  101761. /**
  101762. * Attach the input controls to a specific dom element to get the input from.
  101763. * @param element Defines the element the controls should be listened from
  101764. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101765. */
  101766. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  101767. this.camera.attachControl(element, noPreventDefault);
  101768. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  101769. };
  101770. /** @hidden */
  101771. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  101772. if (evt.alpha !== null) {
  101773. this._alpha = +evt.alpha | 0;
  101774. }
  101775. if (evt.gamma !== null) {
  101776. this._gamma = +evt.gamma | 0;
  101777. }
  101778. this._dirty = true;
  101779. };
  101780. /**
  101781. * Update the current camera state depending on the inputs that have been used this frame.
  101782. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101783. */
  101784. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  101785. if (this._dirty) {
  101786. this._dirty = false;
  101787. if (this._gamma < 0) {
  101788. this._gamma = 180 + this._gamma;
  101789. }
  101790. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  101791. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  101792. }
  101793. };
  101794. /**
  101795. * Detach the current controls from the specified dom element.
  101796. * @param element Defines the element to stop listening the inputs from
  101797. */
  101798. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  101799. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  101800. };
  101801. /**
  101802. * Gets the class name of the current intput.
  101803. * @returns the class name
  101804. */
  101805. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  101806. return "ArcRotateCameraVRDeviceOrientationInput";
  101807. };
  101808. /**
  101809. * Get the friendly name associated with the input class.
  101810. * @returns the input friendly name
  101811. */
  101812. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  101813. return "VRDeviceOrientation";
  101814. };
  101815. return ArcRotateCameraVRDeviceOrientationInput;
  101816. }());
  101817. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  101818. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  101819. })(BABYLON || (BABYLON = {}));
  101820. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  101821. var BABYLON;
  101822. (function (BABYLON) {
  101823. /**
  101824. * This represents all the required metrics to create a VR camera.
  101825. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  101826. */
  101827. var VRCameraMetrics = /** @class */ (function () {
  101828. function VRCameraMetrics() {
  101829. /**
  101830. * Define if the current vr camera should compensate the distortion of the lense or not.
  101831. */
  101832. this.compensateDistortion = true;
  101833. }
  101834. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  101835. /**
  101836. * Gets the rendering aspect ratio based on the provided resolutions.
  101837. */
  101838. get: function () {
  101839. return this.hResolution / (2 * this.vResolution);
  101840. },
  101841. enumerable: true,
  101842. configurable: true
  101843. });
  101844. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  101845. /**
  101846. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  101847. */
  101848. get: function () {
  101849. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  101850. },
  101851. enumerable: true,
  101852. configurable: true
  101853. });
  101854. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  101855. /**
  101856. * @hidden
  101857. */
  101858. get: function () {
  101859. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101860. var h = (4 * meters) / this.hScreenSize;
  101861. return BABYLON.Matrix.Translation(h, 0, 0);
  101862. },
  101863. enumerable: true,
  101864. configurable: true
  101865. });
  101866. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  101867. /**
  101868. * @hidden
  101869. */
  101870. get: function () {
  101871. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101872. var h = (4 * meters) / this.hScreenSize;
  101873. return BABYLON.Matrix.Translation(-h, 0, 0);
  101874. },
  101875. enumerable: true,
  101876. configurable: true
  101877. });
  101878. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  101879. /**
  101880. * @hidden
  101881. */
  101882. get: function () {
  101883. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  101884. },
  101885. enumerable: true,
  101886. configurable: true
  101887. });
  101888. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  101889. /**
  101890. * @hidden
  101891. */
  101892. get: function () {
  101893. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  101894. },
  101895. enumerable: true,
  101896. configurable: true
  101897. });
  101898. /**
  101899. * Get the default VRMetrics based on the most generic setup.
  101900. * @returns the default vr metrics
  101901. */
  101902. VRCameraMetrics.GetDefault = function () {
  101903. var result = new VRCameraMetrics();
  101904. result.hResolution = 1280;
  101905. result.vResolution = 800;
  101906. result.hScreenSize = 0.149759993;
  101907. result.vScreenSize = 0.0935999975;
  101908. result.vScreenCenter = 0.0467999987;
  101909. result.eyeToScreenDistance = 0.0410000011;
  101910. result.lensSeparationDistance = 0.0635000020;
  101911. result.interpupillaryDistance = 0.0640000030;
  101912. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  101913. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  101914. result.postProcessScaleFactor = 1.714605507808412;
  101915. result.lensCenterOffset = 0.151976421;
  101916. return result;
  101917. };
  101918. return VRCameraMetrics;
  101919. }());
  101920. BABYLON.VRCameraMetrics = VRCameraMetrics;
  101921. })(BABYLON || (BABYLON = {}));
  101922. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  101923. var BABYLON;
  101924. (function (BABYLON) {
  101925. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  101926. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101927. });
  101928. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  101929. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101930. });
  101931. /**
  101932. * This represents a WebVR camera.
  101933. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  101934. * @example http://doc.babylonjs.com/how_to/webvr_camera
  101935. */
  101936. var WebVRFreeCamera = /** @class */ (function (_super) {
  101937. __extends(WebVRFreeCamera, _super);
  101938. /**
  101939. * Instantiates a WebVRFreeCamera.
  101940. * @param name The name of the WebVRFreeCamera
  101941. * @param position The starting anchor position for the camera
  101942. * @param scene The scene the camera belongs to
  101943. * @param webVROptions a set of customizable options for the webVRCamera
  101944. */
  101945. function WebVRFreeCamera(name, position, scene, webVROptions) {
  101946. if (webVROptions === void 0) { webVROptions = {}; }
  101947. var _this = _super.call(this, name, position, scene) || this;
  101948. _this.webVROptions = webVROptions;
  101949. /**
  101950. * @hidden
  101951. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  101952. */
  101953. _this._vrDevice = null;
  101954. /**
  101955. * The rawPose of the vrDevice.
  101956. */
  101957. _this.rawPose = null;
  101958. _this._specsVersion = "1.1";
  101959. _this._attached = false;
  101960. _this._descendants = [];
  101961. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  101962. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  101963. /** @hidden */
  101964. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  101965. _this._standingMatrix = null;
  101966. /**
  101967. * Represents device position in babylon space.
  101968. */
  101969. _this.devicePosition = BABYLON.Vector3.Zero();
  101970. /**
  101971. * Represents device rotation in babylon space.
  101972. */
  101973. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  101974. /**
  101975. * The scale of the device to be used when translating from device space to babylon space.
  101976. */
  101977. _this.deviceScaleFactor = 1;
  101978. _this._deviceToWorld = BABYLON.Matrix.Identity();
  101979. _this._worldToDevice = BABYLON.Matrix.Identity();
  101980. /**
  101981. * References to the webVR controllers for the vrDevice.
  101982. */
  101983. _this.controllers = [];
  101984. /**
  101985. * Emits an event when a controller is attached.
  101986. */
  101987. _this.onControllersAttachedObservable = new BABYLON.Observable();
  101988. /**
  101989. * Emits an event when a controller's mesh has been loaded;
  101990. */
  101991. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  101992. /**
  101993. * Emits an event when the HMD's pose has been updated.
  101994. */
  101995. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  101996. _this._poseSet = false;
  101997. /**
  101998. * If the rig cameras be used as parent instead of this camera.
  101999. */
  102000. _this.rigParenting = true;
  102001. _this._defaultHeight = undefined;
  102002. _this._htmlElementAttached = null;
  102003. _this._detachIfAttached = function () {
  102004. var vrDisplay = _this.getEngine().getVRDevice();
  102005. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  102006. _this.detachControl(_this._htmlElementAttached);
  102007. }
  102008. };
  102009. _this._workingVector = BABYLON.Vector3.Zero();
  102010. _this._oneVector = BABYLON.Vector3.One();
  102011. _this._workingMatrix = BABYLON.Matrix.Identity();
  102012. _this._tmpMatrix = new BABYLON.Matrix();
  102013. _this._cache.position = BABYLON.Vector3.Zero();
  102014. if (webVROptions.defaultHeight) {
  102015. _this._defaultHeight = webVROptions.defaultHeight;
  102016. _this.position.y = _this._defaultHeight;
  102017. }
  102018. _this.minZ = 0.1;
  102019. //legacy support - the compensation boolean was removed.
  102020. if (arguments.length === 5) {
  102021. _this.webVROptions = arguments[4];
  102022. }
  102023. // default webVR options
  102024. if (_this.webVROptions.trackPosition == undefined) {
  102025. _this.webVROptions.trackPosition = true;
  102026. }
  102027. if (_this.webVROptions.controllerMeshes == undefined) {
  102028. _this.webVROptions.controllerMeshes = true;
  102029. }
  102030. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  102031. _this.webVROptions.defaultLightingOnControllers = true;
  102032. }
  102033. _this.rotationQuaternion = new BABYLON.Quaternion();
  102034. if (_this.webVROptions && _this.webVROptions.positionScale) {
  102035. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  102036. }
  102037. //enable VR
  102038. var engine = _this.getEngine();
  102039. _this._onVREnabled = function (success) { if (success) {
  102040. _this.initControllers();
  102041. } };
  102042. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  102043. engine.initWebVR().add(function (event) {
  102044. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  102045. return;
  102046. }
  102047. _this._vrDevice = event.vrDisplay;
  102048. //reset the rig parameters.
  102049. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  102050. if (_this._attached) {
  102051. _this.getEngine().enableVR();
  102052. }
  102053. });
  102054. if (typeof (VRFrameData) !== "undefined")
  102055. _this._frameData = new VRFrameData();
  102056. /**
  102057. * The idea behind the following lines:
  102058. * objects that have the camera as parent should actually have the rig cameras as a parent.
  102059. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  102060. * the second will not show it correctly.
  102061. *
  102062. * To solve this - each object that has the camera as parent will be added to a protected array.
  102063. * When the rig camera renders, it will take this array and set all of those to be its children.
  102064. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  102065. * Amazing!
  102066. */
  102067. scene.onBeforeCameraRenderObservable.add(function (camera) {
  102068. if (camera.parent === _this && _this.rigParenting) {
  102069. _this._descendants = _this.getDescendants(true, function (n) {
  102070. // don't take the cameras or the controllers!
  102071. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  102072. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  102073. return !isController && !isRigCamera;
  102074. });
  102075. _this._descendants.forEach(function (node) {
  102076. node.parent = camera;
  102077. });
  102078. }
  102079. });
  102080. scene.onAfterCameraRenderObservable.add(function (camera) {
  102081. if (camera.parent === _this && _this.rigParenting) {
  102082. _this._descendants.forEach(function (node) {
  102083. node.parent = _this;
  102084. });
  102085. }
  102086. });
  102087. return _this;
  102088. }
  102089. /**
  102090. * Gets the device distance from the ground in meters.
  102091. * @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.
  102092. */
  102093. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  102094. if (this._standingMatrix) {
  102095. // Add standing matrix offset to get real offset from ground in room
  102096. this._standingMatrix.getTranslationToRef(this._workingVector);
  102097. return this._deviceRoomPosition.y + this._workingVector.y;
  102098. }
  102099. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  102100. return this._defaultHeight || 0;
  102101. };
  102102. /**
  102103. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  102104. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  102105. */
  102106. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  102107. var _this = this;
  102108. if (callback === void 0) { callback = function (bool) { }; }
  102109. // Use standing matrix if available
  102110. this.getEngine().initWebVRAsync().then(function (result) {
  102111. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  102112. callback(false);
  102113. }
  102114. else {
  102115. _this._standingMatrix = new BABYLON.Matrix();
  102116. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  102117. if (!_this.getScene().useRightHandedSystem) {
  102118. [2, 6, 8, 9, 14].forEach(function (num) {
  102119. if (_this._standingMatrix) {
  102120. _this._standingMatrix.m[num] *= -1;
  102121. }
  102122. });
  102123. }
  102124. callback(true);
  102125. }
  102126. });
  102127. };
  102128. /**
  102129. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  102130. * @returns A promise with a boolean set to if the standing matrix is supported.
  102131. */
  102132. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  102133. var _this = this;
  102134. return new Promise(function (res, rej) {
  102135. _this.useStandingMatrix(function (supported) {
  102136. res(supported);
  102137. });
  102138. });
  102139. };
  102140. /**
  102141. * Disposes the camera
  102142. */
  102143. WebVRFreeCamera.prototype.dispose = function () {
  102144. this._detachIfAttached();
  102145. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  102146. if (this._updateCacheWhenTrackingDisabledObserver) {
  102147. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  102148. }
  102149. _super.prototype.dispose.call(this);
  102150. };
  102151. /**
  102152. * Gets a vrController by name.
  102153. * @param name The name of the controller to retreive
  102154. * @returns the controller matching the name specified or null if not found
  102155. */
  102156. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  102157. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  102158. var gp = _a[_i];
  102159. if (gp.hand === name) {
  102160. return gp;
  102161. }
  102162. }
  102163. return null;
  102164. };
  102165. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  102166. /**
  102167. * The controller corrisponding to the users left hand.
  102168. */
  102169. get: function () {
  102170. if (!this._leftController) {
  102171. this._leftController = this.getControllerByName("left");
  102172. }
  102173. return this._leftController;
  102174. },
  102175. enumerable: true,
  102176. configurable: true
  102177. });
  102178. ;
  102179. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  102180. /**
  102181. * The controller corrisponding to the users right hand.
  102182. */
  102183. get: function () {
  102184. if (!this._rightController) {
  102185. this._rightController = this.getControllerByName("right");
  102186. }
  102187. return this._rightController;
  102188. },
  102189. enumerable: true,
  102190. configurable: true
  102191. });
  102192. ;
  102193. /**
  102194. * Casts a ray forward from the vrCamera's gaze.
  102195. * @param length Length of the ray (default: 100)
  102196. * @returns the ray corrisponding to the gaze
  102197. */
  102198. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  102199. if (length === void 0) { length = 100; }
  102200. if (this.leftCamera) {
  102201. // Use left eye to avoid computation to compute center on every call
  102202. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  102203. }
  102204. else {
  102205. return _super.prototype.getForwardRay.call(this, length);
  102206. }
  102207. };
  102208. /**
  102209. * @hidden
  102210. * Updates the camera based on device's frame data
  102211. */
  102212. WebVRFreeCamera.prototype._checkInputs = function () {
  102213. if (this._vrDevice && this._vrDevice.isPresenting) {
  102214. this._vrDevice.getFrameData(this._frameData);
  102215. this.updateFromDevice(this._frameData.pose);
  102216. }
  102217. _super.prototype._checkInputs.call(this);
  102218. };
  102219. /**
  102220. * Updates the poseControlled values based on the input device pose.
  102221. * @param poseData Pose coming from the device
  102222. */
  102223. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  102224. if (poseData && poseData.orientation) {
  102225. this.rawPose = poseData;
  102226. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  102227. if (this.getScene().useRightHandedSystem) {
  102228. this._deviceRoomRotationQuaternion.z *= -1;
  102229. this._deviceRoomRotationQuaternion.w *= -1;
  102230. }
  102231. if (this.webVROptions.trackPosition && this.rawPose.position) {
  102232. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  102233. if (this.getScene().useRightHandedSystem) {
  102234. this._deviceRoomPosition.z *= -1;
  102235. }
  102236. }
  102237. this._poseSet = true;
  102238. }
  102239. };
  102240. /**
  102241. * WebVR's attach control will start broadcasting frames to the device.
  102242. * Note that in certain browsers (chrome for example) this function must be called
  102243. * within a user-interaction callback. Example:
  102244. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  102245. *
  102246. * @param element html element to attach the vrDevice to
  102247. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  102248. */
  102249. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  102250. _super.prototype.attachControl.call(this, element, noPreventDefault);
  102251. this._attached = true;
  102252. this._htmlElementAttached = element;
  102253. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  102254. if (this._vrDevice) {
  102255. this.getEngine().enableVR();
  102256. }
  102257. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  102258. };
  102259. /**
  102260. * Detaches the camera from the html element and disables VR
  102261. *
  102262. * @param element html element to detach from
  102263. */
  102264. WebVRFreeCamera.prototype.detachControl = function (element) {
  102265. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  102266. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  102267. _super.prototype.detachControl.call(this, element);
  102268. this._attached = false;
  102269. this.getEngine().disableVR();
  102270. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  102271. };
  102272. /**
  102273. * @returns the name of this class
  102274. */
  102275. WebVRFreeCamera.prototype.getClassName = function () {
  102276. return "WebVRFreeCamera";
  102277. };
  102278. /**
  102279. * Calls resetPose on the vrDisplay
  102280. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  102281. */
  102282. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  102283. //uses the vrDisplay's "resetPose()".
  102284. //pitch and roll won't be affected.
  102285. this._vrDevice.resetPose();
  102286. };
  102287. /**
  102288. * @hidden
  102289. * Updates the rig cameras (left and right eye)
  102290. */
  102291. WebVRFreeCamera.prototype._updateRigCameras = function () {
  102292. var camLeft = this._rigCameras[0];
  102293. var camRight = this._rigCameras[1];
  102294. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  102295. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  102296. camLeft.position.copyFrom(this._deviceRoomPosition);
  102297. camRight.position.copyFrom(this._deviceRoomPosition);
  102298. };
  102299. // Remove translation from 6dof headset if trackposition is set to false
  102300. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  102301. if (isViewMatrix === void 0) { isViewMatrix = false; }
  102302. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  102303. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  102304. if (!isViewMatrix) {
  102305. this._tmpMatrix.invert();
  102306. }
  102307. this._tmpMatrix.multiplyToRef(matrix, matrix);
  102308. }
  102309. };
  102310. /**
  102311. * @hidden
  102312. * Updates the cached values of the camera
  102313. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  102314. */
  102315. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  102316. var _this = this;
  102317. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  102318. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  102319. if (!this.updateCacheCalled) {
  102320. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  102321. this.updateCacheCalled = true;
  102322. this.update();
  102323. }
  102324. // Set working vector to the device position in room space rotated by the new rotation
  102325. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  102326. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  102327. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  102328. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  102329. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  102330. // Add translation from anchor position
  102331. this._deviceToWorld.getTranslationToRef(this._workingVector);
  102332. this._workingVector.addInPlace(this.position);
  102333. this._workingVector.subtractInPlace(this._cache.position);
  102334. this._deviceToWorld.setTranslation(this._workingVector);
  102335. // Set an inverted matrix to be used when updating the camera
  102336. this._deviceToWorld.invertToRef(this._worldToDevice);
  102337. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  102338. this.controllers.forEach(function (controller) {
  102339. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  102340. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  102341. controller.update();
  102342. });
  102343. }
  102344. if (!ignoreParentClass) {
  102345. _super.prototype._updateCache.call(this);
  102346. }
  102347. this.updateCacheCalled = false;
  102348. };
  102349. /**
  102350. * @hidden
  102351. * Get current device position in babylon world
  102352. */
  102353. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  102354. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  102355. };
  102356. /**
  102357. * Updates the current device position and rotation in the babylon world
  102358. */
  102359. WebVRFreeCamera.prototype.update = function () {
  102360. this._computeDevicePosition();
  102361. // Get current device rotation in babylon world
  102362. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  102363. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  102364. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  102365. if (this._poseSet) {
  102366. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  102367. }
  102368. _super.prototype.update.call(this);
  102369. };
  102370. /**
  102371. * @hidden
  102372. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  102373. * @returns an identity matrix
  102374. */
  102375. WebVRFreeCamera.prototype._getViewMatrix = function () {
  102376. return BABYLON.Matrix.Identity();
  102377. };
  102378. /**
  102379. * This function is called by the two RIG cameras.
  102380. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  102381. */
  102382. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  102383. var _this = this;
  102384. // Update the parent camera prior to using a child camera to avoid desynchronization
  102385. var parentCamera = this._cameraRigParams["parentCamera"];
  102386. parentCamera._updateCache();
  102387. //WebVR 1.1
  102388. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  102389. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  102390. if (!this.getScene().useRightHandedSystem) {
  102391. [2, 6, 8, 9, 14].forEach(function (num) {
  102392. _this._webvrViewMatrix.m[num] *= -1;
  102393. });
  102394. }
  102395. // update the camera rotation matrix
  102396. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  102397. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  102398. // Computing target and final matrix
  102399. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  102400. // should the view matrix be updated with scale and position offset?
  102401. if (parentCamera.deviceScaleFactor !== 1) {
  102402. this._webvrViewMatrix.invert();
  102403. // scale the position, if set
  102404. if (parentCamera.deviceScaleFactor) {
  102405. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  102406. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  102407. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  102408. }
  102409. this._webvrViewMatrix.invert();
  102410. }
  102411. // Remove translation from 6dof headset if trackposition is set to false
  102412. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  102413. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  102414. // Compute global position
  102415. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  102416. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  102417. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  102418. this._workingMatrix.getTranslationToRef(this._globalPosition);
  102419. this._markSyncedWithParent();
  102420. return this._webvrViewMatrix;
  102421. };
  102422. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  102423. var _this = this;
  102424. var parentCamera = this.parent;
  102425. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  102426. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  102427. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  102428. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  102429. //babylon compatible matrix
  102430. if (!this.getScene().useRightHandedSystem) {
  102431. [8, 9, 10, 11].forEach(function (num) {
  102432. _this._projectionMatrix.m[num] *= -1;
  102433. });
  102434. }
  102435. return this._projectionMatrix;
  102436. };
  102437. /**
  102438. * Initializes the controllers and their meshes
  102439. */
  102440. WebVRFreeCamera.prototype.initControllers = function () {
  102441. var _this = this;
  102442. this.controllers = [];
  102443. var manager = this.getScene().gamepadManager;
  102444. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  102445. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  102446. var webVrController = gamepad;
  102447. if (webVrController.defaultModel) {
  102448. webVrController.defaultModel.setEnabled(false);
  102449. }
  102450. if (webVrController.hand === "right") {
  102451. _this._rightController = null;
  102452. }
  102453. if (webVrController.hand === "left") {
  102454. _this._leftController = null;
  102455. }
  102456. var controllerIndex = _this.controllers.indexOf(webVrController);
  102457. if (controllerIndex !== -1) {
  102458. _this.controllers.splice(controllerIndex, 1);
  102459. }
  102460. }
  102461. });
  102462. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  102463. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  102464. var webVrController_1 = gamepad;
  102465. if (!_this.webVROptions.trackPosition) {
  102466. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  102467. // Cache must be updated before rendering controllers to avoid them being one frame behind
  102468. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  102469. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  102470. _this._updateCache();
  102471. });
  102472. }
  102473. }
  102474. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  102475. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  102476. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  102477. if (_this.webVROptions.controllerMeshes) {
  102478. if (webVrController_1.defaultModel) {
  102479. webVrController_1.defaultModel.setEnabled(true);
  102480. }
  102481. else {
  102482. // Load the meshes
  102483. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  102484. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  102485. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  102486. if (_this.webVROptions.defaultLightingOnControllers) {
  102487. if (!_this._lightOnControllers) {
  102488. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  102489. }
  102490. var activateLightOnSubMeshes_1 = function (mesh, light) {
  102491. var children = mesh.getChildren();
  102492. if (children && children.length !== 0) {
  102493. children.forEach(function (mesh) {
  102494. light.includedOnlyMeshes.push(mesh);
  102495. activateLightOnSubMeshes_1(mesh, light);
  102496. });
  102497. }
  102498. };
  102499. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  102500. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  102501. }
  102502. });
  102503. }
  102504. }
  102505. webVrController_1.attachToPoseControlledCamera(_this);
  102506. // since this is async - sanity check. Is the controller already stored?
  102507. if (_this.controllers.indexOf(webVrController_1) === -1) {
  102508. //add to the controllers array
  102509. _this.controllers.push(webVrController_1);
  102510. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  102511. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  102512. // So we're overriding setting left & right manually to be sure
  102513. var firstViveWandDetected = false;
  102514. for (var i = 0; i < _this.controllers.length; i++) {
  102515. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  102516. if (!firstViveWandDetected) {
  102517. firstViveWandDetected = true;
  102518. _this.controllers[i].hand = "left";
  102519. }
  102520. else {
  102521. _this.controllers[i].hand = "right";
  102522. }
  102523. }
  102524. }
  102525. //did we find enough controllers? Great! let the developer know.
  102526. if (_this.controllers.length >= 2) {
  102527. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  102528. }
  102529. }
  102530. }
  102531. });
  102532. };
  102533. return WebVRFreeCamera;
  102534. }(BABYLON.FreeCamera));
  102535. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  102536. })(BABYLON || (BABYLON = {}));
  102537. //# sourceMappingURL=babylon.webVRCamera.js.map
  102538. var BABYLON;
  102539. (function (BABYLON) {
  102540. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  102541. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  102542. });
  102543. // We're mainly based on the logic defined into the FreeCamera code
  102544. /**
  102545. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  102546. * being tilted forward or back and left or right.
  102547. */
  102548. var DeviceOrientationCamera = /** @class */ (function (_super) {
  102549. __extends(DeviceOrientationCamera, _super);
  102550. /**
  102551. * Creates a new device orientation camera
  102552. * @param name The name of the camera
  102553. * @param position The start position camera
  102554. * @param scene The scene the camera belongs to
  102555. */
  102556. function DeviceOrientationCamera(name, position, scene) {
  102557. var _this = _super.call(this, name, position, scene) || this;
  102558. _this._quaternionCache = new BABYLON.Quaternion();
  102559. _this.inputs.addDeviceOrientation();
  102560. return _this;
  102561. }
  102562. /**
  102563. * Gets the current instance class name ("DeviceOrientationCamera").
  102564. * This helps avoiding instanceof at run time.
  102565. * @returns the class name
  102566. */
  102567. DeviceOrientationCamera.prototype.getClassName = function () {
  102568. return "DeviceOrientationCamera";
  102569. };
  102570. /**
  102571. * @hidden
  102572. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  102573. */
  102574. DeviceOrientationCamera.prototype._checkInputs = function () {
  102575. _super.prototype._checkInputs.call(this);
  102576. this._quaternionCache.copyFrom(this.rotationQuaternion);
  102577. if (this._initialQuaternion) {
  102578. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  102579. }
  102580. };
  102581. /**
  102582. * Reset the camera to its default orientation on the specified axis only.
  102583. * @param axis The axis to reset
  102584. */
  102585. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  102586. var _this = this;
  102587. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  102588. //can only work if this camera has a rotation quaternion already.
  102589. if (!this.rotationQuaternion)
  102590. return;
  102591. if (!this._initialQuaternion) {
  102592. this._initialQuaternion = new BABYLON.Quaternion();
  102593. }
  102594. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  102595. ['x', 'y', 'z'].forEach(function (axisName) {
  102596. if (!axis[axisName]) {
  102597. _this._initialQuaternion[axisName] = 0;
  102598. }
  102599. else {
  102600. _this._initialQuaternion[axisName] *= -1;
  102601. }
  102602. });
  102603. this._initialQuaternion.normalize();
  102604. //force rotation update
  102605. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  102606. };
  102607. return DeviceOrientationCamera;
  102608. }(BABYLON.FreeCamera));
  102609. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  102610. })(BABYLON || (BABYLON = {}));
  102611. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  102612. var BABYLON;
  102613. (function (BABYLON) {
  102614. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  102615. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  102616. });
  102617. /**
  102618. * Camera used to simulate VR rendering (based on FreeCamera)
  102619. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102620. */
  102621. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  102622. __extends(VRDeviceOrientationFreeCamera, _super);
  102623. /**
  102624. * Creates a new VRDeviceOrientationFreeCamera
  102625. * @param name defines camera name
  102626. * @param position defines the start position of the camera
  102627. * @param scene defines the scene the camera belongs to
  102628. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102629. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102630. */
  102631. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  102632. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102633. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102634. var _this = _super.call(this, name, position, scene) || this;
  102635. vrCameraMetrics.compensateDistortion = compensateDistortion;
  102636. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  102637. return _this;
  102638. }
  102639. /**
  102640. * Gets camera class name
  102641. * @returns VRDeviceOrientationFreeCamera
  102642. */
  102643. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  102644. return "VRDeviceOrientationFreeCamera";
  102645. };
  102646. return VRDeviceOrientationFreeCamera;
  102647. }(BABYLON.DeviceOrientationCamera));
  102648. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  102649. })(BABYLON || (BABYLON = {}));
  102650. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  102651. var BABYLON;
  102652. (function (BABYLON) {
  102653. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  102654. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  102655. });
  102656. /**
  102657. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  102658. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102659. */
  102660. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  102661. __extends(VRDeviceOrientationArcRotateCamera, _super);
  102662. /**
  102663. * Creates a new VRDeviceOrientationArcRotateCamera
  102664. * @param name defines camera name
  102665. * @param alpha defines the camera rotation along the logitudinal axis
  102666. * @param beta defines the camera rotation along the latitudinal axis
  102667. * @param radius defines the camera distance from its target
  102668. * @param target defines the camera target
  102669. * @param scene defines the scene the camera belongs to
  102670. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102671. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102672. */
  102673. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  102674. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102675. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102676. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102677. vrCameraMetrics.compensateDistortion = compensateDistortion;
  102678. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  102679. _this.inputs.addVRDeviceOrientation();
  102680. return _this;
  102681. }
  102682. /**
  102683. * Gets camera class name
  102684. * @returns VRDeviceOrientationArcRotateCamera
  102685. */
  102686. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  102687. return "VRDeviceOrientationArcRotateCamera";
  102688. };
  102689. return VRDeviceOrientationArcRotateCamera;
  102690. }(BABYLON.ArcRotateCamera));
  102691. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  102692. })(BABYLON || (BABYLON = {}));
  102693. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  102694. var BABYLON;
  102695. (function (BABYLON) {
  102696. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  102697. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  102698. });
  102699. /**
  102700. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  102701. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102702. */
  102703. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  102704. __extends(VRDeviceOrientationGamepadCamera, _super);
  102705. /**
  102706. * Creates a new VRDeviceOrientationGamepadCamera
  102707. * @param name defines camera name
  102708. * @param position defines the start position of the camera
  102709. * @param scene defines the scene the camera belongs to
  102710. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102711. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102712. */
  102713. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  102714. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102715. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102716. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  102717. _this.inputs.addGamepad();
  102718. return _this;
  102719. }
  102720. /**
  102721. * Gets camera class name
  102722. * @returns VRDeviceOrientationGamepadCamera
  102723. */
  102724. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  102725. return "VRDeviceOrientationGamepadCamera";
  102726. };
  102727. return VRDeviceOrientationGamepadCamera;
  102728. }(BABYLON.VRDeviceOrientationFreeCamera));
  102729. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  102730. })(BABYLON || (BABYLON = {}));
  102731. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  102732. var BABYLON;
  102733. (function (BABYLON) {
  102734. var VRExperienceHelperGazer = /** @class */ (function () {
  102735. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  102736. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  102737. this.scene = scene;
  102738. /** @hidden */
  102739. this._pointerDownOnMeshAsked = false;
  102740. /** @hidden */
  102741. this._isActionableMesh = false;
  102742. /** @hidden */
  102743. this._teleportationRequestInitiated = false;
  102744. /** @hidden */
  102745. this._teleportationBackRequestInitiated = false;
  102746. /** @hidden */
  102747. this._rotationRightAsked = false;
  102748. /** @hidden */
  102749. this._rotationLeftAsked = false;
  102750. /** @hidden */
  102751. this._dpadPressed = true;
  102752. /** @hidden */
  102753. this._activePointer = false;
  102754. this._id = VRExperienceHelperGazer._idCounter++;
  102755. // Gaze tracker
  102756. if (!gazeTrackerToClone) {
  102757. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  102758. this._gazeTracker.bakeCurrentTransformIntoVertices();
  102759. this._gazeTracker.isPickable = false;
  102760. this._gazeTracker.isVisible = false;
  102761. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  102762. targetMat.specularColor = BABYLON.Color3.Black();
  102763. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  102764. targetMat.backFaceCulling = false;
  102765. this._gazeTracker.material = targetMat;
  102766. }
  102767. else {
  102768. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  102769. }
  102770. }
  102771. /** @hidden */
  102772. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  102773. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  102774. };
  102775. /** @hidden */
  102776. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  102777. this._pointerDownOnMeshAsked = true;
  102778. if (this._currentHit) {
  102779. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  102780. }
  102781. };
  102782. /** @hidden */
  102783. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  102784. if (this._currentHit) {
  102785. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  102786. }
  102787. this._pointerDownOnMeshAsked = false;
  102788. };
  102789. /** @hidden */
  102790. VRExperienceHelperGazer.prototype._activatePointer = function () {
  102791. this._activePointer = true;
  102792. };
  102793. /** @hidden */
  102794. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  102795. this._activePointer = false;
  102796. };
  102797. /** @hidden */
  102798. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  102799. if (distance === void 0) { distance = 100; }
  102800. };
  102801. VRExperienceHelperGazer.prototype.dispose = function () {
  102802. this._interactionsEnabled = false;
  102803. this._teleportationEnabled = false;
  102804. if (this._gazeTracker) {
  102805. this._gazeTracker.dispose();
  102806. }
  102807. };
  102808. VRExperienceHelperGazer._idCounter = 0;
  102809. return VRExperienceHelperGazer;
  102810. }());
  102811. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  102812. __extends(VRExperienceHelperControllerGazer, _super);
  102813. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  102814. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  102815. _this.webVRController = webVRController;
  102816. // Laser pointer
  102817. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  102818. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  102819. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  102820. laserPointerMaterial.alpha = 0.6;
  102821. _this._laserPointer.material = laserPointerMaterial;
  102822. _this._laserPointer.rotation.x = Math.PI / 2;
  102823. _this._laserPointer.position.z = -0.5;
  102824. _this._laserPointer.isVisible = false;
  102825. _this._laserPointer.isPickable = false;
  102826. if (!webVRController.mesh) {
  102827. // Create an empty mesh that is used prior to loading the high quality model
  102828. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  102829. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  102830. preloadPointerPose.rotation.x = -0.7;
  102831. preloadMesh.addChild(preloadPointerPose);
  102832. webVRController.attachToMesh(preloadMesh);
  102833. }
  102834. _this._setLaserPointerParent(webVRController.mesh);
  102835. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  102836. _this._setLaserPointerParent(mesh);
  102837. });
  102838. return _this;
  102839. }
  102840. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  102841. return this.webVRController.getForwardRay(length);
  102842. };
  102843. /** @hidden */
  102844. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  102845. _super.prototype._activatePointer.call(this);
  102846. this._laserPointer.isVisible = true;
  102847. };
  102848. /** @hidden */
  102849. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  102850. _super.prototype._deactivatePointer.call(this);
  102851. this._laserPointer.isVisible = false;
  102852. };
  102853. /** @hidden */
  102854. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  102855. this._laserPointer.material.emissiveColor = color;
  102856. };
  102857. /** @hidden */
  102858. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  102859. var makeNotPick = function (root) {
  102860. root.isPickable = false;
  102861. root.getChildMeshes().forEach(function (c) {
  102862. makeNotPick(c);
  102863. });
  102864. };
  102865. makeNotPick(mesh);
  102866. var childMeshes = mesh.getChildMeshes();
  102867. this.webVRController._pointingPoseNode = null;
  102868. for (var i = 0; i < childMeshes.length; i++) {
  102869. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  102870. mesh = childMeshes[i];
  102871. this.webVRController._pointingPoseNode = mesh;
  102872. break;
  102873. }
  102874. }
  102875. this._laserPointer.parent = mesh;
  102876. };
  102877. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  102878. if (distance === void 0) { distance = 100; }
  102879. this._laserPointer.scaling.y = distance;
  102880. this._laserPointer.position.z = -distance / 2;
  102881. };
  102882. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  102883. _super.prototype.dispose.call(this);
  102884. this._laserPointer.dispose();
  102885. if (this._meshAttachedObserver) {
  102886. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  102887. }
  102888. };
  102889. return VRExperienceHelperControllerGazer;
  102890. }(VRExperienceHelperGazer));
  102891. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  102892. __extends(VRExperienceHelperCameraGazer, _super);
  102893. function VRExperienceHelperCameraGazer(getCamera, scene) {
  102894. var _this = _super.call(this, scene) || this;
  102895. _this.getCamera = getCamera;
  102896. return _this;
  102897. }
  102898. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  102899. var camera = this.getCamera();
  102900. if (camera) {
  102901. return camera.getForwardRay(length);
  102902. }
  102903. else {
  102904. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  102905. }
  102906. };
  102907. return VRExperienceHelperCameraGazer;
  102908. }(VRExperienceHelperGazer));
  102909. /**
  102910. * Helps to quickly add VR support to an existing scene.
  102911. * See http://doc.babylonjs.com/how_to/webvr_helper
  102912. */
  102913. var VRExperienceHelper = /** @class */ (function () {
  102914. /**
  102915. * Instantiates a VRExperienceHelper.
  102916. * Helps to quickly add VR support to an existing scene.
  102917. * @param scene The scene the VRExperienceHelper belongs to.
  102918. * @param webVROptions Options to modify the vr experience helper's behavior.
  102919. */
  102920. function VRExperienceHelper(scene,
  102921. /** Options to modify the vr experience helper's behavior. */
  102922. webVROptions) {
  102923. if (webVROptions === void 0) { webVROptions = {}; }
  102924. var _this = this;
  102925. this.webVROptions = webVROptions;
  102926. // Can the system support WebVR, even if a headset isn't plugged in?
  102927. this._webVRsupported = false;
  102928. // If WebVR is supported, is a headset plugged in and are we ready to present?
  102929. this._webVRready = false;
  102930. // Are we waiting for the requestPresent callback to complete?
  102931. this._webVRrequesting = false;
  102932. // Are we presenting to the headset right now? (this is the vrDevice state)
  102933. this._webVRpresenting = false;
  102934. // Are we presenting in the fullscreen fallback?
  102935. this._fullscreenVRpresenting = false;
  102936. /**
  102937. * Observable raised when entering VR.
  102938. */
  102939. this.onEnteringVRObservable = new BABYLON.Observable();
  102940. /**
  102941. * Observable raised when exiting VR.
  102942. */
  102943. this.onExitingVRObservable = new BABYLON.Observable();
  102944. /**
  102945. * Observable raised when controller mesh is loaded.
  102946. */
  102947. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  102948. this._useCustomVRButton = false;
  102949. this._teleportationRequested = false;
  102950. this._teleportActive = false;
  102951. this._floorMeshesCollection = [];
  102952. this._rotationAllowed = true;
  102953. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  102954. this._isDefaultTeleportationTarget = true;
  102955. this._teleportationFillColor = "#444444";
  102956. this._teleportationBorderColor = "#FFFFFF";
  102957. this._rotationAngle = 0;
  102958. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  102959. this._padSensibilityUp = 0.65;
  102960. this._padSensibilityDown = 0.35;
  102961. this._leftController = null;
  102962. this._rightController = null;
  102963. /**
  102964. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  102965. */
  102966. this.onNewMeshSelected = new BABYLON.Observable();
  102967. /**
  102968. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  102969. */
  102970. this.onNewMeshPicked = new BABYLON.Observable();
  102971. /**
  102972. * Observable raised before camera teleportation
  102973. */
  102974. this.onBeforeCameraTeleport = new BABYLON.Observable();
  102975. /**
  102976. * Observable raised after camera teleportation
  102977. */
  102978. this.onAfterCameraTeleport = new BABYLON.Observable();
  102979. /**
  102980. * Observable raised when current selected mesh gets unselected
  102981. */
  102982. this.onSelectedMeshUnselected = new BABYLON.Observable();
  102983. /**
  102984. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  102985. */
  102986. this.teleportationEnabled = true;
  102987. this._teleportationInitialized = false;
  102988. this._interactionsEnabled = false;
  102989. this._interactionsRequested = false;
  102990. this._displayGaze = true;
  102991. this._displayLaserPointer = true;
  102992. /**
  102993. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  102994. */
  102995. this.updateGazeTrackerScale = true;
  102996. this._onResize = function () {
  102997. _this.moveButtonToBottomRight();
  102998. if (_this._fullscreenVRpresenting && _this._webVRready) {
  102999. _this.exitVR();
  103000. }
  103001. };
  103002. this._onFullscreenChange = function () {
  103003. if (document.fullscreen !== undefined) {
  103004. _this._fullscreenVRpresenting = document.fullscreen;
  103005. }
  103006. else if (document.mozFullScreen !== undefined) {
  103007. _this._fullscreenVRpresenting = document.mozFullScreen;
  103008. }
  103009. else if (document.webkitIsFullScreen !== undefined) {
  103010. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  103011. }
  103012. else if (document.msIsFullScreen !== undefined) {
  103013. _this._fullscreenVRpresenting = document.msIsFullScreen;
  103014. }
  103015. else if (document.msFullscreenElement !== undefined) {
  103016. _this._fullscreenVRpresenting = document.msFullscreenElement;
  103017. }
  103018. if (!_this._fullscreenVRpresenting && _this._canvas) {
  103019. _this.exitVR();
  103020. if (!_this._useCustomVRButton) {
  103021. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  103022. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  103023. }
  103024. }
  103025. };
  103026. this.beforeRender = function () {
  103027. if (_this._leftController && _this._leftController._activePointer) {
  103028. _this._castRayAndSelectObject(_this._leftController);
  103029. }
  103030. if (_this._rightController && _this._rightController._activePointer) {
  103031. _this._castRayAndSelectObject(_this._rightController);
  103032. }
  103033. if (_this._noControllerIsActive) {
  103034. _this._castRayAndSelectObject(_this._cameraGazer);
  103035. }
  103036. else {
  103037. _this._cameraGazer._gazeTracker.isVisible = false;
  103038. }
  103039. };
  103040. this._onNewGamepadConnected = function (gamepad) {
  103041. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  103042. if (gamepad.leftStick) {
  103043. gamepad.onleftstickchanged(function (stickValues) {
  103044. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  103045. // Listening to classic/xbox gamepad only if no VR controller is active
  103046. if ((!_this._leftController && !_this._rightController) ||
  103047. ((_this._leftController && !_this._leftController._activePointer) &&
  103048. (_this._rightController && !_this._rightController._activePointer))) {
  103049. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  103050. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  103051. }
  103052. }
  103053. });
  103054. }
  103055. if (gamepad.rightStick) {
  103056. gamepad.onrightstickchanged(function (stickValues) {
  103057. if (_this._teleportationInitialized) {
  103058. _this._checkRotate(stickValues, _this._cameraGazer);
  103059. }
  103060. });
  103061. }
  103062. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  103063. gamepad.onbuttondown(function (buttonPressed) {
  103064. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  103065. _this._cameraGazer._selectionPointerDown();
  103066. }
  103067. });
  103068. gamepad.onbuttonup(function (buttonPressed) {
  103069. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  103070. _this._cameraGazer._selectionPointerUp();
  103071. }
  103072. });
  103073. }
  103074. }
  103075. else {
  103076. var webVRController = gamepad;
  103077. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  103078. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  103079. _this._rightController = controller;
  103080. }
  103081. else {
  103082. _this._leftController = controller;
  103083. }
  103084. _this._tryEnableInteractionOnController(controller);
  103085. }
  103086. };
  103087. // 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
  103088. this._tryEnableInteractionOnController = function (controller) {
  103089. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  103090. _this._enableInteractionOnController(controller);
  103091. }
  103092. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  103093. _this._enableTeleportationOnController(controller);
  103094. }
  103095. };
  103096. this._onNewGamepadDisconnected = function (gamepad) {
  103097. if (gamepad instanceof BABYLON.WebVRController) {
  103098. if (gamepad.hand === "left" && _this._leftController != null) {
  103099. _this._leftController.dispose();
  103100. _this._leftController = null;
  103101. }
  103102. if (gamepad.hand === "right" && _this._rightController != null) {
  103103. _this._rightController.dispose();
  103104. _this._rightController = null;
  103105. }
  103106. }
  103107. };
  103108. this._workingVector = BABYLON.Vector3.Zero();
  103109. this._workingQuaternion = BABYLON.Quaternion.Identity();
  103110. this._workingMatrix = BABYLON.Matrix.Identity();
  103111. this._scene = scene;
  103112. this._canvas = scene.getEngine().getRenderingCanvas();
  103113. // Parse options
  103114. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  103115. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  103116. }
  103117. if (webVROptions.createDeviceOrientationCamera === undefined) {
  103118. webVROptions.createDeviceOrientationCamera = true;
  103119. }
  103120. if (webVROptions.laserToggle === undefined) {
  103121. webVROptions.laserToggle = true;
  103122. }
  103123. if (webVROptions.defaultHeight === undefined) {
  103124. webVROptions.defaultHeight = 1.7;
  103125. }
  103126. if (webVROptions.useCustomVRButton) {
  103127. this._useCustomVRButton = true;
  103128. if (webVROptions.customVRButton) {
  103129. this._btnVR = webVROptions.customVRButton;
  103130. }
  103131. }
  103132. if (webVROptions.rayLength) {
  103133. this._rayLength = webVROptions.rayLength;
  103134. }
  103135. this._defaultHeight = webVROptions.defaultHeight;
  103136. if (webVROptions.positionScale) {
  103137. this._rayLength *= webVROptions.positionScale;
  103138. this._defaultHeight *= webVROptions.positionScale;
  103139. }
  103140. this._hasEnteredVR = false;
  103141. // Set position
  103142. if (this._scene.activeCamera) {
  103143. this._position = this._scene.activeCamera.position.clone();
  103144. }
  103145. else {
  103146. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  103147. }
  103148. // Set non-vr camera
  103149. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  103150. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  103151. // Copy data from existing camera
  103152. if (this._scene.activeCamera) {
  103153. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  103154. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  103155. // Set rotation from previous camera
  103156. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  103157. var targetCamera = this._scene.activeCamera;
  103158. if (targetCamera.rotationQuaternion) {
  103159. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  103160. }
  103161. else {
  103162. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  103163. }
  103164. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  103165. }
  103166. }
  103167. this._scene.activeCamera = this._deviceOrientationCamera;
  103168. if (this._canvas) {
  103169. this._scene.activeCamera.attachControl(this._canvas);
  103170. }
  103171. }
  103172. else {
  103173. this._existingCamera = this._scene.activeCamera;
  103174. }
  103175. // Create VR cameras
  103176. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  103177. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  103178. }
  103179. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  103180. this._webVRCamera.useStandingMatrix();
  103181. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  103182. // Create default button
  103183. if (!this._useCustomVRButton) {
  103184. this._btnVR = document.createElement("BUTTON");
  103185. this._btnVR.className = "babylonVRicon";
  103186. this._btnVR.id = "babylonVRiconbtn";
  103187. this._btnVR.title = "Click to switch to VR";
  103188. 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) }";
  103189. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  103190. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  103191. // css += ".babylonVRicon.vrdisplaysupported { }";
  103192. // css += ".babylonVRicon.vrdisplayready { }";
  103193. // css += ".babylonVRicon.vrdisplayrequesting { }";
  103194. var style = document.createElement('style');
  103195. style.appendChild(document.createTextNode(css));
  103196. document.getElementsByTagName('head')[0].appendChild(style);
  103197. this.moveButtonToBottomRight();
  103198. }
  103199. // VR button click event
  103200. if (this._btnVR) {
  103201. this._btnVR.addEventListener("click", function () {
  103202. if (!_this.isInVRMode) {
  103203. _this.enterVR();
  103204. }
  103205. else {
  103206. _this.exitVR();
  103207. }
  103208. });
  103209. }
  103210. // Window events
  103211. window.addEventListener("resize", this._onResize);
  103212. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  103213. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  103214. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  103215. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  103216. document.onmsfullscreenchange = this._onFullscreenChange;
  103217. // Display vr button when headset is connected
  103218. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  103219. this.displayVRButton();
  103220. }
  103221. else {
  103222. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  103223. if (e.vrDisplay) {
  103224. _this.displayVRButton();
  103225. }
  103226. });
  103227. }
  103228. // Exiting VR mode using 'ESC' key on desktop
  103229. this._onKeyDown = function (event) {
  103230. if (event.keyCode === 27 && _this.isInVRMode) {
  103231. _this.exitVR();
  103232. }
  103233. };
  103234. document.addEventListener("keydown", this._onKeyDown);
  103235. // Exiting VR mode double tapping the touch screen
  103236. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  103237. if (_this.isInVRMode) {
  103238. _this.exitVR();
  103239. if (_this._fullscreenVRpresenting) {
  103240. _this._scene.getEngine().switchFullscreen(true);
  103241. }
  103242. }
  103243. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  103244. // Listen for WebVR display changes
  103245. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  103246. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  103247. this._onVRRequestPresentStart = function () {
  103248. _this._webVRrequesting = true;
  103249. _this.updateButtonVisibility();
  103250. };
  103251. this._onVRRequestPresentComplete = function (success) {
  103252. _this._webVRrequesting = false;
  103253. _this.updateButtonVisibility();
  103254. };
  103255. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  103256. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  103257. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  103258. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  103259. scene.onDisposeObservable.add(function () {
  103260. _this.dispose();
  103261. });
  103262. // Gamepad connection events
  103263. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  103264. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  103265. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  103266. this.updateButtonVisibility();
  103267. //create easing functions
  103268. this._circleEase = new BABYLON.CircleEase();
  103269. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  103270. if (this.webVROptions.floorMeshes) {
  103271. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  103272. }
  103273. }
  103274. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  103275. /** Return this.onEnteringVRObservable
  103276. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  103277. */
  103278. get: function () {
  103279. return this.onEnteringVRObservable;
  103280. },
  103281. enumerable: true,
  103282. configurable: true
  103283. });
  103284. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  103285. /** Return this.onExitingVRObservable
  103286. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  103287. */
  103288. get: function () {
  103289. return this.onExitingVRObservable;
  103290. },
  103291. enumerable: true,
  103292. configurable: true
  103293. });
  103294. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  103295. /** Return this.onControllerMeshLoadedObservable
  103296. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  103297. */
  103298. get: function () {
  103299. return this.onControllerMeshLoadedObservable;
  103300. },
  103301. enumerable: true,
  103302. configurable: true
  103303. });
  103304. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  103305. /**
  103306. * The mesh used to display where the user is going to teleport.
  103307. */
  103308. get: function () {
  103309. return this._teleportationTarget;
  103310. },
  103311. /**
  103312. * Sets the mesh to be used to display where the user is going to teleport.
  103313. */
  103314. set: function (value) {
  103315. if (value) {
  103316. value.name = "teleportationTarget";
  103317. this._isDefaultTeleportationTarget = false;
  103318. this._teleportationTarget = value;
  103319. }
  103320. },
  103321. enumerable: true,
  103322. configurable: true
  103323. });
  103324. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  103325. /**
  103326. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  103327. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  103328. * See http://doc.babylonjs.com/resources/baking_transformations
  103329. */
  103330. get: function () {
  103331. return this._cameraGazer._gazeTracker;
  103332. },
  103333. set: function (value) {
  103334. if (value) {
  103335. // Dispose of existing meshes
  103336. if (this._cameraGazer._gazeTracker) {
  103337. this._cameraGazer._gazeTracker.dispose();
  103338. }
  103339. if (this._leftController && this._leftController._gazeTracker) {
  103340. this._leftController._gazeTracker.dispose();
  103341. }
  103342. if (this._rightController && this._rightController._gazeTracker) {
  103343. this._rightController._gazeTracker.dispose();
  103344. }
  103345. // Set and create gaze trackers on head and controllers
  103346. this._cameraGazer._gazeTracker = value;
  103347. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  103348. this._cameraGazer._gazeTracker.isPickable = false;
  103349. this._cameraGazer._gazeTracker.isVisible = false;
  103350. this._cameraGazer._gazeTracker.name = "gazeTracker";
  103351. if (this._leftController) {
  103352. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  103353. }
  103354. if (this._rightController) {
  103355. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  103356. }
  103357. }
  103358. },
  103359. enumerable: true,
  103360. configurable: true
  103361. });
  103362. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  103363. /**
  103364. * The gaze tracking mesh corresponding to the left controller
  103365. */
  103366. get: function () {
  103367. if (this._leftController) {
  103368. return this._leftController._gazeTracker;
  103369. }
  103370. return null;
  103371. },
  103372. enumerable: true,
  103373. configurable: true
  103374. });
  103375. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  103376. /**
  103377. * The gaze tracking mesh corresponding to the right controller
  103378. */
  103379. get: function () {
  103380. if (this._rightController) {
  103381. return this._rightController._gazeTracker;
  103382. }
  103383. return null;
  103384. },
  103385. enumerable: true,
  103386. configurable: true
  103387. });
  103388. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  103389. /**
  103390. * If the ray of the gaze should be displayed.
  103391. */
  103392. get: function () {
  103393. return this._displayGaze;
  103394. },
  103395. /**
  103396. * Sets if the ray of the gaze should be displayed.
  103397. */
  103398. set: function (value) {
  103399. this._displayGaze = value;
  103400. if (!value) {
  103401. this._cameraGazer._gazeTracker.isVisible = false;
  103402. if (this._leftController) {
  103403. this._leftController._gazeTracker.isVisible = false;
  103404. }
  103405. if (this._rightController) {
  103406. this._rightController._gazeTracker.isVisible = false;
  103407. }
  103408. }
  103409. },
  103410. enumerable: true,
  103411. configurable: true
  103412. });
  103413. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  103414. /**
  103415. * If the ray of the LaserPointer should be displayed.
  103416. */
  103417. get: function () {
  103418. return this._displayLaserPointer;
  103419. },
  103420. /**
  103421. * Sets if the ray of the LaserPointer should be displayed.
  103422. */
  103423. set: function (value) {
  103424. this._displayLaserPointer = value;
  103425. if (!value) {
  103426. if (this._rightController) {
  103427. this._rightController._deactivatePointer();
  103428. this._rightController._gazeTracker.isVisible = false;
  103429. }
  103430. if (this._leftController) {
  103431. this._leftController._deactivatePointer();
  103432. this._leftController._gazeTracker.isVisible = false;
  103433. }
  103434. }
  103435. else {
  103436. if (this._rightController) {
  103437. this._rightController._activatePointer();
  103438. }
  103439. if (this._leftController) {
  103440. this._leftController._activatePointer();
  103441. }
  103442. }
  103443. },
  103444. enumerable: true,
  103445. configurable: true
  103446. });
  103447. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  103448. /**
  103449. * The deviceOrientationCamera used as the camera when not in VR.
  103450. */
  103451. get: function () {
  103452. return this._deviceOrientationCamera;
  103453. },
  103454. enumerable: true,
  103455. configurable: true
  103456. });
  103457. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  103458. /**
  103459. * Based on the current WebVR support, returns the current VR camera used.
  103460. */
  103461. get: function () {
  103462. if (this._webVRready) {
  103463. return this._webVRCamera;
  103464. }
  103465. else {
  103466. return this._scene.activeCamera;
  103467. }
  103468. },
  103469. enumerable: true,
  103470. configurable: true
  103471. });
  103472. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  103473. /**
  103474. * The webVRCamera which is used when in VR.
  103475. */
  103476. get: function () {
  103477. return this._webVRCamera;
  103478. },
  103479. enumerable: true,
  103480. configurable: true
  103481. });
  103482. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  103483. /**
  103484. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  103485. */
  103486. get: function () {
  103487. return this._vrDeviceOrientationCamera;
  103488. },
  103489. enumerable: true,
  103490. configurable: true
  103491. });
  103492. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  103493. get: function () {
  103494. var result = this._cameraGazer._teleportationRequestInitiated
  103495. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  103496. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  103497. return result;
  103498. },
  103499. enumerable: true,
  103500. configurable: true
  103501. });
  103502. // Raised when one of the controller has loaded successfully its associated default mesh
  103503. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  103504. if (this._leftController && this._leftController.webVRController == webVRController) {
  103505. if (webVRController.mesh) {
  103506. this._leftController._setLaserPointerParent(webVRController.mesh);
  103507. }
  103508. }
  103509. if (this._rightController && this._rightController.webVRController == webVRController) {
  103510. if (webVRController.mesh) {
  103511. this._rightController._setLaserPointerParent(webVRController.mesh);
  103512. }
  103513. }
  103514. try {
  103515. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  103516. }
  103517. catch (err) {
  103518. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  103519. }
  103520. };
  103521. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  103522. /**
  103523. * Gets a value indicating if we are currently in VR mode.
  103524. */
  103525. get: function () {
  103526. return this._webVRpresenting || this._fullscreenVRpresenting;
  103527. },
  103528. enumerable: true,
  103529. configurable: true
  103530. });
  103531. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  103532. var vrDisplay = this._scene.getEngine().getVRDevice();
  103533. if (vrDisplay) {
  103534. var wasPresenting = this._webVRpresenting;
  103535. this._webVRpresenting = vrDisplay.isPresenting;
  103536. if (wasPresenting && !this._webVRpresenting)
  103537. this.exitVR();
  103538. }
  103539. else {
  103540. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  103541. }
  103542. this.updateButtonVisibility();
  103543. };
  103544. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  103545. this._webVRsupported = eventArgs.vrSupported;
  103546. this._webVRready = !!eventArgs.vrDisplay;
  103547. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  103548. this.updateButtonVisibility();
  103549. };
  103550. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  103551. if (this._canvas && !this._useCustomVRButton) {
  103552. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  103553. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  103554. }
  103555. };
  103556. VRExperienceHelper.prototype.displayVRButton = function () {
  103557. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  103558. document.body.appendChild(this._btnVR);
  103559. this._btnVRDisplayed = true;
  103560. }
  103561. };
  103562. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  103563. if (!this._btnVR || this._useCustomVRButton) {
  103564. return;
  103565. }
  103566. this._btnVR.className = "babylonVRicon";
  103567. if (this.isInVRMode) {
  103568. this._btnVR.className += " vrdisplaypresenting";
  103569. }
  103570. else {
  103571. if (this._webVRready)
  103572. this._btnVR.className += " vrdisplayready";
  103573. if (this._webVRsupported)
  103574. this._btnVR.className += " vrdisplaysupported";
  103575. if (this._webVRrequesting)
  103576. this._btnVR.className += " vrdisplayrequesting";
  103577. }
  103578. };
  103579. /**
  103580. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  103581. * Otherwise, will use the fullscreen API.
  103582. */
  103583. VRExperienceHelper.prototype.enterVR = function () {
  103584. if (this.onEnteringVRObservable) {
  103585. try {
  103586. this.onEnteringVRObservable.notifyObservers(this);
  103587. }
  103588. catch (err) {
  103589. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  103590. }
  103591. }
  103592. if (this._scene.activeCamera) {
  103593. this._position = this._scene.activeCamera.position.clone();
  103594. // make sure that we return to the last active camera
  103595. this._existingCamera = this._scene.activeCamera;
  103596. }
  103597. if (this._webVRrequesting)
  103598. return;
  103599. // If WebVR is supported and a headset is connected
  103600. if (this._webVRready) {
  103601. if (!this._webVRpresenting) {
  103602. this._webVRCamera.position = this._position;
  103603. this._scene.activeCamera = this._webVRCamera;
  103604. }
  103605. }
  103606. else if (this._vrDeviceOrientationCamera) {
  103607. this._vrDeviceOrientationCamera.position = this._position;
  103608. if (this._scene.activeCamera) {
  103609. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  103610. }
  103611. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  103612. this._scene.getEngine().switchFullscreen(true);
  103613. this.updateButtonVisibility();
  103614. }
  103615. if (this._scene.activeCamera && this._canvas) {
  103616. this._scene.activeCamera.attachControl(this._canvas);
  103617. }
  103618. if (this._interactionsEnabled) {
  103619. this._scene.registerBeforeRender(this.beforeRender);
  103620. }
  103621. this._hasEnteredVR = true;
  103622. };
  103623. /**
  103624. * Attempt to exit VR, or fullscreen.
  103625. */
  103626. VRExperienceHelper.prototype.exitVR = function () {
  103627. if (this._hasEnteredVR) {
  103628. if (this.onExitingVRObservable) {
  103629. try {
  103630. this.onExitingVRObservable.notifyObservers(this);
  103631. }
  103632. catch (err) {
  103633. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  103634. }
  103635. }
  103636. if (this._webVRpresenting) {
  103637. this._scene.getEngine().disableVR();
  103638. }
  103639. if (this._scene.activeCamera) {
  103640. this._position = this._scene.activeCamera.position.clone();
  103641. }
  103642. if (this._deviceOrientationCamera) {
  103643. this._deviceOrientationCamera.position = this._position;
  103644. this._scene.activeCamera = this._deviceOrientationCamera;
  103645. if (this._canvas) {
  103646. this._scene.activeCamera.attachControl(this._canvas);
  103647. }
  103648. }
  103649. else if (this._existingCamera) {
  103650. this._existingCamera.position = this._position;
  103651. this._scene.activeCamera = this._existingCamera;
  103652. }
  103653. this.updateButtonVisibility();
  103654. if (this._interactionsEnabled) {
  103655. this._scene.unregisterBeforeRender(this.beforeRender);
  103656. this._cameraGazer._gazeTracker.isVisible = false;
  103657. if (this._leftController) {
  103658. this._leftController._gazeTracker.isVisible = false;
  103659. }
  103660. if (this._rightController) {
  103661. this._rightController._gazeTracker.isVisible = false;
  103662. }
  103663. }
  103664. // resize to update width and height when exiting vr exits fullscreen
  103665. this._scene.getEngine().resize();
  103666. this._hasEnteredVR = false;
  103667. }
  103668. };
  103669. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  103670. /**
  103671. * The position of the vr experience helper.
  103672. */
  103673. get: function () {
  103674. return this._position;
  103675. },
  103676. /**
  103677. * Sets the position of the vr experience helper.
  103678. */
  103679. set: function (value) {
  103680. this._position = value;
  103681. if (this._scene.activeCamera) {
  103682. this._scene.activeCamera.position = value;
  103683. }
  103684. },
  103685. enumerable: true,
  103686. configurable: true
  103687. });
  103688. /**
  103689. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  103690. */
  103691. VRExperienceHelper.prototype.enableInteractions = function () {
  103692. var _this = this;
  103693. if (!this._interactionsEnabled) {
  103694. this._interactionsRequested = true;
  103695. if (this._leftController) {
  103696. this._enableInteractionOnController(this._leftController);
  103697. }
  103698. if (this._rightController) {
  103699. this._enableInteractionOnController(this._rightController);
  103700. }
  103701. this.raySelectionPredicate = function (mesh) {
  103702. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  103703. };
  103704. this.meshSelectionPredicate = function (mesh) {
  103705. return true;
  103706. };
  103707. this._raySelectionPredicate = function (mesh) {
  103708. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  103709. && mesh.name.indexOf("teleportationTarget") === -1
  103710. && mesh.name.indexOf("torusTeleportation") === -1)) {
  103711. return _this.raySelectionPredicate(mesh);
  103712. }
  103713. return false;
  103714. };
  103715. this._interactionsEnabled = true;
  103716. }
  103717. };
  103718. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  103719. get: function () {
  103720. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  103721. },
  103722. enumerable: true,
  103723. configurable: true
  103724. });
  103725. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  103726. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  103727. if (this._floorMeshesCollection[i].id === mesh.id) {
  103728. return true;
  103729. }
  103730. }
  103731. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  103732. return true;
  103733. }
  103734. return false;
  103735. };
  103736. /**
  103737. * Adds a floor mesh to be used for teleportation.
  103738. * @param floorMesh the mesh to be used for teleportation.
  103739. */
  103740. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  103741. if (!this._floorMeshesCollection) {
  103742. return;
  103743. }
  103744. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  103745. return;
  103746. }
  103747. this._floorMeshesCollection.push(floorMesh);
  103748. };
  103749. /**
  103750. * Removes a floor mesh from being used for teleportation.
  103751. * @param floorMesh the mesh to be removed.
  103752. */
  103753. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  103754. if (!this._floorMeshesCollection) {
  103755. return;
  103756. }
  103757. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  103758. if (meshIndex !== -1) {
  103759. this._floorMeshesCollection.splice(meshIndex, 1);
  103760. }
  103761. };
  103762. /**
  103763. * Enables interactions and teleportation using the VR controllers and gaze.
  103764. * @param vrTeleportationOptions options to modify teleportation behavior.
  103765. */
  103766. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  103767. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  103768. if (!this._teleportationInitialized) {
  103769. this._teleportationRequested = true;
  103770. this.enableInteractions();
  103771. if (vrTeleportationOptions.floorMeshName) {
  103772. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  103773. }
  103774. if (vrTeleportationOptions.floorMeshes) {
  103775. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  103776. }
  103777. if (this._leftController != null) {
  103778. this._enableTeleportationOnController(this._leftController);
  103779. }
  103780. if (this._rightController != null) {
  103781. this._enableTeleportationOnController(this._rightController);
  103782. }
  103783. // Creates an image processing post process for the vignette not relying
  103784. // on the main scene configuration for image processing to reduce setup and spaces
  103785. // (gamma/linear) conflicts.
  103786. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  103787. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  103788. imageProcessingConfiguration.vignetteEnabled = true;
  103789. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  103790. this._webVRCamera.detachPostProcess(this._postProcessMove);
  103791. this._teleportationInitialized = true;
  103792. if (this._isDefaultTeleportationTarget) {
  103793. this._createTeleportationCircles();
  103794. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  103795. }
  103796. }
  103797. };
  103798. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  103799. var _this = this;
  103800. var controllerMesh = controller.webVRController.mesh;
  103801. if (controllerMesh) {
  103802. controller._interactionsEnabled = true;
  103803. controller._activatePointer();
  103804. if (this.webVROptions.laserToggle) {
  103805. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  103806. // Enabling / disabling laserPointer
  103807. if (_this._displayLaserPointer && stateObject.value === 1) {
  103808. if (controller._activePointer) {
  103809. controller._deactivatePointer();
  103810. }
  103811. else {
  103812. controller._activatePointer();
  103813. }
  103814. if (_this.displayGaze) {
  103815. controller._gazeTracker.isVisible = controller._activePointer;
  103816. }
  103817. }
  103818. });
  103819. }
  103820. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  103821. var gazer = controller;
  103822. if (_this._noControllerIsActive) {
  103823. gazer = _this._cameraGazer;
  103824. }
  103825. if (!gazer._pointerDownOnMeshAsked) {
  103826. if (stateObject.value > _this._padSensibilityUp) {
  103827. gazer._selectionPointerDown();
  103828. }
  103829. }
  103830. else if (stateObject.value < _this._padSensibilityDown) {
  103831. gazer._selectionPointerUp();
  103832. }
  103833. });
  103834. }
  103835. };
  103836. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  103837. // Dont teleport if another gaze already requested teleportation
  103838. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  103839. return;
  103840. }
  103841. if (!gazer._teleportationRequestInitiated) {
  103842. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  103843. gazer._activatePointer();
  103844. gazer._teleportationRequestInitiated = true;
  103845. }
  103846. }
  103847. else {
  103848. // Listening to the proper controller values changes to confirm teleportation
  103849. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  103850. if (this._teleportActive) {
  103851. this.teleportCamera(this._haloCenter);
  103852. }
  103853. gazer._teleportationRequestInitiated = false;
  103854. }
  103855. }
  103856. };
  103857. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  103858. // Only rotate when user is not currently selecting a teleportation location
  103859. if (gazer._teleportationRequestInitiated) {
  103860. return;
  103861. }
  103862. if (!gazer._rotationLeftAsked) {
  103863. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  103864. gazer._rotationLeftAsked = true;
  103865. if (this._rotationAllowed) {
  103866. this._rotateCamera(false);
  103867. }
  103868. }
  103869. }
  103870. else {
  103871. if (stateObject.x > -this._padSensibilityDown) {
  103872. gazer._rotationLeftAsked = false;
  103873. }
  103874. }
  103875. if (!gazer._rotationRightAsked) {
  103876. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  103877. gazer._rotationRightAsked = true;
  103878. if (this._rotationAllowed) {
  103879. this._rotateCamera(true);
  103880. }
  103881. }
  103882. }
  103883. else {
  103884. if (stateObject.x < this._padSensibilityDown) {
  103885. gazer._rotationRightAsked = false;
  103886. }
  103887. }
  103888. };
  103889. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  103890. // Only teleport backwards when user is not currently selecting a teleportation location
  103891. if (gazer._teleportationRequestInitiated) {
  103892. return;
  103893. }
  103894. // Teleport backwards
  103895. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  103896. if (!gazer._teleportationBackRequestInitiated) {
  103897. if (!this.currentVRCamera) {
  103898. return;
  103899. }
  103900. // Get rotation and position of the current camera
  103901. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  103902. var position = this.currentVRCamera.position;
  103903. // If the camera has device position, use that instead
  103904. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  103905. rotation = this.currentVRCamera.deviceRotationQuaternion;
  103906. position = this.currentVRCamera.devicePosition;
  103907. }
  103908. // Get matrix with only the y rotation of the device rotation
  103909. rotation.toEulerAnglesToRef(this._workingVector);
  103910. this._workingVector.z = 0;
  103911. this._workingVector.x = 0;
  103912. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  103913. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  103914. // Rotate backwards ray by device rotation to cast at the ground behind the user
  103915. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  103916. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  103917. var ray = new BABYLON.Ray(position, this._workingVector);
  103918. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  103919. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  103920. this.teleportCamera(hit.pickedPoint);
  103921. }
  103922. gazer._teleportationBackRequestInitiated = true;
  103923. }
  103924. }
  103925. else {
  103926. gazer._teleportationBackRequestInitiated = false;
  103927. }
  103928. };
  103929. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  103930. var _this = this;
  103931. var controllerMesh = controller.webVRController.mesh;
  103932. if (controllerMesh) {
  103933. if (!controller._interactionsEnabled) {
  103934. this._enableInteractionOnController(controller);
  103935. }
  103936. controller._interactionsEnabled = true;
  103937. controller._teleportationEnabled = true;
  103938. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103939. controller._dpadPressed = false;
  103940. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  103941. controller._dpadPressed = stateObject.pressed;
  103942. if (!controller._dpadPressed) {
  103943. controller._rotationLeftAsked = false;
  103944. controller._rotationRightAsked = false;
  103945. controller._teleportationBackRequestInitiated = false;
  103946. }
  103947. });
  103948. }
  103949. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  103950. if (_this.teleportationEnabled) {
  103951. _this._checkTeleportBackwards(stateObject, controller);
  103952. _this._checkTeleportWithRay(stateObject, controller);
  103953. }
  103954. _this._checkRotate(stateObject, controller);
  103955. });
  103956. }
  103957. };
  103958. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  103959. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  103960. this._teleportationTarget.isPickable = false;
  103961. var length = 512;
  103962. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  103963. dynamicTexture.hasAlpha = true;
  103964. var context = dynamicTexture.getContext();
  103965. var centerX = length / 2;
  103966. var centerY = length / 2;
  103967. var radius = 200;
  103968. context.beginPath();
  103969. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  103970. context.fillStyle = this._teleportationFillColor;
  103971. context.fill();
  103972. context.lineWidth = 10;
  103973. context.strokeStyle = this._teleportationBorderColor;
  103974. context.stroke();
  103975. context.closePath();
  103976. dynamicTexture.update();
  103977. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  103978. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  103979. this._teleportationTarget.material = teleportationCircleMaterial;
  103980. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  103981. torus.isPickable = false;
  103982. torus.parent = this._teleportationTarget;
  103983. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  103984. var keys = [];
  103985. keys.push({
  103986. frame: 0,
  103987. value: 0
  103988. });
  103989. keys.push({
  103990. frame: 30,
  103991. value: 0.4
  103992. });
  103993. keys.push({
  103994. frame: 60,
  103995. value: 0
  103996. });
  103997. animationInnerCircle.setKeys(keys);
  103998. var easingFunction = new BABYLON.SineEase();
  103999. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  104000. animationInnerCircle.setEasingFunction(easingFunction);
  104001. torus.animations = [];
  104002. torus.animations.push(animationInnerCircle);
  104003. this._scene.beginAnimation(torus, 0, 60, true);
  104004. this._hideTeleportationTarget();
  104005. };
  104006. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  104007. this._teleportActive = true;
  104008. if (this._teleportationInitialized) {
  104009. this._teleportationTarget.isVisible = true;
  104010. if (this._isDefaultTeleportationTarget) {
  104011. this._teleportationTarget.getChildren()[0].isVisible = true;
  104012. }
  104013. }
  104014. };
  104015. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  104016. this._teleportActive = false;
  104017. if (this._teleportationInitialized) {
  104018. this._teleportationTarget.isVisible = false;
  104019. if (this._isDefaultTeleportationTarget) {
  104020. this._teleportationTarget.getChildren()[0].isVisible = false;
  104021. }
  104022. }
  104023. };
  104024. VRExperienceHelper.prototype._rotateCamera = function (right) {
  104025. var _this = this;
  104026. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104027. return;
  104028. }
  104029. if (right) {
  104030. this._rotationAngle++;
  104031. }
  104032. else {
  104033. this._rotationAngle--;
  104034. }
  104035. this.currentVRCamera.animations = [];
  104036. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  104037. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104038. var animationRotationKeys = [];
  104039. animationRotationKeys.push({
  104040. frame: 0,
  104041. value: this.currentVRCamera.rotationQuaternion
  104042. });
  104043. animationRotationKeys.push({
  104044. frame: 6,
  104045. value: target
  104046. });
  104047. animationRotation.setKeys(animationRotationKeys);
  104048. animationRotation.setEasingFunction(this._circleEase);
  104049. this.currentVRCamera.animations.push(animationRotation);
  104050. this._postProcessMove.animations = [];
  104051. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104052. var vignetteWeightKeys = [];
  104053. vignetteWeightKeys.push({
  104054. frame: 0,
  104055. value: 0
  104056. });
  104057. vignetteWeightKeys.push({
  104058. frame: 3,
  104059. value: 4
  104060. });
  104061. vignetteWeightKeys.push({
  104062. frame: 6,
  104063. value: 0
  104064. });
  104065. animationPP.setKeys(vignetteWeightKeys);
  104066. animationPP.setEasingFunction(this._circleEase);
  104067. this._postProcessMove.animations.push(animationPP);
  104068. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104069. var vignetteStretchKeys = [];
  104070. vignetteStretchKeys.push({
  104071. frame: 0,
  104072. value: 0
  104073. });
  104074. vignetteStretchKeys.push({
  104075. frame: 3,
  104076. value: 10
  104077. });
  104078. vignetteStretchKeys.push({
  104079. frame: 6,
  104080. value: 0
  104081. });
  104082. animationPP2.setKeys(vignetteStretchKeys);
  104083. animationPP2.setEasingFunction(this._circleEase);
  104084. this._postProcessMove.animations.push(animationPP2);
  104085. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  104086. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  104087. this._postProcessMove.samples = 4;
  104088. this._webVRCamera.attachPostProcess(this._postProcessMove);
  104089. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  104090. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  104091. });
  104092. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  104093. };
  104094. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  104095. if (hit.pickedPoint) {
  104096. if (gazer._teleportationRequestInitiated) {
  104097. this._displayTeleportationTarget();
  104098. this._haloCenter.copyFrom(hit.pickedPoint);
  104099. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  104100. }
  104101. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  104102. if (pickNormal) {
  104103. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  104104. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  104105. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  104106. }
  104107. this._teleportationTarget.position.y += 0.1;
  104108. }
  104109. };
  104110. /**
  104111. * Teleports the users feet to the desired location
  104112. * @param location The location where the user's feet should be placed
  104113. */
  104114. VRExperienceHelper.prototype.teleportCamera = function (location) {
  104115. var _this = this;
  104116. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104117. return;
  104118. }
  104119. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  104120. // offset of the headset from the anchor.
  104121. if (this.webVRCamera.leftCamera) {
  104122. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  104123. this._workingVector.subtractInPlace(this.webVRCamera.position);
  104124. location.subtractToRef(this._workingVector, this._workingVector);
  104125. }
  104126. else {
  104127. this._workingVector.copyFrom(location);
  104128. }
  104129. // Add height to account for user's height offset
  104130. if (this.isInVRMode) {
  104131. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  104132. }
  104133. else {
  104134. this._workingVector.y += this._defaultHeight;
  104135. }
  104136. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  104137. // Create animation from the camera's position to the new location
  104138. this.currentVRCamera.animations = [];
  104139. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104140. var animationCameraTeleportationKeys = [{
  104141. frame: 0,
  104142. value: this.currentVRCamera.position
  104143. },
  104144. {
  104145. frame: 11,
  104146. value: this._workingVector
  104147. }
  104148. ];
  104149. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  104150. animationCameraTeleportation.setEasingFunction(this._circleEase);
  104151. this.currentVRCamera.animations.push(animationCameraTeleportation);
  104152. this._postProcessMove.animations = [];
  104153. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104154. var vignetteWeightKeys = [];
  104155. vignetteWeightKeys.push({
  104156. frame: 0,
  104157. value: 0
  104158. });
  104159. vignetteWeightKeys.push({
  104160. frame: 5,
  104161. value: 8
  104162. });
  104163. vignetteWeightKeys.push({
  104164. frame: 11,
  104165. value: 0
  104166. });
  104167. animationPP.setKeys(vignetteWeightKeys);
  104168. this._postProcessMove.animations.push(animationPP);
  104169. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104170. var vignetteStretchKeys = [];
  104171. vignetteStretchKeys.push({
  104172. frame: 0,
  104173. value: 0
  104174. });
  104175. vignetteStretchKeys.push({
  104176. frame: 5,
  104177. value: 10
  104178. });
  104179. vignetteStretchKeys.push({
  104180. frame: 11,
  104181. value: 0
  104182. });
  104183. animationPP2.setKeys(vignetteStretchKeys);
  104184. this._postProcessMove.animations.push(animationPP2);
  104185. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  104186. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  104187. this._webVRCamera.attachPostProcess(this._postProcessMove);
  104188. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  104189. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  104190. });
  104191. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  104192. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  104193. });
  104194. this._hideTeleportationTarget();
  104195. };
  104196. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  104197. if (normal) {
  104198. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  104199. if (angle < Math.PI / 2) {
  104200. normal.scaleInPlace(-1);
  104201. }
  104202. }
  104203. return normal;
  104204. };
  104205. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  104206. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104207. return;
  104208. }
  104209. var ray = gazer._getForwardRay(this._rayLength);
  104210. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  104211. if (hit) {
  104212. // Populate the contrllers mesh that can be used for drag/drop
  104213. if (gazer._laserPointer) {
  104214. hit.originMesh = gazer._laserPointer.parent;
  104215. }
  104216. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  104217. }
  104218. gazer._currentHit = hit;
  104219. // Moving the gazeTracker on the mesh face targetted
  104220. if (hit && hit.pickedPoint) {
  104221. if (this._displayGaze) {
  104222. var multiplier = 1;
  104223. gazer._gazeTracker.isVisible = true;
  104224. if (gazer._isActionableMesh) {
  104225. multiplier = 3;
  104226. }
  104227. if (this.updateGazeTrackerScale) {
  104228. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  104229. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  104230. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  104231. }
  104232. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  104233. // To avoid z-fighting
  104234. var deltaFighting = 0.002;
  104235. if (pickNormal) {
  104236. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  104237. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  104238. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  104239. }
  104240. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  104241. if (gazer._gazeTracker.position.x < 0) {
  104242. gazer._gazeTracker.position.x += deltaFighting;
  104243. }
  104244. else {
  104245. gazer._gazeTracker.position.x -= deltaFighting;
  104246. }
  104247. if (gazer._gazeTracker.position.y < 0) {
  104248. gazer._gazeTracker.position.y += deltaFighting;
  104249. }
  104250. else {
  104251. gazer._gazeTracker.position.y -= deltaFighting;
  104252. }
  104253. if (gazer._gazeTracker.position.z < 0) {
  104254. gazer._gazeTracker.position.z += deltaFighting;
  104255. }
  104256. else {
  104257. gazer._gazeTracker.position.z -= deltaFighting;
  104258. }
  104259. }
  104260. // Changing the size of the laser pointer based on the distance from the targetted point
  104261. gazer._updatePointerDistance(hit.distance);
  104262. }
  104263. else {
  104264. gazer._updatePointerDistance();
  104265. gazer._gazeTracker.isVisible = false;
  104266. }
  104267. if (hit && hit.pickedMesh) {
  104268. // The object selected is the floor, we're in a teleportation scenario
  104269. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  104270. // Moving the teleportation area to this targetted point
  104271. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  104272. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  104273. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104274. }
  104275. gazer._currentMeshSelected = null;
  104276. if (gazer._teleportationRequestInitiated) {
  104277. this._moveTeleportationSelectorTo(hit, gazer, ray);
  104278. }
  104279. return;
  104280. }
  104281. // If not, we're in a selection scenario
  104282. //this._teleportationAllowed = false;
  104283. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  104284. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  104285. this.onNewMeshPicked.notifyObservers(hit);
  104286. gazer._currentMeshSelected = hit.pickedMesh;
  104287. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  104288. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  104289. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  104290. gazer._isActionableMesh = true;
  104291. }
  104292. else {
  104293. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104294. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104295. gazer._isActionableMesh = false;
  104296. }
  104297. try {
  104298. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  104299. }
  104300. catch (err) {
  104301. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  104302. }
  104303. }
  104304. else {
  104305. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104306. gazer._currentMeshSelected = null;
  104307. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104308. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104309. }
  104310. }
  104311. }
  104312. else {
  104313. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104314. gazer._currentMeshSelected = null;
  104315. //this._teleportationAllowed = false;
  104316. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104317. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104318. }
  104319. };
  104320. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  104321. if (mesh) {
  104322. this.onSelectedMeshUnselected.notifyObservers(mesh);
  104323. }
  104324. };
  104325. /**
  104326. * Sets the color of the laser ray from the vr controllers.
  104327. * @param color new color for the ray.
  104328. */
  104329. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  104330. if (this._leftController) {
  104331. this._leftController._setLaserPointerColor(color);
  104332. }
  104333. if (this._rightController) {
  104334. this._rightController._setLaserPointerColor(color);
  104335. }
  104336. };
  104337. /**
  104338. * Sets the color of the ray from the vr headsets gaze.
  104339. * @param color new color for the ray.
  104340. */
  104341. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  104342. if (!this._cameraGazer._gazeTracker.material) {
  104343. return;
  104344. }
  104345. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  104346. if (this._leftController) {
  104347. this._leftController._gazeTracker.material.emissiveColor = color;
  104348. }
  104349. if (this._rightController) {
  104350. this._rightController._gazeTracker.material.emissiveColor = color;
  104351. }
  104352. };
  104353. /**
  104354. * Exits VR and disposes of the vr experience helper
  104355. */
  104356. VRExperienceHelper.prototype.dispose = function () {
  104357. if (this.isInVRMode) {
  104358. this.exitVR();
  104359. }
  104360. if (this._postProcessMove) {
  104361. this._postProcessMove.dispose();
  104362. }
  104363. if (this._webVRCamera) {
  104364. this._webVRCamera.dispose();
  104365. }
  104366. if (this._vrDeviceOrientationCamera) {
  104367. this._vrDeviceOrientationCamera.dispose();
  104368. }
  104369. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  104370. document.body.removeChild(this._btnVR);
  104371. }
  104372. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  104373. this._deviceOrientationCamera.dispose();
  104374. }
  104375. if (this._cameraGazer) {
  104376. this._cameraGazer.dispose();
  104377. }
  104378. if (this._leftController) {
  104379. this._leftController.dispose();
  104380. }
  104381. if (this._rightController) {
  104382. this._rightController.dispose();
  104383. }
  104384. if (this._teleportationTarget) {
  104385. this._teleportationTarget.dispose();
  104386. }
  104387. this._floorMeshesCollection = [];
  104388. document.removeEventListener("keydown", this._onKeyDown);
  104389. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104390. window.removeEventListener("resize", this._onResize);
  104391. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  104392. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  104393. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  104394. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  104395. document.onmsfullscreenchange = null;
  104396. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  104397. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  104398. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  104399. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104400. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  104401. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  104402. this._scene.unregisterBeforeRender(this.beforeRender);
  104403. };
  104404. /**
  104405. * Gets the name of the VRExperienceHelper class
  104406. * @returns "VRExperienceHelper"
  104407. */
  104408. VRExperienceHelper.prototype.getClassName = function () {
  104409. return "VRExperienceHelper";
  104410. };
  104411. return VRExperienceHelper;
  104412. }());
  104413. BABYLON.VRExperienceHelper = VRExperienceHelper;
  104414. })(BABYLON || (BABYLON = {}));
  104415. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  104416. // Mainly based on these 2 articles :
  104417. // 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
  104418. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  104419. var BABYLON;
  104420. (function (BABYLON) {
  104421. /**
  104422. * Defines the potential axis of a Joystick
  104423. */
  104424. var JoystickAxis;
  104425. (function (JoystickAxis) {
  104426. /** X axis */
  104427. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  104428. /** Y axis */
  104429. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  104430. /** Z axis */
  104431. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  104432. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  104433. /**
  104434. * Class used to define virtual joystick (used in touch mode)
  104435. */
  104436. var VirtualJoystick = /** @class */ (function () {
  104437. /**
  104438. * Creates a new virtual joystick
  104439. * @param leftJoystick defines that the joystick is for left hand (false by default)
  104440. */
  104441. function VirtualJoystick(leftJoystick) {
  104442. var _this = this;
  104443. if (leftJoystick) {
  104444. this._leftJoystick = true;
  104445. }
  104446. else {
  104447. this._leftJoystick = false;
  104448. }
  104449. VirtualJoystick._globalJoystickIndex++;
  104450. // By default left & right arrow keys are moving the X
  104451. // and up & down keys are moving the Y
  104452. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  104453. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  104454. this.reverseLeftRight = false;
  104455. this.reverseUpDown = false;
  104456. // collections of pointers
  104457. this._touches = new BABYLON.StringDictionary();
  104458. this.deltaPosition = BABYLON.Vector3.Zero();
  104459. this._joystickSensibility = 25;
  104460. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  104461. this._onResize = function (evt) {
  104462. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  104463. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  104464. if (VirtualJoystick.vjCanvas) {
  104465. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  104466. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  104467. }
  104468. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  104469. };
  104470. // injecting a canvas element on top of the canvas 3D game
  104471. if (!VirtualJoystick.vjCanvas) {
  104472. window.addEventListener("resize", this._onResize, false);
  104473. VirtualJoystick.vjCanvas = document.createElement("canvas");
  104474. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  104475. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  104476. VirtualJoystick.vjCanvas.width = window.innerWidth;
  104477. VirtualJoystick.vjCanvas.height = window.innerHeight;
  104478. VirtualJoystick.vjCanvas.style.width = "100%";
  104479. VirtualJoystick.vjCanvas.style.height = "100%";
  104480. VirtualJoystick.vjCanvas.style.position = "absolute";
  104481. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  104482. VirtualJoystick.vjCanvas.style.top = "0px";
  104483. VirtualJoystick.vjCanvas.style.left = "0px";
  104484. VirtualJoystick.vjCanvas.style.zIndex = "5";
  104485. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  104486. // Support for jQuery PEP polyfill
  104487. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  104488. var context = VirtualJoystick.vjCanvas.getContext('2d');
  104489. if (!context) {
  104490. throw new Error("Unable to create canvas for virtual joystick");
  104491. }
  104492. VirtualJoystick.vjCanvasContext = context;
  104493. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  104494. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  104495. document.body.appendChild(VirtualJoystick.vjCanvas);
  104496. }
  104497. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  104498. this.pressed = false;
  104499. // default joystick color
  104500. this._joystickColor = "cyan";
  104501. this._joystickPointerID = -1;
  104502. // current joystick position
  104503. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  104504. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  104505. // origin joystick position
  104506. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  104507. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  104508. this._onPointerDownHandlerRef = function (evt) {
  104509. _this._onPointerDown(evt);
  104510. };
  104511. this._onPointerMoveHandlerRef = function (evt) {
  104512. _this._onPointerMove(evt);
  104513. };
  104514. this._onPointerUpHandlerRef = function (evt) {
  104515. _this._onPointerUp(evt);
  104516. };
  104517. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  104518. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  104519. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  104520. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  104521. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  104522. evt.preventDefault(); // Disables system menu
  104523. }, false);
  104524. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  104525. }
  104526. /**
  104527. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  104528. * @param newJoystickSensibility defines the new sensibility
  104529. */
  104530. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  104531. this._joystickSensibility = newJoystickSensibility;
  104532. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  104533. };
  104534. VirtualJoystick.prototype._onPointerDown = function (e) {
  104535. var positionOnScreenCondition;
  104536. e.preventDefault();
  104537. if (this._leftJoystick === true) {
  104538. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  104539. }
  104540. else {
  104541. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  104542. }
  104543. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  104544. // First contact will be dedicated to the virtual joystick
  104545. this._joystickPointerID = e.pointerId;
  104546. this._joystickPointerStartPos.x = e.clientX;
  104547. this._joystickPointerStartPos.y = e.clientY;
  104548. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  104549. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  104550. this._deltaJoystickVector.x = 0;
  104551. this._deltaJoystickVector.y = 0;
  104552. this.pressed = true;
  104553. this._touches.add(e.pointerId.toString(), e);
  104554. }
  104555. else {
  104556. // You can only trigger the action buttons with a joystick declared
  104557. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  104558. this._action();
  104559. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  104560. }
  104561. }
  104562. };
  104563. VirtualJoystick.prototype._onPointerMove = function (e) {
  104564. // If the current pointer is the one associated to the joystick (first touch contact)
  104565. if (this._joystickPointerID == e.pointerId) {
  104566. this._joystickPointerPos.x = e.clientX;
  104567. this._joystickPointerPos.y = e.clientY;
  104568. this._deltaJoystickVector = this._joystickPointerPos.clone();
  104569. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  104570. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  104571. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  104572. switch (this._axisTargetedByLeftAndRight) {
  104573. case JoystickAxis.X:
  104574. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  104575. break;
  104576. case JoystickAxis.Y:
  104577. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  104578. break;
  104579. case JoystickAxis.Z:
  104580. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  104581. break;
  104582. }
  104583. var directionUpDown = this.reverseUpDown ? 1 : -1;
  104584. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  104585. switch (this._axisTargetedByUpAndDown) {
  104586. case JoystickAxis.X:
  104587. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  104588. break;
  104589. case JoystickAxis.Y:
  104590. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  104591. break;
  104592. case JoystickAxis.Z:
  104593. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  104594. break;
  104595. }
  104596. }
  104597. else {
  104598. var data = this._touches.get(e.pointerId.toString());
  104599. if (data) {
  104600. data.x = e.clientX;
  104601. data.y = e.clientY;
  104602. }
  104603. }
  104604. };
  104605. VirtualJoystick.prototype._onPointerUp = function (e) {
  104606. if (this._joystickPointerID == e.pointerId) {
  104607. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  104608. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  104609. this._joystickPointerID = -1;
  104610. this.pressed = false;
  104611. }
  104612. else {
  104613. var touch = this._touches.get(e.pointerId.toString());
  104614. if (touch) {
  104615. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  104616. }
  104617. }
  104618. this._deltaJoystickVector.x = 0;
  104619. this._deltaJoystickVector.y = 0;
  104620. this._touches.remove(e.pointerId.toString());
  104621. };
  104622. /**
  104623. * Change the color of the virtual joystick
  104624. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  104625. */
  104626. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  104627. this._joystickColor = newColor;
  104628. };
  104629. /**
  104630. * Defines a callback to call when the joystick is touched
  104631. * @param action defines the callback
  104632. */
  104633. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  104634. this._action = action;
  104635. };
  104636. /**
  104637. * Defines which axis you'd like to control for left & right
  104638. * @param axis defines the axis to use
  104639. */
  104640. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  104641. switch (axis) {
  104642. case JoystickAxis.X:
  104643. case JoystickAxis.Y:
  104644. case JoystickAxis.Z:
  104645. this._axisTargetedByLeftAndRight = axis;
  104646. break;
  104647. default:
  104648. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  104649. break;
  104650. }
  104651. };
  104652. /**
  104653. * Defines which axis you'd like to control for up & down
  104654. * @param axis defines the axis to use
  104655. */
  104656. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  104657. switch (axis) {
  104658. case JoystickAxis.X:
  104659. case JoystickAxis.Y:
  104660. case JoystickAxis.Z:
  104661. this._axisTargetedByUpAndDown = axis;
  104662. break;
  104663. default:
  104664. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  104665. break;
  104666. }
  104667. };
  104668. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  104669. var _this = this;
  104670. if (this.pressed) {
  104671. this._touches.forEach(function (key, touch) {
  104672. if (touch.pointerId === _this._joystickPointerID) {
  104673. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  104674. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  104675. VirtualJoystick.vjCanvasContext.beginPath();
  104676. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  104677. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104678. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  104679. VirtualJoystick.vjCanvasContext.stroke();
  104680. VirtualJoystick.vjCanvasContext.closePath();
  104681. VirtualJoystick.vjCanvasContext.beginPath();
  104682. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104683. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  104684. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  104685. VirtualJoystick.vjCanvasContext.stroke();
  104686. VirtualJoystick.vjCanvasContext.closePath();
  104687. VirtualJoystick.vjCanvasContext.beginPath();
  104688. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104689. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  104690. VirtualJoystick.vjCanvasContext.stroke();
  104691. VirtualJoystick.vjCanvasContext.closePath();
  104692. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  104693. }
  104694. else {
  104695. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  104696. VirtualJoystick.vjCanvasContext.beginPath();
  104697. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  104698. VirtualJoystick.vjCanvasContext.beginPath();
  104699. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  104700. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  104701. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  104702. VirtualJoystick.vjCanvasContext.stroke();
  104703. VirtualJoystick.vjCanvasContext.closePath();
  104704. touch.prevX = touch.x;
  104705. touch.prevY = touch.y;
  104706. }
  104707. ;
  104708. });
  104709. }
  104710. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  104711. };
  104712. /**
  104713. * Release internal HTML canvas
  104714. */
  104715. VirtualJoystick.prototype.releaseCanvas = function () {
  104716. if (VirtualJoystick.vjCanvas) {
  104717. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  104718. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  104719. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  104720. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  104721. window.removeEventListener("resize", this._onResize);
  104722. document.body.removeChild(VirtualJoystick.vjCanvas);
  104723. VirtualJoystick.vjCanvas = null;
  104724. }
  104725. };
  104726. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  104727. VirtualJoystick._globalJoystickIndex = 0;
  104728. return VirtualJoystick;
  104729. }());
  104730. BABYLON.VirtualJoystick = VirtualJoystick;
  104731. })(BABYLON || (BABYLON = {}));
  104732. //# sourceMappingURL=babylon.virtualJoystick.js.map
  104733. var BABYLON;
  104734. (function (BABYLON) {
  104735. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  104736. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  104737. });
  104738. /**
  104739. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  104740. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  104741. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  104742. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  104743. */
  104744. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  104745. __extends(VirtualJoysticksCamera, _super);
  104746. /**
  104747. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  104748. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  104749. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  104750. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  104751. * @param name Define the name of the camera in the scene
  104752. * @param position Define the start position of the camera in the scene
  104753. * @param scene Define the scene the camera belongs to
  104754. */
  104755. function VirtualJoysticksCamera(name, position, scene) {
  104756. var _this = _super.call(this, name, position, scene) || this;
  104757. _this.inputs.addVirtualJoystick();
  104758. return _this;
  104759. }
  104760. /**
  104761. * Gets the current object class name.
  104762. * @return the class name
  104763. */
  104764. VirtualJoysticksCamera.prototype.getClassName = function () {
  104765. return "VirtualJoysticksCamera";
  104766. };
  104767. return VirtualJoysticksCamera;
  104768. }(BABYLON.FreeCamera));
  104769. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  104770. })(BABYLON || (BABYLON = {}));
  104771. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  104772. var BABYLON;
  104773. (function (BABYLON) {
  104774. /**
  104775. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  104776. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104777. */
  104778. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  104779. function FreeCameraVirtualJoystickInput() {
  104780. }
  104781. /**
  104782. * Gets the left stick of the virtual joystick.
  104783. * @returns The virtual Joystick
  104784. */
  104785. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  104786. return this._leftjoystick;
  104787. };
  104788. /**
  104789. * Gets the right stick of the virtual joystick.
  104790. * @returns The virtual Joystick
  104791. */
  104792. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  104793. return this._rightjoystick;
  104794. };
  104795. /**
  104796. * Update the current camera state depending on the inputs that have been used this frame.
  104797. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104798. */
  104799. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  104800. if (this._leftjoystick) {
  104801. var camera = this.camera;
  104802. var speed = camera._computeLocalCameraSpeed() * 50;
  104803. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  104804. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  104805. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  104806. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  104807. if (!this._leftjoystick.pressed) {
  104808. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  104809. }
  104810. if (!this._rightjoystick.pressed) {
  104811. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  104812. }
  104813. }
  104814. };
  104815. /**
  104816. * Attach the input controls to a specific dom element to get the input from.
  104817. * @param element Defines the element the controls should be listened from
  104818. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104819. */
  104820. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  104821. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  104822. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  104823. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  104824. this._leftjoystick.setJoystickSensibility(0.15);
  104825. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  104826. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  104827. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  104828. this._rightjoystick.reverseUpDown = true;
  104829. this._rightjoystick.setJoystickSensibility(0.05);
  104830. this._rightjoystick.setJoystickColor("yellow");
  104831. };
  104832. /**
  104833. * Detach the current controls from the specified dom element.
  104834. * @param element Defines the element to stop listening the inputs from
  104835. */
  104836. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  104837. this._leftjoystick.releaseCanvas();
  104838. this._rightjoystick.releaseCanvas();
  104839. };
  104840. /**
  104841. * Gets the class name of the current intput.
  104842. * @returns the class name
  104843. */
  104844. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  104845. return "FreeCameraVirtualJoystickInput";
  104846. };
  104847. /**
  104848. * Get the friendly name associated with the input class.
  104849. * @returns the input friendly name
  104850. */
  104851. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  104852. return "virtualJoystick";
  104853. };
  104854. return FreeCameraVirtualJoystickInput;
  104855. }());
  104856. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  104857. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  104858. })(BABYLON || (BABYLON = {}));
  104859. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  104860. var BABYLON;
  104861. (function (BABYLON) {
  104862. /**
  104863. * Class used to specify simplification options
  104864. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104865. */
  104866. var SimplificationSettings = /** @class */ (function () {
  104867. /**
  104868. * Creates a SimplificationSettings
  104869. * @param quality expected quality
  104870. * @param distance distance when this optimized version should be used
  104871. * @param optimizeMesh already optimized mesh
  104872. */
  104873. function SimplificationSettings(
  104874. /** expected quality */
  104875. quality,
  104876. /** distance when this optimized version should be used */
  104877. distance,
  104878. /** already optimized mesh */
  104879. optimizeMesh) {
  104880. this.quality = quality;
  104881. this.distance = distance;
  104882. this.optimizeMesh = optimizeMesh;
  104883. }
  104884. return SimplificationSettings;
  104885. }());
  104886. BABYLON.SimplificationSettings = SimplificationSettings;
  104887. /**
  104888. * Queue used to order the simplification tasks
  104889. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104890. */
  104891. var SimplificationQueue = /** @class */ (function () {
  104892. /**
  104893. * Creates a new queue
  104894. */
  104895. function SimplificationQueue() {
  104896. this.running = false;
  104897. this._simplificationArray = [];
  104898. }
  104899. /**
  104900. * Adds a new simplification task
  104901. * @param task defines a task to add
  104902. */
  104903. SimplificationQueue.prototype.addTask = function (task) {
  104904. this._simplificationArray.push(task);
  104905. };
  104906. /**
  104907. * Execute next task
  104908. */
  104909. SimplificationQueue.prototype.executeNext = function () {
  104910. var task = this._simplificationArray.pop();
  104911. if (task) {
  104912. this.running = true;
  104913. this.runSimplification(task);
  104914. }
  104915. else {
  104916. this.running = false;
  104917. }
  104918. };
  104919. /**
  104920. * Execute a simplification task
  104921. * @param task defines the task to run
  104922. */
  104923. SimplificationQueue.prototype.runSimplification = function (task) {
  104924. var _this = this;
  104925. if (task.parallelProcessing) {
  104926. //parallel simplifier
  104927. task.settings.forEach(function (setting) {
  104928. var simplifier = _this.getSimplifier(task);
  104929. simplifier.simplify(setting, function (newMesh) {
  104930. task.mesh.addLODLevel(setting.distance, newMesh);
  104931. newMesh.isVisible = true;
  104932. //check if it is the last
  104933. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  104934. //all done, run the success callback.
  104935. task.successCallback();
  104936. }
  104937. _this.executeNext();
  104938. });
  104939. });
  104940. }
  104941. else {
  104942. //single simplifier.
  104943. var simplifier = this.getSimplifier(task);
  104944. var runDecimation = function (setting, callback) {
  104945. simplifier.simplify(setting, function (newMesh) {
  104946. task.mesh.addLODLevel(setting.distance, newMesh);
  104947. newMesh.isVisible = true;
  104948. //run the next quality level
  104949. callback();
  104950. });
  104951. };
  104952. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  104953. runDecimation(task.settings[loop.index], function () {
  104954. loop.executeNext();
  104955. });
  104956. }, function () {
  104957. //execution ended, run the success callback.
  104958. if (task.successCallback) {
  104959. task.successCallback();
  104960. }
  104961. _this.executeNext();
  104962. });
  104963. }
  104964. };
  104965. SimplificationQueue.prototype.getSimplifier = function (task) {
  104966. switch (task.simplificationType) {
  104967. case SimplificationType.QUADRATIC:
  104968. default:
  104969. return new QuadraticErrorSimplification(task.mesh);
  104970. }
  104971. };
  104972. return SimplificationQueue;
  104973. }());
  104974. BABYLON.SimplificationQueue = SimplificationQueue;
  104975. /**
  104976. * The implemented types of simplification
  104977. * At the moment only Quadratic Error Decimation is implemented
  104978. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104979. */
  104980. var SimplificationType;
  104981. (function (SimplificationType) {
  104982. /** Quadratic error decimation */
  104983. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  104984. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  104985. var DecimationTriangle = /** @class */ (function () {
  104986. function DecimationTriangle(vertices) {
  104987. this.vertices = vertices;
  104988. this.error = new Array(4);
  104989. this.deleted = false;
  104990. this.isDirty = false;
  104991. this.deletePending = false;
  104992. this.borderFactor = 0;
  104993. }
  104994. return DecimationTriangle;
  104995. }());
  104996. var DecimationVertex = /** @class */ (function () {
  104997. function DecimationVertex(position, id) {
  104998. this.position = position;
  104999. this.id = id;
  105000. this.isBorder = true;
  105001. this.q = new QuadraticMatrix();
  105002. this.triangleCount = 0;
  105003. this.triangleStart = 0;
  105004. this.originalOffsets = [];
  105005. }
  105006. DecimationVertex.prototype.updatePosition = function (newPosition) {
  105007. this.position.copyFrom(newPosition);
  105008. };
  105009. return DecimationVertex;
  105010. }());
  105011. var QuadraticMatrix = /** @class */ (function () {
  105012. function QuadraticMatrix(data) {
  105013. this.data = new Array(10);
  105014. for (var i = 0; i < 10; ++i) {
  105015. if (data && data[i]) {
  105016. this.data[i] = data[i];
  105017. }
  105018. else {
  105019. this.data[i] = 0;
  105020. }
  105021. }
  105022. }
  105023. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  105024. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  105025. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  105026. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  105027. return det;
  105028. };
  105029. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  105030. for (var i = 0; i < 10; ++i) {
  105031. this.data[i] += matrix.data[i];
  105032. }
  105033. };
  105034. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  105035. for (var i = 0; i < 10; ++i) {
  105036. this.data[i] += data[i];
  105037. }
  105038. };
  105039. QuadraticMatrix.prototype.add = function (matrix) {
  105040. var m = new QuadraticMatrix();
  105041. for (var i = 0; i < 10; ++i) {
  105042. m.data[i] = this.data[i] + matrix.data[i];
  105043. }
  105044. return m;
  105045. };
  105046. QuadraticMatrix.FromData = function (a, b, c, d) {
  105047. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  105048. };
  105049. //returning an array to avoid garbage collection
  105050. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  105051. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  105052. };
  105053. return QuadraticMatrix;
  105054. }());
  105055. var Reference = /** @class */ (function () {
  105056. function Reference(vertexId, triangleId) {
  105057. this.vertexId = vertexId;
  105058. this.triangleId = triangleId;
  105059. }
  105060. return Reference;
  105061. }());
  105062. /**
  105063. * An implementation of the Quadratic Error simplification algorithm.
  105064. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  105065. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  105066. * @author RaananW
  105067. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  105068. */
  105069. var QuadraticErrorSimplification = /** @class */ (function () {
  105070. function QuadraticErrorSimplification(_mesh) {
  105071. this._mesh = _mesh;
  105072. this.syncIterations = 5000;
  105073. this.aggressiveness = 7;
  105074. this.decimationIterations = 100;
  105075. this.boundingBoxEpsilon = BABYLON.Epsilon;
  105076. }
  105077. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  105078. var _this = this;
  105079. this.initDecimatedMesh();
  105080. //iterating through the submeshes array, one after the other.
  105081. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  105082. _this.initWithMesh(loop.index, function () {
  105083. _this.runDecimation(settings, loop.index, function () {
  105084. loop.executeNext();
  105085. });
  105086. }, settings.optimizeMesh);
  105087. }, function () {
  105088. setTimeout(function () {
  105089. successCallback(_this._reconstructedMesh);
  105090. }, 0);
  105091. });
  105092. };
  105093. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  105094. var _this = this;
  105095. var targetCount = ~~(this.triangles.length * settings.quality);
  105096. var deletedTriangles = 0;
  105097. var triangleCount = this.triangles.length;
  105098. var iterationFunction = function (iteration, callback) {
  105099. setTimeout(function () {
  105100. if (iteration % 5 === 0) {
  105101. _this.updateMesh(iteration === 0);
  105102. }
  105103. for (var i = 0; i < _this.triangles.length; ++i) {
  105104. _this.triangles[i].isDirty = false;
  105105. }
  105106. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  105107. var trianglesIterator = function (i) {
  105108. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  105109. var t = _this.triangles[tIdx];
  105110. if (!t)
  105111. return;
  105112. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  105113. return;
  105114. }
  105115. for (var j = 0; j < 3; ++j) {
  105116. if (t.error[j] < threshold) {
  105117. var deleted0 = [];
  105118. var deleted1 = [];
  105119. var v0 = t.vertices[j];
  105120. var v1 = t.vertices[(j + 1) % 3];
  105121. if (v0.isBorder || v1.isBorder)
  105122. continue;
  105123. var p = BABYLON.Vector3.Zero();
  105124. var n = BABYLON.Vector3.Zero();
  105125. var uv = BABYLON.Vector2.Zero();
  105126. var color = new BABYLON.Color4(0, 0, 0, 1);
  105127. _this.calculateError(v0, v1, p, n, uv, color);
  105128. var delTr = new Array();
  105129. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  105130. continue;
  105131. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  105132. continue;
  105133. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  105134. continue;
  105135. var uniqueArray = new Array();
  105136. delTr.forEach(function (deletedT) {
  105137. if (uniqueArray.indexOf(deletedT) === -1) {
  105138. deletedT.deletePending = true;
  105139. uniqueArray.push(deletedT);
  105140. }
  105141. });
  105142. if (uniqueArray.length % 2 !== 0) {
  105143. continue;
  105144. }
  105145. v0.q = v1.q.add(v0.q);
  105146. v0.updatePosition(p);
  105147. var tStart = _this.references.length;
  105148. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  105149. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  105150. var tCount = _this.references.length - tStart;
  105151. if (tCount <= v0.triangleCount) {
  105152. if (tCount) {
  105153. for (var c = 0; c < tCount; c++) {
  105154. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  105155. }
  105156. }
  105157. }
  105158. else {
  105159. v0.triangleStart = tStart;
  105160. }
  105161. v0.triangleCount = tCount;
  105162. break;
  105163. }
  105164. }
  105165. };
  105166. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  105167. }, 0);
  105168. };
  105169. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  105170. if (triangleCount - deletedTriangles <= targetCount)
  105171. loop.breakLoop();
  105172. else {
  105173. iterationFunction(loop.index, function () {
  105174. loop.executeNext();
  105175. });
  105176. }
  105177. }, function () {
  105178. setTimeout(function () {
  105179. //reconstruct this part of the mesh
  105180. _this.reconstructMesh(submeshIndex);
  105181. successCallback();
  105182. }, 0);
  105183. });
  105184. };
  105185. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  105186. var _this = this;
  105187. this.vertices = [];
  105188. this.triangles = [];
  105189. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  105190. var indices = this._mesh.getIndices();
  105191. var submesh = this._mesh.subMeshes[submeshIndex];
  105192. var findInVertices = function (positionToSearch) {
  105193. if (optimizeMesh) {
  105194. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  105195. if (_this.vertices[ii].position.equals(positionToSearch)) {
  105196. return _this.vertices[ii];
  105197. }
  105198. }
  105199. }
  105200. return null;
  105201. };
  105202. var vertexReferences = [];
  105203. var vertexInit = function (i) {
  105204. if (!positionData) {
  105205. return;
  105206. }
  105207. var offset = i + submesh.verticesStart;
  105208. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  105209. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  105210. vertex.originalOffsets.push(offset);
  105211. if (vertex.id === _this.vertices.length) {
  105212. _this.vertices.push(vertex);
  105213. }
  105214. vertexReferences.push(vertex.id);
  105215. };
  105216. //var totalVertices = mesh.getTotalVertices();
  105217. var totalVertices = submesh.verticesCount;
  105218. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  105219. var indicesInit = function (i) {
  105220. if (!indices) {
  105221. return;
  105222. }
  105223. var offset = (submesh.indexStart / 3) + i;
  105224. var pos = (offset * 3);
  105225. var i0 = indices[pos + 0];
  105226. var i1 = indices[pos + 1];
  105227. var i2 = indices[pos + 2];
  105228. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  105229. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  105230. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  105231. var triangle = new DecimationTriangle([v0, v1, v2]);
  105232. triangle.originalOffset = pos;
  105233. _this.triangles.push(triangle);
  105234. };
  105235. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  105236. _this.init(callback);
  105237. });
  105238. });
  105239. };
  105240. QuadraticErrorSimplification.prototype.init = function (callback) {
  105241. var _this = this;
  105242. var triangleInit1 = function (i) {
  105243. var t = _this.triangles[i];
  105244. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  105245. for (var j = 0; j < 3; j++) {
  105246. 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))));
  105247. }
  105248. };
  105249. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  105250. var triangleInit2 = function (i) {
  105251. var t = _this.triangles[i];
  105252. for (var j = 0; j < 3; ++j) {
  105253. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  105254. }
  105255. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  105256. };
  105257. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  105258. callback();
  105259. });
  105260. });
  105261. };
  105262. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  105263. var newTriangles = [];
  105264. var i;
  105265. for (i = 0; i < this.vertices.length; ++i) {
  105266. this.vertices[i].triangleCount = 0;
  105267. }
  105268. var t;
  105269. var j;
  105270. for (i = 0; i < this.triangles.length; ++i) {
  105271. if (!this.triangles[i].deleted) {
  105272. t = this.triangles[i];
  105273. for (j = 0; j < 3; ++j) {
  105274. t.vertices[j].triangleCount = 1;
  105275. }
  105276. newTriangles.push(t);
  105277. }
  105278. }
  105279. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  105280. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  105281. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  105282. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  105283. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  105284. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  105285. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  105286. var vertexCount = 0;
  105287. for (i = 0; i < this.vertices.length; ++i) {
  105288. var vertex = this.vertices[i];
  105289. vertex.id = vertexCount;
  105290. if (vertex.triangleCount) {
  105291. vertex.originalOffsets.forEach(function (originalOffset) {
  105292. if (!normalData) {
  105293. return;
  105294. }
  105295. newPositionData.push(vertex.position.x);
  105296. newPositionData.push(vertex.position.y);
  105297. newPositionData.push(vertex.position.z);
  105298. newNormalData.push(normalData[originalOffset * 3]);
  105299. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  105300. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  105301. if (uvs && uvs.length) {
  105302. newUVsData.push(uvs[(originalOffset * 2)]);
  105303. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  105304. }
  105305. else if (colorsData && colorsData.length) {
  105306. newColorsData.push(colorsData[(originalOffset * 4)]);
  105307. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  105308. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  105309. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  105310. }
  105311. ++vertexCount;
  105312. });
  105313. }
  105314. }
  105315. var startingIndex = this._reconstructedMesh.getTotalIndices();
  105316. var startingVertex = this._reconstructedMesh.getTotalVertices();
  105317. var submeshesArray = this._reconstructedMesh.subMeshes;
  105318. this._reconstructedMesh.subMeshes = [];
  105319. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  105320. var originalIndices = this._mesh.getIndices();
  105321. for (i = 0; i < newTriangles.length; ++i) {
  105322. t = newTriangles[i]; //now get the new referencing point for each vertex
  105323. [0, 1, 2].forEach(function (idx) {
  105324. var id = originalIndices[t.originalOffset + idx];
  105325. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  105326. if (offset < 0)
  105327. offset = 0;
  105328. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  105329. });
  105330. }
  105331. //overwriting the old vertex buffers and indices.
  105332. this._reconstructedMesh.setIndices(newIndicesArray);
  105333. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  105334. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  105335. if (newUVsData.length > 0)
  105336. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  105337. if (newColorsData.length > 0)
  105338. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  105339. //create submesh
  105340. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  105341. if (submeshIndex > 0) {
  105342. this._reconstructedMesh.subMeshes = [];
  105343. submeshesArray.forEach(function (submesh) {
  105344. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  105345. });
  105346. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  105347. }
  105348. };
  105349. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  105350. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  105351. this._reconstructedMesh.material = this._mesh.material;
  105352. this._reconstructedMesh.parent = this._mesh.parent;
  105353. this._reconstructedMesh.isVisible = false;
  105354. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  105355. };
  105356. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  105357. for (var i = 0; i < vertex1.triangleCount; ++i) {
  105358. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  105359. if (t.deleted)
  105360. continue;
  105361. var s = this.references[vertex1.triangleStart + i].vertexId;
  105362. var v1 = t.vertices[(s + 1) % 3];
  105363. var v2 = t.vertices[(s + 2) % 3];
  105364. if ((v1 === vertex2 || v2 === vertex2)) {
  105365. deletedArray[i] = true;
  105366. delTr.push(t);
  105367. continue;
  105368. }
  105369. var d1 = v1.position.subtract(point);
  105370. d1 = d1.normalize();
  105371. var d2 = v2.position.subtract(point);
  105372. d2 = d2.normalize();
  105373. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  105374. return true;
  105375. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  105376. deletedArray[i] = false;
  105377. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  105378. return true;
  105379. }
  105380. return false;
  105381. };
  105382. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  105383. var newDeleted = deletedTriangles;
  105384. for (var i = 0; i < vertex.triangleCount; ++i) {
  105385. var ref = this.references[vertex.triangleStart + i];
  105386. var t = this.triangles[ref.triangleId];
  105387. if (t.deleted)
  105388. continue;
  105389. if (deletedArray[i] && t.deletePending) {
  105390. t.deleted = true;
  105391. newDeleted++;
  105392. continue;
  105393. }
  105394. t.vertices[ref.vertexId] = origVertex;
  105395. t.isDirty = true;
  105396. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  105397. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  105398. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  105399. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  105400. this.references.push(ref);
  105401. }
  105402. return newDeleted;
  105403. };
  105404. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  105405. for (var i = 0; i < this.vertices.length; ++i) {
  105406. var vCount = [];
  105407. var vId = [];
  105408. var v = this.vertices[i];
  105409. var j;
  105410. for (j = 0; j < v.triangleCount; ++j) {
  105411. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  105412. for (var ii = 0; ii < 3; ii++) {
  105413. var ofs = 0;
  105414. var vv = triangle.vertices[ii];
  105415. while (ofs < vCount.length) {
  105416. if (vId[ofs] === vv.id)
  105417. break;
  105418. ++ofs;
  105419. }
  105420. if (ofs === vCount.length) {
  105421. vCount.push(1);
  105422. vId.push(vv.id);
  105423. }
  105424. else {
  105425. vCount[ofs]++;
  105426. }
  105427. }
  105428. }
  105429. for (j = 0; j < vCount.length; ++j) {
  105430. if (vCount[j] === 1) {
  105431. this.vertices[vId[j]].isBorder = true;
  105432. }
  105433. else {
  105434. this.vertices[vId[j]].isBorder = false;
  105435. }
  105436. }
  105437. }
  105438. };
  105439. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  105440. if (identifyBorders === void 0) { identifyBorders = false; }
  105441. var i;
  105442. if (!identifyBorders) {
  105443. var newTrianglesVector = [];
  105444. for (i = 0; i < this.triangles.length; ++i) {
  105445. if (!this.triangles[i].deleted) {
  105446. newTrianglesVector.push(this.triangles[i]);
  105447. }
  105448. }
  105449. this.triangles = newTrianglesVector;
  105450. }
  105451. for (i = 0; i < this.vertices.length; ++i) {
  105452. this.vertices[i].triangleCount = 0;
  105453. this.vertices[i].triangleStart = 0;
  105454. }
  105455. var t;
  105456. var j;
  105457. var v;
  105458. for (i = 0; i < this.triangles.length; ++i) {
  105459. t = this.triangles[i];
  105460. for (j = 0; j < 3; ++j) {
  105461. v = t.vertices[j];
  105462. v.triangleCount++;
  105463. }
  105464. }
  105465. var tStart = 0;
  105466. for (i = 0; i < this.vertices.length; ++i) {
  105467. this.vertices[i].triangleStart = tStart;
  105468. tStart += this.vertices[i].triangleCount;
  105469. this.vertices[i].triangleCount = 0;
  105470. }
  105471. var newReferences = new Array(this.triangles.length * 3);
  105472. for (i = 0; i < this.triangles.length; ++i) {
  105473. t = this.triangles[i];
  105474. for (j = 0; j < 3; ++j) {
  105475. v = t.vertices[j];
  105476. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  105477. v.triangleCount++;
  105478. }
  105479. }
  105480. this.references = newReferences;
  105481. if (identifyBorders) {
  105482. this.identifyBorder();
  105483. }
  105484. };
  105485. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  105486. var x = point.x;
  105487. var y = point.y;
  105488. var z = point.z;
  105489. 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
  105490. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  105491. };
  105492. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  105493. var q = vertex1.q.add(vertex2.q);
  105494. var border = vertex1.isBorder && vertex2.isBorder;
  105495. var error = 0;
  105496. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  105497. if (qDet !== 0 && !border) {
  105498. if (!pointResult) {
  105499. pointResult = BABYLON.Vector3.Zero();
  105500. }
  105501. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  105502. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  105503. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  105504. error = this.vertexError(q, pointResult);
  105505. }
  105506. else {
  105507. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  105508. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  105509. var error1 = this.vertexError(q, vertex1.position);
  105510. var error2 = this.vertexError(q, vertex2.position);
  105511. var error3 = this.vertexError(q, p3);
  105512. error = Math.min(error1, error2, error3);
  105513. if (error === error1) {
  105514. if (pointResult) {
  105515. pointResult.copyFrom(vertex1.position);
  105516. }
  105517. }
  105518. else if (error === error2) {
  105519. if (pointResult) {
  105520. pointResult.copyFrom(vertex2.position);
  105521. }
  105522. }
  105523. else {
  105524. if (pointResult) {
  105525. pointResult.copyFrom(p3);
  105526. }
  105527. }
  105528. }
  105529. return error;
  105530. };
  105531. return QuadraticErrorSimplification;
  105532. }());
  105533. })(BABYLON || (BABYLON = {}));
  105534. //# sourceMappingURL=babylon.meshSimplification.js.map
  105535. var BABYLON;
  105536. (function (BABYLON) {
  105537. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  105538. get: function () {
  105539. if (!this._simplificationQueue) {
  105540. this._simplificationQueue = new BABYLON.SimplificationQueue();
  105541. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  105542. if (!component) {
  105543. component = new SimplicationQueueSceneComponent(this);
  105544. this._addComponent(component);
  105545. }
  105546. }
  105547. return this._simplificationQueue;
  105548. },
  105549. set: function (value) {
  105550. this._simplificationQueue = value;
  105551. },
  105552. enumerable: true,
  105553. configurable: true
  105554. });
  105555. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  105556. if (parallelProcessing === void 0) { parallelProcessing = true; }
  105557. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  105558. this.getScene().simplificationQueue.addTask({
  105559. settings: settings,
  105560. parallelProcessing: parallelProcessing,
  105561. mesh: this,
  105562. simplificationType: simplificationType,
  105563. successCallback: successCallback
  105564. });
  105565. return this;
  105566. };
  105567. /**
  105568. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  105569. * created in a scene
  105570. */
  105571. var SimplicationQueueSceneComponent = /** @class */ (function () {
  105572. /**
  105573. * Creates a new instance of the component for the given scene
  105574. * @param scene Defines the scene to register the component in
  105575. */
  105576. function SimplicationQueueSceneComponent(scene) {
  105577. /**
  105578. * The component name helpfull to identify the component in the list of scene components.
  105579. */
  105580. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  105581. this.scene = scene;
  105582. }
  105583. /**
  105584. * Registers the component in a given scene
  105585. */
  105586. SimplicationQueueSceneComponent.prototype.register = function () {
  105587. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  105588. };
  105589. /**
  105590. * Rebuilds the elements related to this component in case of
  105591. * context lost for instance.
  105592. */
  105593. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  105594. // Nothing to do for this component
  105595. };
  105596. /**
  105597. * Disposes the component and the associated ressources
  105598. */
  105599. SimplicationQueueSceneComponent.prototype.dispose = function () {
  105600. // Nothing to do for this component
  105601. };
  105602. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  105603. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  105604. this.scene._simplificationQueue.executeNext();
  105605. }
  105606. };
  105607. return SimplicationQueueSceneComponent;
  105608. }());
  105609. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  105610. })(BABYLON || (BABYLON = {}));
  105611. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  105612. var BABYLON;
  105613. (function (BABYLON) {
  105614. /**
  105615. * Class used to represent a specific level of detail of a mesh
  105616. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  105617. */
  105618. var MeshLODLevel = /** @class */ (function () {
  105619. /**
  105620. * Creates a new LOD level
  105621. * @param distance defines the distance where this level should star being displayed
  105622. * @param mesh defines the mesh to use to render this level
  105623. */
  105624. function MeshLODLevel(
  105625. /** Defines the distance where this level should star being displayed */
  105626. distance,
  105627. /** Defines the mesh to use to render this level */
  105628. mesh) {
  105629. this.distance = distance;
  105630. this.mesh = mesh;
  105631. }
  105632. return MeshLODLevel;
  105633. }());
  105634. BABYLON.MeshLODLevel = MeshLODLevel;
  105635. })(BABYLON || (BABYLON = {}));
  105636. //# sourceMappingURL=babylon.meshLODLevel.js.map
  105637. var BABYLON;
  105638. (function (BABYLON) {
  105639. /**
  105640. * Defines the root class used to create scene optimization to use with SceneOptimizer
  105641. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105642. */
  105643. var SceneOptimization = /** @class */ (function () {
  105644. /**
  105645. * Creates the SceneOptimization object
  105646. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105647. * @param desc defines the description associated with the optimization
  105648. */
  105649. function SceneOptimization(
  105650. /**
  105651. * Defines the priority of this optimization (0 by default which means first in the list)
  105652. */
  105653. priority) {
  105654. if (priority === void 0) { priority = 0; }
  105655. this.priority = priority;
  105656. }
  105657. /**
  105658. * Gets a string describing the action executed by the current optimization
  105659. * @returns description string
  105660. */
  105661. SceneOptimization.prototype.getDescription = function () {
  105662. return "";
  105663. };
  105664. /**
  105665. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105666. * @param scene defines the current scene where to apply this optimization
  105667. * @param optimizer defines the current optimizer
  105668. * @returns true if everything that can be done was applied
  105669. */
  105670. SceneOptimization.prototype.apply = function (scene, optimizer) {
  105671. return true;
  105672. };
  105673. ;
  105674. return SceneOptimization;
  105675. }());
  105676. BABYLON.SceneOptimization = SceneOptimization;
  105677. /**
  105678. * Defines an optimization used to reduce the size of render target textures
  105679. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105680. */
  105681. var TextureOptimization = /** @class */ (function (_super) {
  105682. __extends(TextureOptimization, _super);
  105683. /**
  105684. * Creates the TextureOptimization object
  105685. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105686. * @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
  105687. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  105688. */
  105689. function TextureOptimization(
  105690. /**
  105691. * Defines the priority of this optimization (0 by default which means first in the list)
  105692. */
  105693. priority,
  105694. /**
  105695. * 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
  105696. */
  105697. maximumSize,
  105698. /**
  105699. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  105700. */
  105701. step) {
  105702. if (priority === void 0) { priority = 0; }
  105703. if (maximumSize === void 0) { maximumSize = 1024; }
  105704. if (step === void 0) { step = 0.5; }
  105705. var _this = _super.call(this, priority) || this;
  105706. _this.priority = priority;
  105707. _this.maximumSize = maximumSize;
  105708. _this.step = step;
  105709. return _this;
  105710. }
  105711. /**
  105712. * Gets a string describing the action executed by the current optimization
  105713. * @returns description string
  105714. */
  105715. TextureOptimization.prototype.getDescription = function () {
  105716. return "Reducing render target texture size to " + this.maximumSize;
  105717. };
  105718. /**
  105719. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105720. * @param scene defines the current scene where to apply this optimization
  105721. * @param optimizer defines the current optimizer
  105722. * @returns true if everything that can be done was applied
  105723. */
  105724. TextureOptimization.prototype.apply = function (scene, optimizer) {
  105725. var allDone = true;
  105726. for (var index = 0; index < scene.textures.length; index++) {
  105727. var texture = scene.textures[index];
  105728. if (!texture.canRescale || texture.getContext) {
  105729. continue;
  105730. }
  105731. var currentSize = texture.getSize();
  105732. var maxDimension = Math.max(currentSize.width, currentSize.height);
  105733. if (maxDimension > this.maximumSize) {
  105734. texture.scale(this.step);
  105735. allDone = false;
  105736. }
  105737. }
  105738. return allDone;
  105739. };
  105740. return TextureOptimization;
  105741. }(SceneOptimization));
  105742. BABYLON.TextureOptimization = TextureOptimization;
  105743. /**
  105744. * Defines an optimization used to increase or decrease the rendering resolution
  105745. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105746. */
  105747. var HardwareScalingOptimization = /** @class */ (function (_super) {
  105748. __extends(HardwareScalingOptimization, _super);
  105749. /**
  105750. * Creates the HardwareScalingOptimization object
  105751. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105752. * @param maximumScale defines the maximum scale to use (2 by default)
  105753. * @param step defines the step to use between two passes (0.5 by default)
  105754. */
  105755. function HardwareScalingOptimization(
  105756. /**
  105757. * Defines the priority of this optimization (0 by default which means first in the list)
  105758. */
  105759. priority,
  105760. /**
  105761. * Defines the maximum scale to use (2 by default)
  105762. */
  105763. maximumScale,
  105764. /**
  105765. * Defines the step to use between two passes (0.5 by default)
  105766. */
  105767. step) {
  105768. if (priority === void 0) { priority = 0; }
  105769. if (maximumScale === void 0) { maximumScale = 2; }
  105770. if (step === void 0) { step = 0.25; }
  105771. var _this = _super.call(this, priority) || this;
  105772. _this.priority = priority;
  105773. _this.maximumScale = maximumScale;
  105774. _this.step = step;
  105775. _this._currentScale = -1;
  105776. _this._directionOffset = 1;
  105777. return _this;
  105778. }
  105779. /**
  105780. * Gets a string describing the action executed by the current optimization
  105781. * @return description string
  105782. */
  105783. HardwareScalingOptimization.prototype.getDescription = function () {
  105784. return "Setting hardware scaling level to " + this._currentScale;
  105785. };
  105786. /**
  105787. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105788. * @param scene defines the current scene where to apply this optimization
  105789. * @param optimizer defines the current optimizer
  105790. * @returns true if everything that can be done was applied
  105791. */
  105792. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  105793. if (this._currentScale === -1) {
  105794. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  105795. if (this._currentScale > this.maximumScale) {
  105796. this._directionOffset = -1;
  105797. }
  105798. }
  105799. this._currentScale += this._directionOffset * this.step;
  105800. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  105801. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  105802. };
  105803. ;
  105804. return HardwareScalingOptimization;
  105805. }(SceneOptimization));
  105806. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  105807. /**
  105808. * Defines an optimization used to remove shadows
  105809. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105810. */
  105811. var ShadowsOptimization = /** @class */ (function (_super) {
  105812. __extends(ShadowsOptimization, _super);
  105813. function ShadowsOptimization() {
  105814. return _super !== null && _super.apply(this, arguments) || this;
  105815. }
  105816. /**
  105817. * Gets a string describing the action executed by the current optimization
  105818. * @return description string
  105819. */
  105820. ShadowsOptimization.prototype.getDescription = function () {
  105821. return "Turning shadows on/off";
  105822. };
  105823. /**
  105824. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105825. * @param scene defines the current scene where to apply this optimization
  105826. * @param optimizer defines the current optimizer
  105827. * @returns true if everything that can be done was applied
  105828. */
  105829. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  105830. scene.shadowsEnabled = optimizer.isInImprovementMode;
  105831. return true;
  105832. };
  105833. ;
  105834. return ShadowsOptimization;
  105835. }(SceneOptimization));
  105836. BABYLON.ShadowsOptimization = ShadowsOptimization;
  105837. /**
  105838. * Defines an optimization used to turn post-processes off
  105839. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105840. */
  105841. var PostProcessesOptimization = /** @class */ (function (_super) {
  105842. __extends(PostProcessesOptimization, _super);
  105843. function PostProcessesOptimization() {
  105844. return _super !== null && _super.apply(this, arguments) || this;
  105845. }
  105846. /**
  105847. * Gets a string describing the action executed by the current optimization
  105848. * @return description string
  105849. */
  105850. PostProcessesOptimization.prototype.getDescription = function () {
  105851. return "Turning post-processes on/off";
  105852. };
  105853. /**
  105854. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105855. * @param scene defines the current scene where to apply this optimization
  105856. * @param optimizer defines the current optimizer
  105857. * @returns true if everything that can be done was applied
  105858. */
  105859. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  105860. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  105861. return true;
  105862. };
  105863. ;
  105864. return PostProcessesOptimization;
  105865. }(SceneOptimization));
  105866. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  105867. /**
  105868. * Defines an optimization used to turn lens flares off
  105869. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105870. */
  105871. var LensFlaresOptimization = /** @class */ (function (_super) {
  105872. __extends(LensFlaresOptimization, _super);
  105873. function LensFlaresOptimization() {
  105874. return _super !== null && _super.apply(this, arguments) || this;
  105875. }
  105876. /**
  105877. * Gets a string describing the action executed by the current optimization
  105878. * @return description string
  105879. */
  105880. LensFlaresOptimization.prototype.getDescription = function () {
  105881. return "Turning lens flares on/off";
  105882. };
  105883. /**
  105884. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105885. * @param scene defines the current scene where to apply this optimization
  105886. * @param optimizer defines the current optimizer
  105887. * @returns true if everything that can be done was applied
  105888. */
  105889. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  105890. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  105891. return true;
  105892. };
  105893. ;
  105894. return LensFlaresOptimization;
  105895. }(SceneOptimization));
  105896. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  105897. /**
  105898. * Defines an optimization based on user defined callback.
  105899. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105900. */
  105901. var CustomOptimization = /** @class */ (function (_super) {
  105902. __extends(CustomOptimization, _super);
  105903. function CustomOptimization() {
  105904. return _super !== null && _super.apply(this, arguments) || this;
  105905. }
  105906. /**
  105907. * Gets a string describing the action executed by the current optimization
  105908. * @returns description string
  105909. */
  105910. CustomOptimization.prototype.getDescription = function () {
  105911. if (this.onGetDescription) {
  105912. return this.onGetDescription();
  105913. }
  105914. return "Running user defined callback";
  105915. };
  105916. /**
  105917. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105918. * @param scene defines the current scene where to apply this optimization
  105919. * @param optimizer defines the current optimizer
  105920. * @returns true if everything that can be done was applied
  105921. */
  105922. CustomOptimization.prototype.apply = function (scene, optimizer) {
  105923. if (this.onApply) {
  105924. return this.onApply(scene, optimizer);
  105925. }
  105926. return true;
  105927. };
  105928. ;
  105929. return CustomOptimization;
  105930. }(SceneOptimization));
  105931. BABYLON.CustomOptimization = CustomOptimization;
  105932. /**
  105933. * Defines an optimization used to turn particles off
  105934. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105935. */
  105936. var ParticlesOptimization = /** @class */ (function (_super) {
  105937. __extends(ParticlesOptimization, _super);
  105938. function ParticlesOptimization() {
  105939. return _super !== null && _super.apply(this, arguments) || this;
  105940. }
  105941. /**
  105942. * Gets a string describing the action executed by the current optimization
  105943. * @return description string
  105944. */
  105945. ParticlesOptimization.prototype.getDescription = function () {
  105946. return "Turning particles on/off";
  105947. };
  105948. /**
  105949. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105950. * @param scene defines the current scene where to apply this optimization
  105951. * @param optimizer defines the current optimizer
  105952. * @returns true if everything that can be done was applied
  105953. */
  105954. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  105955. scene.particlesEnabled = optimizer.isInImprovementMode;
  105956. return true;
  105957. };
  105958. ;
  105959. return ParticlesOptimization;
  105960. }(SceneOptimization));
  105961. BABYLON.ParticlesOptimization = ParticlesOptimization;
  105962. /**
  105963. * Defines an optimization used to turn render targets off
  105964. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105965. */
  105966. var RenderTargetsOptimization = /** @class */ (function (_super) {
  105967. __extends(RenderTargetsOptimization, _super);
  105968. function RenderTargetsOptimization() {
  105969. return _super !== null && _super.apply(this, arguments) || this;
  105970. }
  105971. /**
  105972. * Gets a string describing the action executed by the current optimization
  105973. * @return description string
  105974. */
  105975. RenderTargetsOptimization.prototype.getDescription = function () {
  105976. return "Turning render targets off";
  105977. };
  105978. /**
  105979. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105980. * @param scene defines the current scene where to apply this optimization
  105981. * @param optimizer defines the current optimizer
  105982. * @returns true if everything that can be done was applied
  105983. */
  105984. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  105985. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  105986. return true;
  105987. };
  105988. ;
  105989. return RenderTargetsOptimization;
  105990. }(SceneOptimization));
  105991. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  105992. /**
  105993. * Defines an optimization used to merge meshes with compatible materials
  105994. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105995. */
  105996. var MergeMeshesOptimization = /** @class */ (function (_super) {
  105997. __extends(MergeMeshesOptimization, _super);
  105998. function MergeMeshesOptimization() {
  105999. var _this = _super !== null && _super.apply(this, arguments) || this;
  106000. _this._canBeMerged = function (abstractMesh) {
  106001. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  106002. return false;
  106003. }
  106004. var mesh = abstractMesh;
  106005. if (mesh.isDisposed()) {
  106006. return false;
  106007. }
  106008. if (!mesh.isVisible || !mesh.isEnabled()) {
  106009. return false;
  106010. }
  106011. if (mesh.instances.length > 0) {
  106012. return false;
  106013. }
  106014. if (mesh.skeleton || mesh.hasLODLevels) {
  106015. return false;
  106016. }
  106017. return true;
  106018. };
  106019. return _this;
  106020. }
  106021. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  106022. /**
  106023. * Gets or sets a boolean which defines if optimization octree has to be updated
  106024. */
  106025. get: function () {
  106026. return MergeMeshesOptimization._UpdateSelectionTree;
  106027. },
  106028. /**
  106029. * Gets or sets a boolean which defines if optimization octree has to be updated
  106030. */
  106031. set: function (value) {
  106032. MergeMeshesOptimization._UpdateSelectionTree = value;
  106033. },
  106034. enumerable: true,
  106035. configurable: true
  106036. });
  106037. /**
  106038. * Gets a string describing the action executed by the current optimization
  106039. * @return description string
  106040. */
  106041. MergeMeshesOptimization.prototype.getDescription = function () {
  106042. return "Merging similar meshes together";
  106043. };
  106044. /**
  106045. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  106046. * @param scene defines the current scene where to apply this optimization
  106047. * @param optimizer defines the current optimizer
  106048. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  106049. * @returns true if everything that can be done was applied
  106050. */
  106051. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  106052. var globalPool = scene.meshes.slice(0);
  106053. var globalLength = globalPool.length;
  106054. for (var index = 0; index < globalLength; index++) {
  106055. var currentPool = new Array();
  106056. var current = globalPool[index];
  106057. // Checks
  106058. if (!this._canBeMerged(current)) {
  106059. continue;
  106060. }
  106061. currentPool.push(current);
  106062. // Find compatible meshes
  106063. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  106064. var otherMesh = globalPool[subIndex];
  106065. if (!this._canBeMerged(otherMesh)) {
  106066. continue;
  106067. }
  106068. if (otherMesh.material !== current.material) {
  106069. continue;
  106070. }
  106071. if (otherMesh.checkCollisions !== current.checkCollisions) {
  106072. continue;
  106073. }
  106074. currentPool.push(otherMesh);
  106075. globalLength--;
  106076. globalPool.splice(subIndex, 1);
  106077. subIndex--;
  106078. }
  106079. if (currentPool.length < 2) {
  106080. continue;
  106081. }
  106082. // Merge meshes
  106083. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  106084. }
  106085. // Call the octree system optimization if it is defined.
  106086. var sceneAsAny = scene;
  106087. if (sceneAsAny.createOrUpdateSelectionOctree) {
  106088. if (updateSelectionTree != undefined) {
  106089. if (updateSelectionTree) {
  106090. sceneAsAny.createOrUpdateSelectionOctree();
  106091. }
  106092. }
  106093. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  106094. sceneAsAny.createOrUpdateSelectionOctree();
  106095. }
  106096. }
  106097. return true;
  106098. };
  106099. ;
  106100. MergeMeshesOptimization._UpdateSelectionTree = false;
  106101. return MergeMeshesOptimization;
  106102. }(SceneOptimization));
  106103. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  106104. /**
  106105. * Defines a list of options used by SceneOptimizer
  106106. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106107. */
  106108. var SceneOptimizerOptions = /** @class */ (function () {
  106109. /**
  106110. * Creates a new list of options used by SceneOptimizer
  106111. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  106112. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  106113. */
  106114. function SceneOptimizerOptions(
  106115. /**
  106116. * Defines the target frame rate to reach (60 by default)
  106117. */
  106118. targetFrameRate,
  106119. /**
  106120. * Defines the interval between two checkes (2000ms by default)
  106121. */
  106122. trackerDuration) {
  106123. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  106124. if (trackerDuration === void 0) { trackerDuration = 2000; }
  106125. this.targetFrameRate = targetFrameRate;
  106126. this.trackerDuration = trackerDuration;
  106127. /**
  106128. * Gets the list of optimizations to apply
  106129. */
  106130. this.optimizations = new Array();
  106131. }
  106132. /**
  106133. * Add a new optimization
  106134. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  106135. * @returns the current SceneOptimizerOptions
  106136. */
  106137. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  106138. this.optimizations.push(optimization);
  106139. return this;
  106140. };
  106141. /**
  106142. * Add a new custom optimization
  106143. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  106144. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  106145. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  106146. * @returns the current SceneOptimizerOptions
  106147. */
  106148. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  106149. if (priority === void 0) { priority = 0; }
  106150. var optimization = new CustomOptimization(priority);
  106151. optimization.onApply = onApply;
  106152. optimization.onGetDescription = onGetDescription;
  106153. this.optimizations.push(optimization);
  106154. return this;
  106155. };
  106156. /**
  106157. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  106158. * @param targetFrameRate defines the target frame rate (60 by default)
  106159. * @returns a SceneOptimizerOptions object
  106160. */
  106161. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  106162. var result = new SceneOptimizerOptions(targetFrameRate);
  106163. var priority = 0;
  106164. result.addOptimization(new MergeMeshesOptimization(priority));
  106165. result.addOptimization(new ShadowsOptimization(priority));
  106166. result.addOptimization(new LensFlaresOptimization(priority));
  106167. // Next priority
  106168. priority++;
  106169. result.addOptimization(new PostProcessesOptimization(priority));
  106170. result.addOptimization(new ParticlesOptimization(priority));
  106171. // Next priority
  106172. priority++;
  106173. result.addOptimization(new TextureOptimization(priority, 1024));
  106174. return result;
  106175. };
  106176. /**
  106177. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  106178. * @param targetFrameRate defines the target frame rate (60 by default)
  106179. * @returns a SceneOptimizerOptions object
  106180. */
  106181. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  106182. var result = new SceneOptimizerOptions(targetFrameRate);
  106183. var priority = 0;
  106184. result.addOptimization(new MergeMeshesOptimization(priority));
  106185. result.addOptimization(new ShadowsOptimization(priority));
  106186. result.addOptimization(new LensFlaresOptimization(priority));
  106187. // Next priority
  106188. priority++;
  106189. result.addOptimization(new PostProcessesOptimization(priority));
  106190. result.addOptimization(new ParticlesOptimization(priority));
  106191. // Next priority
  106192. priority++;
  106193. result.addOptimization(new TextureOptimization(priority, 512));
  106194. // Next priority
  106195. priority++;
  106196. result.addOptimization(new RenderTargetsOptimization(priority));
  106197. // Next priority
  106198. priority++;
  106199. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  106200. return result;
  106201. };
  106202. /**
  106203. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  106204. * @param targetFrameRate defines the target frame rate (60 by default)
  106205. * @returns a SceneOptimizerOptions object
  106206. */
  106207. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  106208. var result = new SceneOptimizerOptions(targetFrameRate);
  106209. var priority = 0;
  106210. result.addOptimization(new MergeMeshesOptimization(priority));
  106211. result.addOptimization(new ShadowsOptimization(priority));
  106212. result.addOptimization(new LensFlaresOptimization(priority));
  106213. // Next priority
  106214. priority++;
  106215. result.addOptimization(new PostProcessesOptimization(priority));
  106216. result.addOptimization(new ParticlesOptimization(priority));
  106217. // Next priority
  106218. priority++;
  106219. result.addOptimization(new TextureOptimization(priority, 256));
  106220. // Next priority
  106221. priority++;
  106222. result.addOptimization(new RenderTargetsOptimization(priority));
  106223. // Next priority
  106224. priority++;
  106225. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  106226. return result;
  106227. };
  106228. return SceneOptimizerOptions;
  106229. }());
  106230. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  106231. /**
  106232. * Class used to run optimizations in order to reach a target frame rate
  106233. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106234. */
  106235. var SceneOptimizer = /** @class */ (function () {
  106236. /**
  106237. * Creates a new SceneOptimizer
  106238. * @param scene defines the scene to work on
  106239. * @param options defines the options to use with the SceneOptimizer
  106240. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  106241. * @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)
  106242. */
  106243. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  106244. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  106245. if (improvementMode === void 0) { improvementMode = false; }
  106246. var _this = this;
  106247. this._isRunning = false;
  106248. this._currentPriorityLevel = 0;
  106249. this._targetFrameRate = 60;
  106250. this._trackerDuration = 2000;
  106251. this._currentFrameRate = 0;
  106252. this._improvementMode = false;
  106253. /**
  106254. * Defines an observable called when the optimizer reaches the target frame rate
  106255. */
  106256. this.onSuccessObservable = new BABYLON.Observable();
  106257. /**
  106258. * Defines an observable called when the optimizer enables an optimization
  106259. */
  106260. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  106261. /**
  106262. * Defines an observable called when the optimizer is not able to reach the target frame rate
  106263. */
  106264. this.onFailureObservable = new BABYLON.Observable();
  106265. if (!options) {
  106266. this._options = new SceneOptimizerOptions();
  106267. }
  106268. else {
  106269. this._options = options;
  106270. }
  106271. if (this._options.targetFrameRate) {
  106272. this._targetFrameRate = this._options.targetFrameRate;
  106273. }
  106274. if (this._options.trackerDuration) {
  106275. this._trackerDuration = this._options.trackerDuration;
  106276. }
  106277. if (autoGeneratePriorities) {
  106278. var priority = 0;
  106279. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  106280. var optim = _a[_i];
  106281. optim.priority = priority++;
  106282. }
  106283. }
  106284. this._improvementMode = improvementMode;
  106285. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  106286. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  106287. _this._sceneDisposeObserver = null;
  106288. _this.dispose();
  106289. });
  106290. }
  106291. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  106292. /**
  106293. * Gets a boolean indicating if the optimizer is in improvement mode
  106294. */
  106295. get: function () {
  106296. return this._improvementMode;
  106297. },
  106298. enumerable: true,
  106299. configurable: true
  106300. });
  106301. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  106302. /**
  106303. * Gets the current priority level (0 at start)
  106304. */
  106305. get: function () {
  106306. return this._currentPriorityLevel;
  106307. },
  106308. enumerable: true,
  106309. configurable: true
  106310. });
  106311. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  106312. /**
  106313. * Gets the current frame rate checked by the SceneOptimizer
  106314. */
  106315. get: function () {
  106316. return this._currentFrameRate;
  106317. },
  106318. enumerable: true,
  106319. configurable: true
  106320. });
  106321. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  106322. /**
  106323. * Gets or sets the current target frame rate (60 by default)
  106324. */
  106325. get: function () {
  106326. return this._targetFrameRate;
  106327. },
  106328. /**
  106329. * Gets or sets the current target frame rate (60 by default)
  106330. */
  106331. set: function (value) {
  106332. this._targetFrameRate = value;
  106333. },
  106334. enumerable: true,
  106335. configurable: true
  106336. });
  106337. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  106338. /**
  106339. * Gets or sets the current interval between two checks (every 2000ms by default)
  106340. */
  106341. get: function () {
  106342. return this._trackerDuration;
  106343. },
  106344. /**
  106345. * Gets or sets the current interval between two checks (every 2000ms by default)
  106346. */
  106347. set: function (value) {
  106348. this._trackerDuration = value;
  106349. },
  106350. enumerable: true,
  106351. configurable: true
  106352. });
  106353. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  106354. /**
  106355. * Gets the list of active optimizations
  106356. */
  106357. get: function () {
  106358. return this._options.optimizations;
  106359. },
  106360. enumerable: true,
  106361. configurable: true
  106362. });
  106363. /**
  106364. * Stops the current optimizer
  106365. */
  106366. SceneOptimizer.prototype.stop = function () {
  106367. this._isRunning = false;
  106368. };
  106369. /**
  106370. * Reset the optimizer to initial step (current priority level = 0)
  106371. */
  106372. SceneOptimizer.prototype.reset = function () {
  106373. this._currentPriorityLevel = 0;
  106374. };
  106375. /**
  106376. * Start the optimizer. By default it will try to reach a specific framerate
  106377. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  106378. */
  106379. SceneOptimizer.prototype.start = function () {
  106380. var _this = this;
  106381. if (this._isRunning) {
  106382. return;
  106383. }
  106384. this._isRunning = true;
  106385. // Let's wait for the scene to be ready before running our check
  106386. this._scene.executeWhenReady(function () {
  106387. setTimeout(function () {
  106388. _this._checkCurrentState();
  106389. }, _this._trackerDuration);
  106390. });
  106391. };
  106392. SceneOptimizer.prototype._checkCurrentState = function () {
  106393. var _this = this;
  106394. if (!this._isRunning) {
  106395. return;
  106396. }
  106397. var scene = this._scene;
  106398. var options = this._options;
  106399. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  106400. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  106401. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  106402. this._isRunning = false;
  106403. this.onSuccessObservable.notifyObservers(this);
  106404. return;
  106405. }
  106406. // Apply current level of optimizations
  106407. var allDone = true;
  106408. var noOptimizationApplied = true;
  106409. for (var index = 0; index < options.optimizations.length; index++) {
  106410. var optimization = options.optimizations[index];
  106411. if (optimization.priority === this._currentPriorityLevel) {
  106412. noOptimizationApplied = false;
  106413. allDone = allDone && optimization.apply(scene, this);
  106414. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  106415. }
  106416. }
  106417. // If no optimization was applied, this is a failure :(
  106418. if (noOptimizationApplied) {
  106419. this._isRunning = false;
  106420. this.onFailureObservable.notifyObservers(this);
  106421. return;
  106422. }
  106423. // If all optimizations were done, move to next level
  106424. if (allDone) {
  106425. this._currentPriorityLevel++;
  106426. }
  106427. // Let's the system running for a specific amount of time before checking FPS
  106428. scene.executeWhenReady(function () {
  106429. setTimeout(function () {
  106430. _this._checkCurrentState();
  106431. }, _this._trackerDuration);
  106432. });
  106433. };
  106434. /**
  106435. * Release all resources
  106436. */
  106437. SceneOptimizer.prototype.dispose = function () {
  106438. this.stop();
  106439. this.onSuccessObservable.clear();
  106440. this.onFailureObservable.clear();
  106441. this.onNewOptimizationAppliedObservable.clear();
  106442. if (this._sceneDisposeObserver) {
  106443. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  106444. }
  106445. };
  106446. /**
  106447. * Helper function to create a SceneOptimizer with one single line of code
  106448. * @param scene defines the scene to work on
  106449. * @param options defines the options to use with the SceneOptimizer
  106450. * @param onSuccess defines a callback to call on success
  106451. * @param onFailure defines a callback to call on failure
  106452. * @returns the new SceneOptimizer object
  106453. */
  106454. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  106455. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  106456. if (onSuccess) {
  106457. optimizer.onSuccessObservable.add(function () {
  106458. onSuccess();
  106459. });
  106460. }
  106461. if (onFailure) {
  106462. optimizer.onFailureObservable.add(function () {
  106463. onFailure();
  106464. });
  106465. }
  106466. optimizer.start();
  106467. return optimizer;
  106468. };
  106469. return SceneOptimizer;
  106470. }());
  106471. BABYLON.SceneOptimizer = SceneOptimizer;
  106472. })(BABYLON || (BABYLON = {}));
  106473. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  106474. var BABYLON;
  106475. (function (BABYLON) {
  106476. /**
  106477. * Gets the outline renderer associated with the scene
  106478. * @returns a OutlineRenderer
  106479. */
  106480. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  106481. if (!this._outlineRenderer) {
  106482. this._outlineRenderer = new OutlineRenderer(this);
  106483. }
  106484. return this._outlineRenderer;
  106485. };
  106486. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  106487. get: function () {
  106488. return this._renderOutline;
  106489. },
  106490. set: function (value) {
  106491. if (value) {
  106492. // Lazy Load the component.
  106493. this.getScene().getOutlineRenderer();
  106494. }
  106495. this._renderOutline = value;
  106496. },
  106497. enumerable: true,
  106498. configurable: true
  106499. });
  106500. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  106501. get: function () {
  106502. return this._renderOverlay;
  106503. },
  106504. set: function (value) {
  106505. if (value) {
  106506. // Lazy Load the component.
  106507. this.getScene().getOutlineRenderer();
  106508. }
  106509. this._renderOverlay = value;
  106510. },
  106511. enumerable: true,
  106512. configurable: true
  106513. });
  106514. /**
  106515. * This class is responsible to draw bothe outline/overlay of meshes.
  106516. * It should not be used directly but through the available method on mesh.
  106517. */
  106518. var OutlineRenderer = /** @class */ (function () {
  106519. /**
  106520. * Instantiates a new outline renderer. (There could be only one per scene).
  106521. * @param scene Defines the scene it belongs to
  106522. */
  106523. function OutlineRenderer(scene) {
  106524. /**
  106525. * The name of the component. Each component must have a unique name.
  106526. */
  106527. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  106528. /**
  106529. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  106530. */
  106531. this.zOffset = 1;
  106532. this.scene = scene;
  106533. this._engine = scene.getEngine();
  106534. this.scene._addComponent(this);
  106535. }
  106536. /**
  106537. * Register the component to one instance of a scene.
  106538. */
  106539. OutlineRenderer.prototype.register = function () {
  106540. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  106541. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  106542. };
  106543. /**
  106544. * Rebuilds the elements related to this component in case of
  106545. * context lost for instance.
  106546. */
  106547. OutlineRenderer.prototype.rebuild = function () {
  106548. // Nothing to do here.
  106549. };
  106550. /**
  106551. * Disposes the component and the associated ressources.
  106552. */
  106553. OutlineRenderer.prototype.dispose = function () {
  106554. // Nothing to do here.
  106555. };
  106556. /**
  106557. * Renders the outline in the canvas.
  106558. * @param subMesh Defines the sumesh to render
  106559. * @param batch Defines the batch of meshes in case of instances
  106560. * @param useOverlay Defines if the rendering is for the overlay or the outline
  106561. */
  106562. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  106563. var _this = this;
  106564. if (useOverlay === void 0) { useOverlay = false; }
  106565. var scene = this.scene;
  106566. var engine = scene.getEngine();
  106567. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  106568. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  106569. return;
  106570. }
  106571. var mesh = subMesh.getRenderingMesh();
  106572. var material = subMesh.getMaterial();
  106573. if (!material || !scene.activeCamera) {
  106574. return;
  106575. }
  106576. engine.enableEffect(this._effect);
  106577. // Logarithmic depth
  106578. if (material.useLogarithmicDepth) {
  106579. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  106580. }
  106581. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  106582. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  106583. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  106584. // Bones
  106585. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  106586. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  106587. }
  106588. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  106589. // Alpha test
  106590. if (material && material.needAlphaTesting()) {
  106591. var alphaTexture = material.getAlphaTestTexture();
  106592. if (alphaTexture) {
  106593. this._effect.setTexture("diffuseSampler", alphaTexture);
  106594. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  106595. }
  106596. }
  106597. engine.setZOffset(-this.zOffset);
  106598. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  106599. engine.setZOffset(0);
  106600. };
  106601. /**
  106602. * Returns whether or not the outline renderer is ready for a given submesh.
  106603. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  106604. * @param subMesh Defines the submesh to check readyness for
  106605. * @param useInstances Defines wheter wee are trying to render instances or not
  106606. * @returns true if ready otherwise false
  106607. */
  106608. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  106609. var defines = [];
  106610. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  106611. var mesh = subMesh.getMesh();
  106612. var material = subMesh.getMaterial();
  106613. if (material) {
  106614. // Alpha test
  106615. if (material.needAlphaTesting()) {
  106616. defines.push("#define ALPHATEST");
  106617. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  106618. attribs.push(BABYLON.VertexBuffer.UVKind);
  106619. defines.push("#define UV1");
  106620. }
  106621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  106622. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  106623. defines.push("#define UV2");
  106624. }
  106625. }
  106626. //Logarithmic depth
  106627. if (material.useLogarithmicDepth) {
  106628. defines.push("#define LOGARITHMICDEPTH");
  106629. }
  106630. }
  106631. // Bones
  106632. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  106633. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  106634. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  106635. if (mesh.numBoneInfluencers > 4) {
  106636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  106637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  106638. }
  106639. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  106640. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  106641. }
  106642. else {
  106643. defines.push("#define NUM_BONE_INFLUENCERS 0");
  106644. }
  106645. // Instances
  106646. if (useInstances) {
  106647. defines.push("#define INSTANCES");
  106648. attribs.push("world0");
  106649. attribs.push("world1");
  106650. attribs.push("world2");
  106651. attribs.push("world3");
  106652. }
  106653. // Get correct effect
  106654. var join = defines.join("\n");
  106655. if (this._cachedDefines !== join) {
  106656. this._cachedDefines = join;
  106657. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  106658. }
  106659. return this._effect.isReady();
  106660. };
  106661. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  106662. // Outline - step 1
  106663. this._savedDepthWrite = this._engine.getDepthWrite();
  106664. if (mesh.renderOutline) {
  106665. this._engine.setDepthWrite(false);
  106666. this.render(subMesh, batch);
  106667. this._engine.setDepthWrite(this._savedDepthWrite);
  106668. }
  106669. };
  106670. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  106671. // Outline - step 2
  106672. if (mesh.renderOutline && this._savedDepthWrite) {
  106673. this._engine.setDepthWrite(true);
  106674. this._engine.setColorWrite(false);
  106675. this.render(subMesh, batch);
  106676. this._engine.setColorWrite(true);
  106677. }
  106678. // Overlay
  106679. if (mesh.renderOverlay) {
  106680. var currentMode = this._engine.getAlphaMode();
  106681. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  106682. this.render(subMesh, batch, true);
  106683. this._engine.setAlphaMode(currentMode);
  106684. }
  106685. };
  106686. return OutlineRenderer;
  106687. }());
  106688. BABYLON.OutlineRenderer = OutlineRenderer;
  106689. })(BABYLON || (BABYLON = {}));
  106690. //# sourceMappingURL=babylon.outlineRenderer.js.map
  106691. var BABYLON;
  106692. (function (BABYLON) {
  106693. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  106694. if (this._edgesRenderer) {
  106695. this._edgesRenderer.dispose();
  106696. this._edgesRenderer = null;
  106697. }
  106698. return this;
  106699. };
  106700. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  106701. if (epsilon === void 0) { epsilon = 0.95; }
  106702. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106703. this.disableEdgesRendering();
  106704. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  106705. return this;
  106706. };
  106707. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  106708. get: function () {
  106709. return this._edgesRenderer;
  106710. },
  106711. enumerable: true,
  106712. configurable: true
  106713. });
  106714. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  106715. if (epsilon === void 0) { epsilon = 0.95; }
  106716. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106717. this.disableEdgesRendering();
  106718. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  106719. return this;
  106720. };
  106721. /**
  106722. * FaceAdjacencies Helper class to generate edges
  106723. */
  106724. var FaceAdjacencies = /** @class */ (function () {
  106725. function FaceAdjacencies() {
  106726. this.edges = new Array();
  106727. this.edgesConnectedCount = 0;
  106728. }
  106729. return FaceAdjacencies;
  106730. }());
  106731. /**
  106732. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  106733. */
  106734. var EdgesRenderer = /** @class */ (function () {
  106735. /**
  106736. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  106737. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  106738. * @param source Mesh used to create edges
  106739. * @param epsilon sum of angles in adjacency to check for edge
  106740. * @param checkVerticesInsteadOfIndices
  106741. * @param generateEdgesLines - should generate Lines or only prepare resources.
  106742. */
  106743. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  106744. if (epsilon === void 0) { epsilon = 0.95; }
  106745. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106746. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  106747. var _this = this;
  106748. /**
  106749. * Define the size of the edges with an orthographic camera
  106750. */
  106751. this.edgesWidthScalerForOrthographic = 1000.0;
  106752. /**
  106753. * Define the size of the edges with a perspective camera
  106754. */
  106755. this.edgesWidthScalerForPerspective = 50.0;
  106756. this._linesPositions = new Array();
  106757. this._linesNormals = new Array();
  106758. this._linesIndices = new Array();
  106759. this._buffers = {};
  106760. this._checkVerticesInsteadOfIndices = false;
  106761. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  106762. this.isEnabled = true;
  106763. this._source = source;
  106764. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  106765. this._epsilon = epsilon;
  106766. this._prepareRessources();
  106767. if (generateEdgesLines) {
  106768. this._generateEdgesLines();
  106769. }
  106770. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  106771. _this._rebuild();
  106772. });
  106773. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  106774. _this.dispose();
  106775. });
  106776. }
  106777. EdgesRenderer.prototype._prepareRessources = function () {
  106778. if (this._lineShader) {
  106779. return;
  106780. }
  106781. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  106782. attributes: ["position", "normal"],
  106783. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  106784. });
  106785. this._lineShader.disableDepthWrite = true;
  106786. this._lineShader.backFaceCulling = false;
  106787. };
  106788. /** @hidden */
  106789. EdgesRenderer.prototype._rebuild = function () {
  106790. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  106791. if (buffer) {
  106792. buffer._rebuild();
  106793. }
  106794. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  106795. if (buffer) {
  106796. buffer._rebuild();
  106797. }
  106798. var scene = this._source.getScene();
  106799. var engine = scene.getEngine();
  106800. this._ib = engine.createIndexBuffer(this._linesIndices);
  106801. };
  106802. /**
  106803. * Releases the required resources for the edges renderer
  106804. */
  106805. EdgesRenderer.prototype.dispose = function () {
  106806. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  106807. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  106808. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  106809. if (buffer) {
  106810. buffer.dispose();
  106811. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  106812. }
  106813. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  106814. if (buffer) {
  106815. buffer.dispose();
  106816. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  106817. }
  106818. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  106819. this._lineShader.dispose();
  106820. };
  106821. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  106822. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  106823. return 0;
  106824. }
  106825. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  106826. return 1;
  106827. }
  106828. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  106829. return 2;
  106830. }
  106831. return -1;
  106832. };
  106833. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  106834. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  106835. return 0;
  106836. }
  106837. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  106838. return 1;
  106839. }
  106840. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  106841. return 2;
  106842. }
  106843. return -1;
  106844. };
  106845. /**
  106846. * Checks if the pair of p0 and p1 is en edge
  106847. * @param faceIndex
  106848. * @param edge
  106849. * @param faceNormals
  106850. * @param p0
  106851. * @param p1
  106852. * @private
  106853. */
  106854. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  106855. var needToCreateLine;
  106856. if (edge === undefined) {
  106857. needToCreateLine = true;
  106858. }
  106859. else {
  106860. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  106861. needToCreateLine = dotProduct < this._epsilon;
  106862. }
  106863. if (needToCreateLine) {
  106864. var offset = this._linesPositions.length / 3;
  106865. var normal = p0.subtract(p1);
  106866. normal.normalize();
  106867. // Positions
  106868. this._linesPositions.push(p0.x);
  106869. this._linesPositions.push(p0.y);
  106870. this._linesPositions.push(p0.z);
  106871. this._linesPositions.push(p0.x);
  106872. this._linesPositions.push(p0.y);
  106873. this._linesPositions.push(p0.z);
  106874. this._linesPositions.push(p1.x);
  106875. this._linesPositions.push(p1.y);
  106876. this._linesPositions.push(p1.z);
  106877. this._linesPositions.push(p1.x);
  106878. this._linesPositions.push(p1.y);
  106879. this._linesPositions.push(p1.z);
  106880. // Normals
  106881. this._linesNormals.push(p1.x);
  106882. this._linesNormals.push(p1.y);
  106883. this._linesNormals.push(p1.z);
  106884. this._linesNormals.push(-1);
  106885. this._linesNormals.push(p1.x);
  106886. this._linesNormals.push(p1.y);
  106887. this._linesNormals.push(p1.z);
  106888. this._linesNormals.push(1);
  106889. this._linesNormals.push(p0.x);
  106890. this._linesNormals.push(p0.y);
  106891. this._linesNormals.push(p0.z);
  106892. this._linesNormals.push(-1);
  106893. this._linesNormals.push(p0.x);
  106894. this._linesNormals.push(p0.y);
  106895. this._linesNormals.push(p0.z);
  106896. this._linesNormals.push(1);
  106897. // Indices
  106898. this._linesIndices.push(offset);
  106899. this._linesIndices.push(offset + 1);
  106900. this._linesIndices.push(offset + 2);
  106901. this._linesIndices.push(offset);
  106902. this._linesIndices.push(offset + 2);
  106903. this._linesIndices.push(offset + 3);
  106904. }
  106905. };
  106906. /**
  106907. * Generates lines edges from adjacencjes
  106908. * @private
  106909. */
  106910. EdgesRenderer.prototype._generateEdgesLines = function () {
  106911. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106912. var indices = this._source.getIndices();
  106913. if (!indices || !positions) {
  106914. return;
  106915. }
  106916. // First let's find adjacencies
  106917. var adjacencies = new Array();
  106918. var faceNormals = new Array();
  106919. var index;
  106920. var faceAdjacencies;
  106921. // Prepare faces
  106922. for (index = 0; index < indices.length; index += 3) {
  106923. faceAdjacencies = new FaceAdjacencies();
  106924. var p0Index = indices[index];
  106925. var p1Index = indices[index + 1];
  106926. var p2Index = indices[index + 2];
  106927. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  106928. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  106929. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  106930. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  106931. faceNormal.normalize();
  106932. faceNormals.push(faceNormal);
  106933. adjacencies.push(faceAdjacencies);
  106934. }
  106935. // Scan
  106936. for (index = 0; index < adjacencies.length; index++) {
  106937. faceAdjacencies = adjacencies[index];
  106938. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  106939. var otherFaceAdjacencies = adjacencies[otherIndex];
  106940. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  106941. break;
  106942. }
  106943. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  106944. continue;
  106945. }
  106946. var otherP0 = indices[otherIndex * 3];
  106947. var otherP1 = indices[otherIndex * 3 + 1];
  106948. var otherP2 = indices[otherIndex * 3 + 2];
  106949. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  106950. var otherEdgeIndex = 0;
  106951. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  106952. continue;
  106953. }
  106954. switch (edgeIndex) {
  106955. case 0:
  106956. if (this._checkVerticesInsteadOfIndices) {
  106957. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106958. }
  106959. else {
  106960. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  106961. }
  106962. break;
  106963. case 1:
  106964. if (this._checkVerticesInsteadOfIndices) {
  106965. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106966. }
  106967. else {
  106968. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  106969. }
  106970. break;
  106971. case 2:
  106972. if (this._checkVerticesInsteadOfIndices) {
  106973. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106974. }
  106975. else {
  106976. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  106977. }
  106978. break;
  106979. }
  106980. if (otherEdgeIndex === -1) {
  106981. continue;
  106982. }
  106983. faceAdjacencies.edges[edgeIndex] = otherIndex;
  106984. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  106985. faceAdjacencies.edgesConnectedCount++;
  106986. otherFaceAdjacencies.edgesConnectedCount++;
  106987. if (faceAdjacencies.edgesConnectedCount === 3) {
  106988. break;
  106989. }
  106990. }
  106991. }
  106992. }
  106993. // Create lines
  106994. for (index = 0; index < adjacencies.length; index++) {
  106995. // 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
  106996. var current = adjacencies[index];
  106997. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  106998. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  106999. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  107000. }
  107001. // Merge into a single mesh
  107002. var engine = this._source.getScene().getEngine();
  107003. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  107004. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  107005. this._ib = engine.createIndexBuffer(this._linesIndices);
  107006. this._indicesCount = this._linesIndices.length;
  107007. };
  107008. /**
  107009. * Checks wether or not the edges renderer is ready to render.
  107010. * @return true if ready, otherwise false.
  107011. */
  107012. EdgesRenderer.prototype.isReady = function () {
  107013. return this._lineShader.isReady();
  107014. };
  107015. /**
  107016. * Renders the edges of the attached mesh,
  107017. */
  107018. EdgesRenderer.prototype.render = function () {
  107019. var scene = this._source.getScene();
  107020. if (!this.isReady() || !scene.activeCamera) {
  107021. return;
  107022. }
  107023. var engine = scene.getEngine();
  107024. this._lineShader._preBind();
  107025. if (this._source.edgesColor.a !== 1) {
  107026. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  107027. }
  107028. else {
  107029. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  107030. }
  107031. // VBOs
  107032. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  107033. scene.resetCachedMaterial();
  107034. this._lineShader.setColor4("color", this._source.edgesColor);
  107035. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  107036. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  107037. }
  107038. else {
  107039. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  107040. }
  107041. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  107042. this._lineShader.bind(this._source.getWorldMatrix());
  107043. // Draw order
  107044. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  107045. this._lineShader.unbind();
  107046. };
  107047. return EdgesRenderer;
  107048. }());
  107049. BABYLON.EdgesRenderer = EdgesRenderer;
  107050. })(BABYLON || (BABYLON = {}));
  107051. //# sourceMappingURL=babylon.edgesRenderer.js.map
  107052. var BABYLON;
  107053. (function (BABYLON) {
  107054. /**
  107055. * FaceAdjacencies Helper class to generate edges
  107056. */
  107057. var FaceAdjacencies = /** @class */ (function () {
  107058. function FaceAdjacencies() {
  107059. this.edges = new Array();
  107060. this.edgesConnectedCount = 0;
  107061. }
  107062. return FaceAdjacencies;
  107063. }());
  107064. /**
  107065. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  107066. */
  107067. var LineEdgesRenderer = /** @class */ (function (_super) {
  107068. __extends(LineEdgesRenderer, _super);
  107069. /**
  107070. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  107071. * @param source LineMesh used to generate edges
  107072. * @param epsilon not important (specified angle for edge detection)
  107073. * @param checkVerticesInsteadOfIndices not important for LineMesh
  107074. */
  107075. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  107076. if (epsilon === void 0) { epsilon = 0.95; }
  107077. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  107078. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  107079. _this._generateEdgesLines();
  107080. return _this;
  107081. }
  107082. /**
  107083. * Always create the edge since its a line so only important things are p0 and p1
  107084. * @param faceIndex not important for LineMesh
  107085. * @param edge not important for LineMesh
  107086. * @param faceNormals not important for LineMesh
  107087. * @param p0 beginnig of line
  107088. * @param p1 end of line
  107089. */
  107090. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  107091. var offset = this._linesPositions.length / 3;
  107092. var normal = p0.subtract(p1);
  107093. normal.normalize();
  107094. // Positions
  107095. this._linesPositions.push(p0.x);
  107096. this._linesPositions.push(p0.y);
  107097. this._linesPositions.push(p0.z);
  107098. this._linesPositions.push(p0.x);
  107099. this._linesPositions.push(p0.y);
  107100. this._linesPositions.push(p0.z);
  107101. this._linesPositions.push(p1.x);
  107102. this._linesPositions.push(p1.y);
  107103. this._linesPositions.push(p1.z);
  107104. this._linesPositions.push(p1.x);
  107105. this._linesPositions.push(p1.y);
  107106. this._linesPositions.push(p1.z);
  107107. // Normals
  107108. this._linesNormals.push(p1.x);
  107109. this._linesNormals.push(p1.y);
  107110. this._linesNormals.push(p1.z);
  107111. this._linesNormals.push(-1);
  107112. this._linesNormals.push(p1.x);
  107113. this._linesNormals.push(p1.y);
  107114. this._linesNormals.push(p1.z);
  107115. this._linesNormals.push(1);
  107116. this._linesNormals.push(p0.x);
  107117. this._linesNormals.push(p0.y);
  107118. this._linesNormals.push(p0.z);
  107119. this._linesNormals.push(-1);
  107120. this._linesNormals.push(p0.x);
  107121. this._linesNormals.push(p0.y);
  107122. this._linesNormals.push(p0.z);
  107123. this._linesNormals.push(1);
  107124. // Indices
  107125. this._linesIndices.push(offset);
  107126. this._linesIndices.push(offset + 1);
  107127. this._linesIndices.push(offset + 2);
  107128. this._linesIndices.push(offset);
  107129. this._linesIndices.push(offset + 2);
  107130. this._linesIndices.push(offset + 3);
  107131. };
  107132. /**
  107133. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  107134. */
  107135. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  107136. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  107137. var indices = this._source.getIndices();
  107138. if (!indices || !positions) {
  107139. return;
  107140. }
  107141. // First let's find adjacencies
  107142. var adjacencies = new Array();
  107143. var faceNormals = new Array();
  107144. var index;
  107145. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  107146. var currentAdjecancy = new FaceAdjacencies();
  107147. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  107148. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  107149. adjacencies.push(currentAdjecancy);
  107150. }
  107151. // Create lines
  107152. for (index = 0; index < adjacencies.length; index++) {
  107153. // 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
  107154. var current = adjacencies[index];
  107155. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  107156. }
  107157. // Merge into a single mesh
  107158. var engine = this._source.getScene().getEngine();
  107159. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  107160. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  107161. this._ib = engine.createIndexBuffer(this._linesIndices);
  107162. this._indicesCount = this._linesIndices.length;
  107163. };
  107164. return LineEdgesRenderer;
  107165. }(BABYLON.EdgesRenderer));
  107166. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  107167. })(BABYLON || (BABYLON = {}));
  107168. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  107169. var BABYLON;
  107170. (function (BABYLON) {
  107171. // Adds the parser to the scene parsers.
  107172. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  107173. if (parsedData.effectLayers) {
  107174. if (!container.effectLayers) {
  107175. container.effectLayers = new Array();
  107176. }
  107177. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  107178. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  107179. container.effectLayers.push(effectLayer);
  107180. }
  107181. }
  107182. });
  107183. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  107184. var index = this.effectLayers.indexOf(toRemove);
  107185. if (index !== -1) {
  107186. this.effectLayers.splice(index, 1);
  107187. }
  107188. return index;
  107189. };
  107190. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  107191. this.effectLayers.push(newEffectLayer);
  107192. };
  107193. /**
  107194. * Defines the layer scene component responsible to manage any effect layers
  107195. * in a given scene.
  107196. */
  107197. var EffectLayerSceneComponent = /** @class */ (function () {
  107198. /**
  107199. * Creates a new instance of the component for the given scene
  107200. * @param scene Defines the scene to register the component in
  107201. */
  107202. function EffectLayerSceneComponent(scene) {
  107203. /**
  107204. * The component name helpfull to identify the component in the list of scene components.
  107205. */
  107206. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  107207. this._renderEffects = false;
  107208. this._needStencil = false;
  107209. this._previousStencilState = false;
  107210. this.scene = scene;
  107211. this._engine = scene.getEngine();
  107212. scene.effectLayers = new Array();
  107213. }
  107214. /**
  107215. * Registers the component in a given scene
  107216. */
  107217. EffectLayerSceneComponent.prototype.register = function () {
  107218. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  107219. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  107220. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  107221. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  107222. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  107223. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  107224. };
  107225. /**
  107226. * Rebuilds the elements related to this component in case of
  107227. * context lost for instance.
  107228. */
  107229. EffectLayerSceneComponent.prototype.rebuild = function () {
  107230. var layers = this.scene.effectLayers;
  107231. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107232. var effectLayer = layers_1[_i];
  107233. effectLayer._rebuild();
  107234. }
  107235. };
  107236. /**
  107237. * Serializes the component data to the specified json object
  107238. * @param serializationObject The object to serialize to
  107239. */
  107240. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  107241. // Effect layers
  107242. serializationObject.effectLayers = [];
  107243. var layers = this.scene.effectLayers;
  107244. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107245. var effectLayer = layers_2[_i];
  107246. if (effectLayer.serialize) {
  107247. serializationObject.effectLayers.push(effectLayer.serialize());
  107248. }
  107249. }
  107250. };
  107251. /**
  107252. * Adds all the element from the container to the scene
  107253. * @param container the container holding the elements
  107254. */
  107255. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  107256. var _this = this;
  107257. if (!container.effectLayers) {
  107258. return;
  107259. }
  107260. container.effectLayers.forEach(function (o) {
  107261. _this.scene.addEffectLayer(o);
  107262. });
  107263. };
  107264. /**
  107265. * Removes all the elements in the container from the scene
  107266. * @param container contains the elements to remove
  107267. */
  107268. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  107269. var _this = this;
  107270. if (!container.effectLayers) {
  107271. return;
  107272. }
  107273. container.effectLayers.forEach(function (o) {
  107274. _this.scene.removeEffectLayer(o);
  107275. });
  107276. };
  107277. /**
  107278. * Disposes the component and the associated ressources.
  107279. */
  107280. EffectLayerSceneComponent.prototype.dispose = function () {
  107281. var layers = this.scene.effectLayers;
  107282. while (layers.length) {
  107283. layers[0].dispose();
  107284. }
  107285. };
  107286. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  107287. var layers = this.scene.effectLayers;
  107288. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  107289. var layer = layers_3[_i];
  107290. if (!layer.hasMesh(mesh)) {
  107291. continue;
  107292. }
  107293. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  107294. var subMesh = _b[_a];
  107295. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  107296. return false;
  107297. }
  107298. }
  107299. }
  107300. return true;
  107301. };
  107302. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  107303. this._renderEffects = false;
  107304. this._needStencil = false;
  107305. var layers = this.scene.effectLayers;
  107306. if (layers && layers.length > 0) {
  107307. this._previousStencilState = this._engine.getStencilBuffer();
  107308. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  107309. var effectLayer = layers_4[_i];
  107310. if (effectLayer.shouldRender() &&
  107311. (!effectLayer.camera ||
  107312. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  107313. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  107314. this._renderEffects = true;
  107315. this._needStencil = this._needStencil || effectLayer.needStencil();
  107316. var renderTarget = effectLayer._mainTexture;
  107317. if (renderTarget._shouldRender()) {
  107318. this.scene.incrementRenderId();
  107319. renderTarget.render(false, false);
  107320. }
  107321. }
  107322. }
  107323. this.scene.incrementRenderId();
  107324. }
  107325. };
  107326. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  107327. // Activate effect Layer stencil
  107328. if (this._needStencil) {
  107329. this._engine.setStencilBuffer(true);
  107330. }
  107331. };
  107332. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  107333. // Restore effect Layer stencil
  107334. if (this._needStencil) {
  107335. this._engine.setStencilBuffer(this._previousStencilState);
  107336. }
  107337. };
  107338. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  107339. if (this._renderEffects) {
  107340. this._engine.setDepthBuffer(false);
  107341. var layers = this.scene.effectLayers;
  107342. for (var i = 0; i < layers.length; i++) {
  107343. var effectLayer = layers[i];
  107344. if (effectLayer.renderingGroupId === renderingGroupId) {
  107345. if (effectLayer.shouldRender()) {
  107346. effectLayer.render();
  107347. }
  107348. }
  107349. }
  107350. this._engine.setDepthBuffer(true);
  107351. }
  107352. };
  107353. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  107354. if (this._renderEffects) {
  107355. this._draw(-1);
  107356. }
  107357. };
  107358. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  107359. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  107360. this._draw(index);
  107361. }
  107362. };
  107363. return EffectLayerSceneComponent;
  107364. }());
  107365. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  107366. })(BABYLON || (BABYLON = {}));
  107367. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  107368. var __assign = (this && this.__assign) || function () {
  107369. __assign = Object.assign || function(t) {
  107370. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107371. s = arguments[i];
  107372. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107373. t[p] = s[p];
  107374. }
  107375. return t;
  107376. };
  107377. return __assign.apply(this, arguments);
  107378. };
  107379. var BABYLON;
  107380. (function (BABYLON) {
  107381. /**
  107382. * The effect layer Helps adding post process effect blended with the main pass.
  107383. *
  107384. * This can be for instance use to generate glow or higlight effects on the scene.
  107385. *
  107386. * The effect layer class can not be used directly and is intented to inherited from to be
  107387. * customized per effects.
  107388. */
  107389. var EffectLayer = /** @class */ (function () {
  107390. /**
  107391. * Instantiates a new effect Layer and references it in the scene.
  107392. * @param name The name of the layer
  107393. * @param scene The scene to use the layer in
  107394. */
  107395. function EffectLayer(
  107396. /** The Friendly of the effect in the scene */
  107397. name, scene) {
  107398. this._vertexBuffers = {};
  107399. this._maxSize = 0;
  107400. this._mainTextureDesiredSize = { width: 0, height: 0 };
  107401. this._shouldRender = true;
  107402. this._postProcesses = [];
  107403. this._textures = [];
  107404. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  107405. /**
  107406. * The clear color of the texture used to generate the glow map.
  107407. */
  107408. this.neutralColor = new BABYLON.Color4();
  107409. /**
  107410. * Specifies wether the highlight layer is enabled or not.
  107411. */
  107412. this.isEnabled = true;
  107413. /**
  107414. * An event triggered when the effect layer has been disposed.
  107415. */
  107416. this.onDisposeObservable = new BABYLON.Observable();
  107417. /**
  107418. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  107419. */
  107420. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  107421. /**
  107422. * An event triggered when the generated texture is being merged in the scene.
  107423. */
  107424. this.onBeforeComposeObservable = new BABYLON.Observable();
  107425. /**
  107426. * An event triggered when the generated texture has been merged in the scene.
  107427. */
  107428. this.onAfterComposeObservable = new BABYLON.Observable();
  107429. /**
  107430. * An event triggered when the efffect layer changes its size.
  107431. */
  107432. this.onSizeChangedObservable = new BABYLON.Observable();
  107433. this.name = name;
  107434. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  107435. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  107436. if (!component) {
  107437. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  107438. this._scene._addComponent(component);
  107439. }
  107440. this._engine = this._scene.getEngine();
  107441. this._maxSize = this._engine.getCaps().maxTextureSize;
  107442. this._scene.effectLayers.push(this);
  107443. // Generate Buffers
  107444. this._generateIndexBuffer();
  107445. this._genrateVertexBuffer();
  107446. }
  107447. Object.defineProperty(EffectLayer.prototype, "camera", {
  107448. /**
  107449. * Gets the camera attached to the layer.
  107450. */
  107451. get: function () {
  107452. return this._effectLayerOptions.camera;
  107453. },
  107454. enumerable: true,
  107455. configurable: true
  107456. });
  107457. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  107458. /**
  107459. * Gets the rendering group id the layer should render in.
  107460. */
  107461. get: function () {
  107462. return this._effectLayerOptions.renderingGroupId;
  107463. },
  107464. enumerable: true,
  107465. configurable: true
  107466. });
  107467. /**
  107468. * Initializes the effect layer with the required options.
  107469. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  107470. */
  107471. EffectLayer.prototype._init = function (options) {
  107472. // Adapt options
  107473. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  107474. this._setMainTextureSize();
  107475. this._createMainTexture();
  107476. this._createTextureAndPostProcesses();
  107477. this._mergeEffect = this._createMergeEffect();
  107478. };
  107479. /**
  107480. * Generates the index buffer of the full screen quad blending to the main canvas.
  107481. */
  107482. EffectLayer.prototype._generateIndexBuffer = function () {
  107483. // Indices
  107484. var indices = [];
  107485. indices.push(0);
  107486. indices.push(1);
  107487. indices.push(2);
  107488. indices.push(0);
  107489. indices.push(2);
  107490. indices.push(3);
  107491. this._indexBuffer = this._engine.createIndexBuffer(indices);
  107492. };
  107493. /**
  107494. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  107495. */
  107496. EffectLayer.prototype._genrateVertexBuffer = function () {
  107497. // VBO
  107498. var vertices = [];
  107499. vertices.push(1, 1);
  107500. vertices.push(-1, 1);
  107501. vertices.push(-1, -1);
  107502. vertices.push(1, -1);
  107503. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  107504. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  107505. };
  107506. /**
  107507. * Sets the main texture desired size which is the closest power of two
  107508. * of the engine canvas size.
  107509. */
  107510. EffectLayer.prototype._setMainTextureSize = function () {
  107511. if (this._effectLayerOptions.mainTextureFixedSize) {
  107512. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  107513. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  107514. }
  107515. else {
  107516. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  107517. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  107518. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  107519. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  107520. }
  107521. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  107522. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  107523. };
  107524. /**
  107525. * Creates the main texture for the effect layer.
  107526. */
  107527. EffectLayer.prototype._createMainTexture = function () {
  107528. var _this = this;
  107529. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  107530. width: this._mainTextureDesiredSize.width,
  107531. height: this._mainTextureDesiredSize.height
  107532. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  107533. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  107534. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107535. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107536. this._mainTexture.anisotropicFilteringLevel = 1;
  107537. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107538. this._mainTexture.renderParticles = false;
  107539. this._mainTexture.renderList = null;
  107540. this._mainTexture.ignoreCameraViewport = true;
  107541. // Custom render function
  107542. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  107543. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  107544. var index;
  107545. var engine = _this._scene.getEngine();
  107546. if (depthOnlySubMeshes.length) {
  107547. engine.setColorWrite(false);
  107548. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  107549. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  107550. }
  107551. engine.setColorWrite(true);
  107552. }
  107553. for (index = 0; index < opaqueSubMeshes.length; index++) {
  107554. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  107555. }
  107556. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  107557. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  107558. }
  107559. for (index = 0; index < transparentSubMeshes.length; index++) {
  107560. _this._renderSubMesh(transparentSubMeshes.data[index]);
  107561. }
  107562. };
  107563. this._mainTexture.onClearObservable.add(function (engine) {
  107564. engine.clear(_this.neutralColor, true, true, true);
  107565. });
  107566. };
  107567. /**
  107568. * Checks for the readiness of the element composing the layer.
  107569. * @param subMesh the mesh to check for
  107570. * @param useInstances specify wether or not to use instances to render the mesh
  107571. * @param emissiveTexture the associated emissive texture used to generate the glow
  107572. * @return true if ready otherwise, false
  107573. */
  107574. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  107575. var material = subMesh.getMaterial();
  107576. if (!material) {
  107577. return false;
  107578. }
  107579. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  107580. return false;
  107581. }
  107582. var defines = [];
  107583. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107584. var mesh = subMesh.getMesh();
  107585. var uv1 = false;
  107586. var uv2 = false;
  107587. // Alpha test
  107588. if (material && material.needAlphaTesting()) {
  107589. var alphaTexture = material.getAlphaTestTexture();
  107590. if (alphaTexture) {
  107591. defines.push("#define ALPHATEST");
  107592. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  107593. alphaTexture.coordinatesIndex === 1) {
  107594. defines.push("#define DIFFUSEUV2");
  107595. uv2 = true;
  107596. }
  107597. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  107598. defines.push("#define DIFFUSEUV1");
  107599. uv1 = true;
  107600. }
  107601. }
  107602. }
  107603. // Emissive
  107604. if (emissiveTexture) {
  107605. defines.push("#define EMISSIVE");
  107606. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  107607. emissiveTexture.coordinatesIndex === 1) {
  107608. defines.push("#define EMISSIVEUV2");
  107609. uv2 = true;
  107610. }
  107611. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  107612. defines.push("#define EMISSIVEUV1");
  107613. uv1 = true;
  107614. }
  107615. }
  107616. if (uv1) {
  107617. attribs.push(BABYLON.VertexBuffer.UVKind);
  107618. defines.push("#define UV1");
  107619. }
  107620. if (uv2) {
  107621. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107622. defines.push("#define UV2");
  107623. }
  107624. // Bones
  107625. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  107626. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  107627. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  107628. if (mesh.numBoneInfluencers > 4) {
  107629. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  107630. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  107631. }
  107632. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  107633. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  107634. }
  107635. else {
  107636. defines.push("#define NUM_BONE_INFLUENCERS 0");
  107637. }
  107638. // Morph targets
  107639. var manager = mesh.morphTargetManager;
  107640. var morphInfluencers = 0;
  107641. if (manager) {
  107642. if (manager.numInfluencers > 0) {
  107643. defines.push("#define MORPHTARGETS");
  107644. morphInfluencers = manager.numInfluencers;
  107645. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  107646. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  107647. }
  107648. }
  107649. // Instances
  107650. if (useInstances) {
  107651. defines.push("#define INSTANCES");
  107652. attribs.push("world0");
  107653. attribs.push("world1");
  107654. attribs.push("world2");
  107655. attribs.push("world3");
  107656. }
  107657. // Get correct effect
  107658. var join = defines.join("\n");
  107659. if (this._cachedDefines !== join) {
  107660. this._cachedDefines = join;
  107661. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  107662. }
  107663. return this._effectLayerMapGenerationEffect.isReady();
  107664. };
  107665. /**
  107666. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  107667. */
  107668. EffectLayer.prototype.render = function () {
  107669. var currentEffect = this._mergeEffect;
  107670. // Check
  107671. if (!currentEffect.isReady())
  107672. return;
  107673. for (var i = 0; i < this._postProcesses.length; i++) {
  107674. if (!this._postProcesses[i].isReady()) {
  107675. return;
  107676. }
  107677. }
  107678. var engine = this._scene.getEngine();
  107679. this.onBeforeComposeObservable.notifyObservers(this);
  107680. // Render
  107681. engine.enableEffect(currentEffect);
  107682. engine.setState(false);
  107683. // VBOs
  107684. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  107685. // Cache
  107686. var previousAlphaMode = engine.getAlphaMode();
  107687. // Go Blend.
  107688. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  107689. // Blends the map on the main canvas.
  107690. this._internalRender(currentEffect);
  107691. // Restore Alpha
  107692. engine.setAlphaMode(previousAlphaMode);
  107693. this.onAfterComposeObservable.notifyObservers(this);
  107694. // Handle size changes.
  107695. var size = this._mainTexture.getSize();
  107696. this._setMainTextureSize();
  107697. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  107698. // Recreate RTT and post processes on size change.
  107699. this.onSizeChangedObservable.notifyObservers(this);
  107700. this._disposeTextureAndPostProcesses();
  107701. this._createMainTexture();
  107702. this._createTextureAndPostProcesses();
  107703. }
  107704. };
  107705. /**
  107706. * Determine if a given mesh will be used in the current effect.
  107707. * @param mesh mesh to test
  107708. * @returns true if the mesh will be used
  107709. */
  107710. EffectLayer.prototype.hasMesh = function (mesh) {
  107711. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  107712. return true;
  107713. }
  107714. return false;
  107715. };
  107716. /**
  107717. * Returns true if the layer contains information to display, otherwise false.
  107718. * @returns true if the glow layer should be rendered
  107719. */
  107720. EffectLayer.prototype.shouldRender = function () {
  107721. return this.isEnabled && this._shouldRender;
  107722. };
  107723. /**
  107724. * Returns true if the mesh should render, otherwise false.
  107725. * @param mesh The mesh to render
  107726. * @returns true if it should render otherwise false
  107727. */
  107728. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  107729. return true;
  107730. };
  107731. /**
  107732. * Returns true if the mesh should render, otherwise false.
  107733. * @param mesh The mesh to render
  107734. * @returns true if it should render otherwise false
  107735. */
  107736. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  107737. return true;
  107738. };
  107739. /**
  107740. * Renders the submesh passed in parameter to the generation map.
  107741. */
  107742. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  107743. var _this = this;
  107744. if (!this.shouldRender()) {
  107745. return;
  107746. }
  107747. var material = subMesh.getMaterial();
  107748. var mesh = subMesh.getRenderingMesh();
  107749. var scene = this._scene;
  107750. var engine = scene.getEngine();
  107751. if (!material) {
  107752. return;
  107753. }
  107754. // Do not block in blend mode.
  107755. if (material.needAlphaBlendingForMesh(mesh)) {
  107756. return;
  107757. }
  107758. // Culling
  107759. engine.setState(material.backFaceCulling);
  107760. // Managing instances
  107761. var batch = mesh._getInstancesRenderList(subMesh._id);
  107762. if (batch.mustReturn) {
  107763. return;
  107764. }
  107765. // Early Exit per mesh
  107766. if (!this._shouldRenderMesh(mesh)) {
  107767. return;
  107768. }
  107769. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  107770. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  107771. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  107772. engine.enableEffect(this._effectLayerMapGenerationEffect);
  107773. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  107774. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  107775. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  107776. // Alpha test
  107777. if (material && material.needAlphaTesting()) {
  107778. var alphaTexture = material.getAlphaTestTexture();
  107779. if (alphaTexture) {
  107780. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  107781. var textureMatrix = alphaTexture.getTextureMatrix();
  107782. if (textureMatrix) {
  107783. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  107784. }
  107785. }
  107786. }
  107787. // Glow emissive only
  107788. if (this._emissiveTextureAndColor.texture) {
  107789. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  107790. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  107791. }
  107792. // Bones
  107793. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  107794. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  107795. }
  107796. // Morph targets
  107797. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  107798. // Draw
  107799. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  107800. }
  107801. else {
  107802. // Need to reset refresh rate of the main map
  107803. this._mainTexture.resetRefreshCounter();
  107804. }
  107805. };
  107806. /**
  107807. * Rebuild the required buffers.
  107808. * @hidden Internal use only.
  107809. */
  107810. EffectLayer.prototype._rebuild = function () {
  107811. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107812. if (vb) {
  107813. vb._rebuild();
  107814. }
  107815. this._generateIndexBuffer();
  107816. };
  107817. /**
  107818. * Dispose only the render target textures and post process.
  107819. */
  107820. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  107821. this._mainTexture.dispose();
  107822. for (var i = 0; i < this._postProcesses.length; i++) {
  107823. if (this._postProcesses[i]) {
  107824. this._postProcesses[i].dispose();
  107825. }
  107826. }
  107827. this._postProcesses = [];
  107828. for (var i = 0; i < this._textures.length; i++) {
  107829. if (this._textures[i]) {
  107830. this._textures[i].dispose();
  107831. }
  107832. }
  107833. this._textures = [];
  107834. };
  107835. /**
  107836. * Dispose the highlight layer and free resources.
  107837. */
  107838. EffectLayer.prototype.dispose = function () {
  107839. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107840. if (vertexBuffer) {
  107841. vertexBuffer.dispose();
  107842. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  107843. }
  107844. if (this._indexBuffer) {
  107845. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  107846. this._indexBuffer = null;
  107847. }
  107848. // Clean textures and post processes
  107849. this._disposeTextureAndPostProcesses();
  107850. // Remove from scene
  107851. var index = this._scene.effectLayers.indexOf(this, 0);
  107852. if (index > -1) {
  107853. this._scene.effectLayers.splice(index, 1);
  107854. }
  107855. // Callback
  107856. this.onDisposeObservable.notifyObservers(this);
  107857. this.onDisposeObservable.clear();
  107858. this.onBeforeRenderMainTextureObservable.clear();
  107859. this.onBeforeComposeObservable.clear();
  107860. this.onAfterComposeObservable.clear();
  107861. this.onSizeChangedObservable.clear();
  107862. };
  107863. /**
  107864. * Gets the class name of the effect layer
  107865. * @returns the string with the class name of the effect layer
  107866. */
  107867. EffectLayer.prototype.getClassName = function () {
  107868. return "EffectLayer";
  107869. };
  107870. /**
  107871. * Creates an effect layer from parsed effect layer data
  107872. * @param parsedEffectLayer defines effect layer data
  107873. * @param scene defines the current scene
  107874. * @param rootUrl defines the root URL containing the effect layer information
  107875. * @returns a parsed effect Layer
  107876. */
  107877. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  107878. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  107879. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  107880. };
  107881. __decorate([
  107882. BABYLON.serialize()
  107883. ], EffectLayer.prototype, "name", void 0);
  107884. __decorate([
  107885. BABYLON.serializeAsColor4()
  107886. ], EffectLayer.prototype, "neutralColor", void 0);
  107887. __decorate([
  107888. BABYLON.serialize()
  107889. ], EffectLayer.prototype, "isEnabled", void 0);
  107890. __decorate([
  107891. BABYLON.serializeAsCameraReference()
  107892. ], EffectLayer.prototype, "camera", null);
  107893. __decorate([
  107894. BABYLON.serialize()
  107895. ], EffectLayer.prototype, "renderingGroupId", null);
  107896. return EffectLayer;
  107897. }());
  107898. BABYLON.EffectLayer = EffectLayer;
  107899. })(BABYLON || (BABYLON = {}));
  107900. //# sourceMappingURL=babylon.effectLayer.js.map
  107901. var BABYLON;
  107902. (function (BABYLON) {
  107903. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  107904. for (var index = 0; index < this.effectLayers.length; index++) {
  107905. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  107906. return this.effectLayers[index];
  107907. }
  107908. }
  107909. return null;
  107910. };
  107911. /**
  107912. * Special Glow Blur post process only blurring the alpha channel
  107913. * It enforces keeping the most luminous color in the color channel.
  107914. */
  107915. var GlowBlurPostProcess = /** @class */ (function (_super) {
  107916. __extends(GlowBlurPostProcess, _super);
  107917. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  107918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  107919. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  107920. _this.direction = direction;
  107921. _this.kernel = kernel;
  107922. _this.onApplyObservable.add(function (effect) {
  107923. effect.setFloat2("screenSize", _this.width, _this.height);
  107924. effect.setVector2("direction", _this.direction);
  107925. effect.setFloat("blurWidth", _this.kernel);
  107926. });
  107927. return _this;
  107928. }
  107929. return GlowBlurPostProcess;
  107930. }(BABYLON.PostProcess));
  107931. /**
  107932. * The highlight layer Helps adding a glow effect around a mesh.
  107933. *
  107934. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  107935. * glowy meshes to your scene.
  107936. *
  107937. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  107938. */
  107939. var HighlightLayer = /** @class */ (function (_super) {
  107940. __extends(HighlightLayer, _super);
  107941. /**
  107942. * Instantiates a new highlight Layer and references it to the scene..
  107943. * @param name The name of the layer
  107944. * @param scene The scene to use the layer in
  107945. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  107946. */
  107947. function HighlightLayer(name, scene, options) {
  107948. var _this = _super.call(this, name, scene) || this;
  107949. _this.name = name;
  107950. /**
  107951. * Specifies whether or not the inner glow is ACTIVE in the layer.
  107952. */
  107953. _this.innerGlow = true;
  107954. /**
  107955. * Specifies whether or not the outer glow is ACTIVE in the layer.
  107956. */
  107957. _this.outerGlow = true;
  107958. /**
  107959. * An event triggered when the highlight layer is being blurred.
  107960. */
  107961. _this.onBeforeBlurObservable = new BABYLON.Observable();
  107962. /**
  107963. * An event triggered when the highlight layer has been blurred.
  107964. */
  107965. _this.onAfterBlurObservable = new BABYLON.Observable();
  107966. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  107967. _this._meshes = {};
  107968. _this._excludedMeshes = {};
  107969. _this.neutralColor = HighlightLayer.NeutralColor;
  107970. // Warn on stencil
  107971. if (!_this._engine.isStencilEnable) {
  107972. 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 }");
  107973. }
  107974. // Adapt options
  107975. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  107976. // Initialize the layer
  107977. _this._init({
  107978. alphaBlendingMode: _this._options.alphaBlendingMode,
  107979. camera: _this._options.camera,
  107980. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  107981. mainTextureRatio: _this._options.mainTextureRatio,
  107982. renderingGroupId: _this._options.renderingGroupId
  107983. });
  107984. // Do not render as long as no meshes have been added
  107985. _this._shouldRender = false;
  107986. return _this;
  107987. }
  107988. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  107989. /**
  107990. * Gets the horizontal size of the blur.
  107991. */
  107992. get: function () {
  107993. return this._horizontalBlurPostprocess.kernel;
  107994. },
  107995. /**
  107996. * Specifies the horizontal size of the blur.
  107997. */
  107998. set: function (value) {
  107999. this._horizontalBlurPostprocess.kernel = value;
  108000. },
  108001. enumerable: true,
  108002. configurable: true
  108003. });
  108004. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  108005. /**
  108006. * Gets the vertical size of the blur.
  108007. */
  108008. get: function () {
  108009. return this._verticalBlurPostprocess.kernel;
  108010. },
  108011. /**
  108012. * Specifies the vertical size of the blur.
  108013. */
  108014. set: function (value) {
  108015. this._verticalBlurPostprocess.kernel = value;
  108016. },
  108017. enumerable: true,
  108018. configurable: true
  108019. });
  108020. /**
  108021. * Get the effect name of the layer.
  108022. * @return The effect name
  108023. */
  108024. HighlightLayer.prototype.getEffectName = function () {
  108025. return HighlightLayer.EffectName;
  108026. };
  108027. /**
  108028. * Create the merge effect. This is the shader use to blit the information back
  108029. * to the main canvas at the end of the scene rendering.
  108030. */
  108031. HighlightLayer.prototype._createMergeEffect = function () {
  108032. // Effect
  108033. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  108034. };
  108035. /**
  108036. * Creates the render target textures and post processes used in the highlight layer.
  108037. */
  108038. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  108039. var _this = this;
  108040. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  108041. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  108042. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  108043. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  108044. var textureType = 0;
  108045. if (this._engine.getCaps().textureHalfFloatRender) {
  108046. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  108047. }
  108048. else {
  108049. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108050. }
  108051. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  108052. width: blurTextureWidth,
  108053. height: blurTextureHeight
  108054. }, this._scene, false, true, textureType);
  108055. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108056. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108057. this._blurTexture.anisotropicFilteringLevel = 16;
  108058. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  108059. this._blurTexture.renderParticles = false;
  108060. this._blurTexture.ignoreCameraViewport = true;
  108061. this._textures = [this._blurTexture];
  108062. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  108063. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108064. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  108065. effect.setTexture("textureSampler", _this._mainTexture);
  108066. });
  108067. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108068. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  108069. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  108070. });
  108071. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108072. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  108073. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  108074. });
  108075. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  108076. }
  108077. else {
  108078. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  108079. width: blurTextureWidth,
  108080. height: blurTextureHeight
  108081. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108082. this._horizontalBlurPostprocess.width = blurTextureWidth;
  108083. this._horizontalBlurPostprocess.height = blurTextureHeight;
  108084. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  108085. effect.setTexture("textureSampler", _this._mainTexture);
  108086. });
  108087. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  108088. width: blurTextureWidth,
  108089. height: blurTextureHeight
  108090. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108091. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  108092. }
  108093. this._mainTexture.onAfterUnbindObservable.add(function () {
  108094. _this.onBeforeBlurObservable.notifyObservers(_this);
  108095. var internalTexture = _this._blurTexture.getInternalTexture();
  108096. if (internalTexture) {
  108097. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  108098. }
  108099. _this.onAfterBlurObservable.notifyObservers(_this);
  108100. });
  108101. // Prevent autoClear.
  108102. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  108103. };
  108104. /**
  108105. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  108106. */
  108107. HighlightLayer.prototype.needStencil = function () {
  108108. return true;
  108109. };
  108110. /**
  108111. * Checks for the readiness of the element composing the layer.
  108112. * @param subMesh the mesh to check for
  108113. * @param useInstances specify wether or not to use instances to render the mesh
  108114. * @param emissiveTexture the associated emissive texture used to generate the glow
  108115. * @return true if ready otherwise, false
  108116. */
  108117. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  108118. var material = subMesh.getMaterial();
  108119. var mesh = subMesh.getRenderingMesh();
  108120. if (!material || !mesh || !this._meshes) {
  108121. return false;
  108122. }
  108123. var emissiveTexture = null;
  108124. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  108125. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  108126. emissiveTexture = material.emissiveTexture;
  108127. }
  108128. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  108129. };
  108130. /**
  108131. * Implementation specific of rendering the generating effect on the main canvas.
  108132. * @param effect The effect used to render through
  108133. */
  108134. HighlightLayer.prototype._internalRender = function (effect) {
  108135. // Texture
  108136. effect.setTexture("textureSampler", this._blurTexture);
  108137. // Cache
  108138. var engine = this._engine;
  108139. var previousStencilBuffer = engine.getStencilBuffer();
  108140. var previousStencilFunction = engine.getStencilFunction();
  108141. var previousStencilMask = engine.getStencilMask();
  108142. var previousStencilOperationPass = engine.getStencilOperationPass();
  108143. var previousStencilOperationFail = engine.getStencilOperationFail();
  108144. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  108145. var previousStencilReference = engine.getStencilFunctionReference();
  108146. // Stencil operations
  108147. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  108148. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  108149. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  108150. // Draw order
  108151. engine.setStencilMask(0x00);
  108152. engine.setStencilBuffer(true);
  108153. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  108154. // 2 passes inner outer
  108155. if (this.outerGlow) {
  108156. effect.setFloat("offset", 0);
  108157. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  108158. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108159. }
  108160. if (this.innerGlow) {
  108161. effect.setFloat("offset", 1);
  108162. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  108163. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108164. }
  108165. // Restore Cache
  108166. engine.setStencilFunction(previousStencilFunction);
  108167. engine.setStencilMask(previousStencilMask);
  108168. engine.setStencilBuffer(previousStencilBuffer);
  108169. engine.setStencilOperationPass(previousStencilOperationPass);
  108170. engine.setStencilOperationFail(previousStencilOperationFail);
  108171. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  108172. engine.setStencilFunctionReference(previousStencilReference);
  108173. };
  108174. /**
  108175. * Returns true if the layer contains information to display, otherwise false.
  108176. */
  108177. HighlightLayer.prototype.shouldRender = function () {
  108178. if (_super.prototype.shouldRender.call(this)) {
  108179. return this._meshes ? true : false;
  108180. }
  108181. return false;
  108182. };
  108183. /**
  108184. * Returns true if the mesh should render, otherwise false.
  108185. * @param mesh The mesh to render
  108186. * @returns true if it should render otherwise false
  108187. */
  108188. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  108189. // Excluded Mesh
  108190. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  108191. return false;
  108192. }
  108193. ;
  108194. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108195. return false;
  108196. }
  108197. return true;
  108198. };
  108199. /**
  108200. * Sets the required values for both the emissive texture and and the main color.
  108201. */
  108202. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  108203. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  108204. if (highlightLayerMesh) {
  108205. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  108206. }
  108207. else {
  108208. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  108209. }
  108210. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  108211. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  108212. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  108213. }
  108214. else {
  108215. this._emissiveTextureAndColor.texture = null;
  108216. }
  108217. };
  108218. /**
  108219. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  108220. * @param mesh The mesh to exclude from the highlight layer
  108221. */
  108222. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  108223. if (!this._excludedMeshes) {
  108224. return;
  108225. }
  108226. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  108227. if (!meshExcluded) {
  108228. this._excludedMeshes[mesh.uniqueId] = {
  108229. mesh: mesh,
  108230. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  108231. mesh.getEngine().setStencilBuffer(false);
  108232. }),
  108233. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  108234. mesh.getEngine().setStencilBuffer(true);
  108235. }),
  108236. };
  108237. }
  108238. };
  108239. /**
  108240. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  108241. * @param mesh The mesh to highlight
  108242. */
  108243. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  108244. if (!this._excludedMeshes) {
  108245. return;
  108246. }
  108247. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  108248. if (meshExcluded) {
  108249. if (meshExcluded.beforeRender) {
  108250. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  108251. }
  108252. if (meshExcluded.afterRender) {
  108253. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  108254. }
  108255. }
  108256. this._excludedMeshes[mesh.uniqueId] = null;
  108257. };
  108258. /**
  108259. * Determine if a given mesh will be highlighted by the current HighlightLayer
  108260. * @param mesh mesh to test
  108261. * @returns true if the mesh will be highlighted by the current HighlightLayer
  108262. */
  108263. HighlightLayer.prototype.hasMesh = function (mesh) {
  108264. if (!this._meshes) {
  108265. return false;
  108266. }
  108267. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108268. return false;
  108269. }
  108270. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  108271. };
  108272. /**
  108273. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  108274. * @param mesh The mesh to highlight
  108275. * @param color The color of the highlight
  108276. * @param glowEmissiveOnly Extract the glow from the emissive texture
  108277. */
  108278. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  108279. var _this = this;
  108280. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  108281. if (!this._meshes) {
  108282. return;
  108283. }
  108284. var meshHighlight = this._meshes[mesh.uniqueId];
  108285. if (meshHighlight) {
  108286. meshHighlight.color = color;
  108287. }
  108288. else {
  108289. this._meshes[mesh.uniqueId] = {
  108290. mesh: mesh,
  108291. color: color,
  108292. // Lambda required for capture due to Observable this context
  108293. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  108294. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  108295. _this._defaultStencilReference(mesh);
  108296. }
  108297. else {
  108298. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  108299. }
  108300. }),
  108301. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  108302. glowEmissiveOnly: glowEmissiveOnly
  108303. };
  108304. mesh.onDisposeObservable.add(function () {
  108305. _this._disposeMesh(mesh);
  108306. });
  108307. }
  108308. this._shouldRender = true;
  108309. };
  108310. /**
  108311. * Remove a mesh from the highlight layer in order to make it stop glowing.
  108312. * @param mesh The mesh to highlight
  108313. */
  108314. HighlightLayer.prototype.removeMesh = function (mesh) {
  108315. if (!this._meshes) {
  108316. return;
  108317. }
  108318. var meshHighlight = this._meshes[mesh.uniqueId];
  108319. if (meshHighlight) {
  108320. if (meshHighlight.observerHighlight) {
  108321. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  108322. }
  108323. if (meshHighlight.observerDefault) {
  108324. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  108325. }
  108326. delete this._meshes[mesh.uniqueId];
  108327. }
  108328. this._shouldRender = false;
  108329. for (var meshHighlightToCheck in this._meshes) {
  108330. if (this._meshes[meshHighlightToCheck]) {
  108331. this._shouldRender = true;
  108332. break;
  108333. }
  108334. }
  108335. };
  108336. /**
  108337. * Force the stencil to the normal expected value for none glowing parts
  108338. */
  108339. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  108340. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  108341. };
  108342. /**
  108343. * Free any resources and references associated to a mesh.
  108344. * Internal use
  108345. * @param mesh The mesh to free.
  108346. * @hidden
  108347. */
  108348. HighlightLayer.prototype._disposeMesh = function (mesh) {
  108349. this.removeMesh(mesh);
  108350. this.removeExcludedMesh(mesh);
  108351. };
  108352. /**
  108353. * Dispose the highlight layer and free resources.
  108354. */
  108355. HighlightLayer.prototype.dispose = function () {
  108356. if (this._meshes) {
  108357. // Clean mesh references
  108358. for (var id in this._meshes) {
  108359. var meshHighlight = this._meshes[id];
  108360. if (meshHighlight && meshHighlight.mesh) {
  108361. if (meshHighlight.observerHighlight) {
  108362. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  108363. }
  108364. if (meshHighlight.observerDefault) {
  108365. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  108366. }
  108367. }
  108368. }
  108369. this._meshes = null;
  108370. }
  108371. if (this._excludedMeshes) {
  108372. for (var id in this._excludedMeshes) {
  108373. var meshHighlight = this._excludedMeshes[id];
  108374. if (meshHighlight) {
  108375. if (meshHighlight.beforeRender) {
  108376. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  108377. }
  108378. if (meshHighlight.afterRender) {
  108379. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  108380. }
  108381. }
  108382. }
  108383. this._excludedMeshes = null;
  108384. }
  108385. _super.prototype.dispose.call(this);
  108386. };
  108387. /**
  108388. * Gets the class name of the effect layer
  108389. * @returns the string with the class name of the effect layer
  108390. */
  108391. HighlightLayer.prototype.getClassName = function () {
  108392. return "HighlightLayer";
  108393. };
  108394. /**
  108395. * Serializes this Highlight layer
  108396. * @returns a serialized Highlight layer object
  108397. */
  108398. HighlightLayer.prototype.serialize = function () {
  108399. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108400. serializationObject.customType = "BABYLON.HighlightLayer";
  108401. // Highlighted meshes
  108402. serializationObject.meshes = [];
  108403. if (this._meshes) {
  108404. for (var m in this._meshes) {
  108405. var mesh = this._meshes[m];
  108406. if (mesh) {
  108407. serializationObject.meshes.push({
  108408. glowEmissiveOnly: mesh.glowEmissiveOnly,
  108409. color: mesh.color.asArray(),
  108410. meshId: mesh.mesh.id
  108411. });
  108412. }
  108413. }
  108414. }
  108415. // Excluded meshes
  108416. serializationObject.excludedMeshes = [];
  108417. if (this._excludedMeshes) {
  108418. for (var e in this._excludedMeshes) {
  108419. var excludedMesh = this._excludedMeshes[e];
  108420. if (excludedMesh) {
  108421. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  108422. }
  108423. }
  108424. }
  108425. return serializationObject;
  108426. };
  108427. /**
  108428. * Creates a Highlight layer from parsed Highlight layer data
  108429. * @param parsedHightlightLayer defines the Highlight layer data
  108430. * @param scene defines the current scene
  108431. * @param rootUrl defines the root URL containing the Highlight layer information
  108432. * @returns a parsed Highlight layer
  108433. */
  108434. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  108435. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  108436. var index;
  108437. // Excluded meshes
  108438. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  108439. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  108440. if (mesh) {
  108441. hl.addExcludedMesh(mesh);
  108442. }
  108443. }
  108444. // Included meshes
  108445. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  108446. var highlightedMesh = parsedHightlightLayer.meshes[index];
  108447. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  108448. if (mesh) {
  108449. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  108450. }
  108451. }
  108452. return hl;
  108453. };
  108454. /**
  108455. * Effect Name of the highlight layer.
  108456. */
  108457. HighlightLayer.EffectName = "HighlightLayer";
  108458. /**
  108459. * The neutral color used during the preparation of the glow effect.
  108460. * This is black by default as the blend operation is a blend operation.
  108461. */
  108462. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  108463. /**
  108464. * Stencil value used for glowing meshes.
  108465. */
  108466. HighlightLayer.GlowingMeshStencilReference = 0x02;
  108467. /**
  108468. * Stencil value used for the other meshes in the scene.
  108469. */
  108470. HighlightLayer.NormalMeshStencilReference = 0x01;
  108471. __decorate([
  108472. BABYLON.serialize()
  108473. ], HighlightLayer.prototype, "innerGlow", void 0);
  108474. __decorate([
  108475. BABYLON.serialize()
  108476. ], HighlightLayer.prototype, "outerGlow", void 0);
  108477. __decorate([
  108478. BABYLON.serialize()
  108479. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  108480. __decorate([
  108481. BABYLON.serialize()
  108482. ], HighlightLayer.prototype, "blurVerticalSize", null);
  108483. __decorate([
  108484. BABYLON.serialize("options")
  108485. ], HighlightLayer.prototype, "_options", void 0);
  108486. return HighlightLayer;
  108487. }(BABYLON.EffectLayer));
  108488. BABYLON.HighlightLayer = HighlightLayer;
  108489. })(BABYLON || (BABYLON = {}));
  108490. //# sourceMappingURL=babylon.highlightLayer.js.map
  108491. var BABYLON;
  108492. (function (BABYLON) {
  108493. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  108494. for (var index = 0; index < this.effectLayers.length; index++) {
  108495. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  108496. return this.effectLayers[index];
  108497. }
  108498. }
  108499. return null;
  108500. };
  108501. /**
  108502. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  108503. *
  108504. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  108505. * glowy meshes to your scene.
  108506. *
  108507. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  108508. */
  108509. var GlowLayer = /** @class */ (function (_super) {
  108510. __extends(GlowLayer, _super);
  108511. /**
  108512. * Instantiates a new glow Layer and references it to the scene.
  108513. * @param name The name of the layer
  108514. * @param scene The scene to use the layer in
  108515. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  108516. */
  108517. function GlowLayer(name, scene, options) {
  108518. var _this = _super.call(this, name, scene) || this;
  108519. _this._intensity = 1.0;
  108520. _this._includedOnlyMeshes = [];
  108521. _this._excludedMeshes = [];
  108522. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  108523. // Adapt options
  108524. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  108525. // Initialize the layer
  108526. _this._init({
  108527. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  108528. camera: _this._options.camera,
  108529. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  108530. mainTextureRatio: _this._options.mainTextureRatio,
  108531. renderingGroupId: _this._options.renderingGroupId
  108532. });
  108533. return _this;
  108534. }
  108535. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  108536. /**
  108537. * Gets the kernel size of the blur.
  108538. */
  108539. get: function () {
  108540. return this._horizontalBlurPostprocess1.kernel;
  108541. },
  108542. /**
  108543. * Sets the kernel size of the blur.
  108544. */
  108545. set: function (value) {
  108546. this._horizontalBlurPostprocess1.kernel = value;
  108547. this._verticalBlurPostprocess1.kernel = value;
  108548. this._horizontalBlurPostprocess2.kernel = value;
  108549. this._verticalBlurPostprocess2.kernel = value;
  108550. },
  108551. enumerable: true,
  108552. configurable: true
  108553. });
  108554. Object.defineProperty(GlowLayer.prototype, "intensity", {
  108555. /**
  108556. * Gets the glow intensity.
  108557. */
  108558. get: function () {
  108559. return this._intensity;
  108560. },
  108561. /**
  108562. * Sets the glow intensity.
  108563. */
  108564. set: function (value) {
  108565. this._intensity = value;
  108566. },
  108567. enumerable: true,
  108568. configurable: true
  108569. });
  108570. /**
  108571. * Get the effect name of the layer.
  108572. * @return The effect name
  108573. */
  108574. GlowLayer.prototype.getEffectName = function () {
  108575. return GlowLayer.EffectName;
  108576. };
  108577. /**
  108578. * Create the merge effect. This is the shader use to blit the information back
  108579. * to the main canvas at the end of the scene rendering.
  108580. */
  108581. GlowLayer.prototype._createMergeEffect = function () {
  108582. // Effect
  108583. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  108584. };
  108585. /**
  108586. * Creates the render target textures and post processes used in the glow layer.
  108587. */
  108588. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  108589. var _this = this;
  108590. var blurTextureWidth = this._mainTextureDesiredSize.width;
  108591. var blurTextureHeight = this._mainTextureDesiredSize.height;
  108592. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  108593. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  108594. var textureType = 0;
  108595. if (this._engine.getCaps().textureHalfFloatRender) {
  108596. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  108597. }
  108598. else {
  108599. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108600. }
  108601. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  108602. width: blurTextureWidth,
  108603. height: blurTextureHeight
  108604. }, this._scene, false, true, textureType);
  108605. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108606. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108607. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108608. this._blurTexture1.renderParticles = false;
  108609. this._blurTexture1.ignoreCameraViewport = true;
  108610. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  108611. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  108612. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  108613. width: blurTextureWidth2,
  108614. height: blurTextureHeight2
  108615. }, this._scene, false, true, textureType);
  108616. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108617. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108618. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108619. this._blurTexture2.renderParticles = false;
  108620. this._blurTexture2.ignoreCameraViewport = true;
  108621. this._textures = [this._blurTexture1, this._blurTexture2];
  108622. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  108623. width: blurTextureWidth,
  108624. height: blurTextureHeight
  108625. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108626. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  108627. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  108628. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  108629. effect.setTexture("textureSampler", _this._mainTexture);
  108630. });
  108631. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  108632. width: blurTextureWidth,
  108633. height: blurTextureHeight
  108634. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108635. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  108636. width: blurTextureWidth2,
  108637. height: blurTextureHeight2
  108638. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108639. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  108640. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  108641. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  108642. effect.setTexture("textureSampler", _this._blurTexture1);
  108643. });
  108644. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  108645. width: blurTextureWidth2,
  108646. height: blurTextureHeight2
  108647. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108648. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  108649. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  108650. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  108651. this._mainTexture.samples = this._options.mainTextureSamples;
  108652. this._mainTexture.onAfterUnbindObservable.add(function () {
  108653. var internalTexture = _this._blurTexture1.getInternalTexture();
  108654. if (internalTexture) {
  108655. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  108656. internalTexture = _this._blurTexture2.getInternalTexture();
  108657. if (internalTexture) {
  108658. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  108659. }
  108660. }
  108661. });
  108662. // Prevent autoClear.
  108663. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  108664. };
  108665. /**
  108666. * Checks for the readiness of the element composing the layer.
  108667. * @param subMesh the mesh to check for
  108668. * @param useInstances specify wether or not to use instances to render the mesh
  108669. * @param emissiveTexture the associated emissive texture used to generate the glow
  108670. * @return true if ready otherwise, false
  108671. */
  108672. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  108673. var material = subMesh.getMaterial();
  108674. var mesh = subMesh.getRenderingMesh();
  108675. if (!material || !mesh) {
  108676. return false;
  108677. }
  108678. var emissiveTexture = material.emissiveTexture;
  108679. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  108680. };
  108681. /**
  108682. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  108683. */
  108684. GlowLayer.prototype.needStencil = function () {
  108685. return false;
  108686. };
  108687. /**
  108688. * Implementation specific of rendering the generating effect on the main canvas.
  108689. * @param effect The effect used to render through
  108690. */
  108691. GlowLayer.prototype._internalRender = function (effect) {
  108692. // Texture
  108693. effect.setTexture("textureSampler", this._blurTexture1);
  108694. effect.setTexture("textureSampler2", this._blurTexture2);
  108695. effect.setFloat("offset", this._intensity);
  108696. // Cache
  108697. var engine = this._engine;
  108698. var previousStencilBuffer = engine.getStencilBuffer();
  108699. // Draw order
  108700. engine.setStencilBuffer(false);
  108701. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108702. // Draw order
  108703. engine.setStencilBuffer(previousStencilBuffer);
  108704. };
  108705. /**
  108706. * Sets the required values for both the emissive texture and and the main color.
  108707. */
  108708. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  108709. var textureLevel = 1.0;
  108710. if (this.customEmissiveTextureSelector) {
  108711. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  108712. }
  108713. else {
  108714. if (material) {
  108715. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  108716. if (this._emissiveTextureAndColor.texture) {
  108717. textureLevel = this._emissiveTextureAndColor.texture.level;
  108718. }
  108719. }
  108720. else {
  108721. this._emissiveTextureAndColor.texture = null;
  108722. }
  108723. }
  108724. if (this.customEmissiveColorSelector) {
  108725. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  108726. }
  108727. else {
  108728. if (material.emissiveColor) {
  108729. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  108730. }
  108731. else {
  108732. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  108733. }
  108734. }
  108735. };
  108736. /**
  108737. * Returns true if the mesh should render, otherwise false.
  108738. * @param mesh The mesh to render
  108739. * @returns true if it should render otherwise false
  108740. */
  108741. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  108742. return this.hasMesh(mesh);
  108743. };
  108744. /**
  108745. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  108746. * @param mesh The mesh to exclude from the glow layer
  108747. */
  108748. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  108749. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  108750. this._excludedMeshes.push(mesh.uniqueId);
  108751. }
  108752. };
  108753. /**
  108754. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  108755. * @param mesh The mesh to remove
  108756. */
  108757. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  108758. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  108759. if (index !== -1) {
  108760. this._excludedMeshes.splice(index, 1);
  108761. }
  108762. };
  108763. /**
  108764. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  108765. * @param mesh The mesh to include in the glow layer
  108766. */
  108767. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  108768. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  108769. this._includedOnlyMeshes.push(mesh.uniqueId);
  108770. }
  108771. };
  108772. /**
  108773. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  108774. * @param mesh The mesh to remove
  108775. */
  108776. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  108777. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  108778. if (index !== -1) {
  108779. this._includedOnlyMeshes.splice(index, 1);
  108780. }
  108781. };
  108782. /**
  108783. * Determine if a given mesh will be used in the glow layer
  108784. * @param mesh The mesh to test
  108785. * @returns true if the mesh will be highlighted by the current glow layer
  108786. */
  108787. GlowLayer.prototype.hasMesh = function (mesh) {
  108788. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108789. return false;
  108790. }
  108791. // Included Mesh
  108792. if (this._includedOnlyMeshes.length) {
  108793. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  108794. }
  108795. ;
  108796. // Excluded Mesh
  108797. if (this._excludedMeshes.length) {
  108798. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  108799. }
  108800. ;
  108801. return true;
  108802. };
  108803. /**
  108804. * Free any resources and references associated to a mesh.
  108805. * Internal use
  108806. * @param mesh The mesh to free.
  108807. * @hidden
  108808. */
  108809. GlowLayer.prototype._disposeMesh = function (mesh) {
  108810. this.removeIncludedOnlyMesh(mesh);
  108811. this.removeExcludedMesh(mesh);
  108812. };
  108813. /**
  108814. * Gets the class name of the effect layer
  108815. * @returns the string with the class name of the effect layer
  108816. */
  108817. GlowLayer.prototype.getClassName = function () {
  108818. return "GlowLayer";
  108819. };
  108820. /**
  108821. * Serializes this glow layer
  108822. * @returns a serialized glow layer object
  108823. */
  108824. GlowLayer.prototype.serialize = function () {
  108825. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108826. serializationObject.customType = "BABYLON.GlowLayer";
  108827. var index;
  108828. // Included meshes
  108829. serializationObject.includedMeshes = [];
  108830. if (this._includedOnlyMeshes.length) {
  108831. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  108832. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  108833. if (mesh) {
  108834. serializationObject.includedMeshes.push(mesh.id);
  108835. }
  108836. }
  108837. }
  108838. // Excluded meshes
  108839. serializationObject.excludedMeshes = [];
  108840. if (this._excludedMeshes.length) {
  108841. for (index = 0; index < this._excludedMeshes.length; index++) {
  108842. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  108843. if (mesh) {
  108844. serializationObject.excludedMeshes.push(mesh.id);
  108845. }
  108846. }
  108847. }
  108848. return serializationObject;
  108849. };
  108850. /**
  108851. * Creates a Glow Layer from parsed glow layer data
  108852. * @param parsedGlowLayer defines glow layer data
  108853. * @param scene defines the current scene
  108854. * @param rootUrl defines the root URL containing the glow layer information
  108855. * @returns a parsed Glow Layer
  108856. */
  108857. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  108858. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  108859. var index;
  108860. // Excluded meshes
  108861. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  108862. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  108863. if (mesh) {
  108864. gl.addExcludedMesh(mesh);
  108865. }
  108866. }
  108867. // Included meshes
  108868. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  108869. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  108870. if (mesh) {
  108871. gl.addIncludedOnlyMesh(mesh);
  108872. }
  108873. }
  108874. return gl;
  108875. };
  108876. /**
  108877. * Effect Name of the layer.
  108878. */
  108879. GlowLayer.EffectName = "GlowLayer";
  108880. /**
  108881. * The default blur kernel size used for the glow.
  108882. */
  108883. GlowLayer.DefaultBlurKernelSize = 32;
  108884. /**
  108885. * The default texture size ratio used for the glow.
  108886. */
  108887. GlowLayer.DefaultTextureRatio = 0.5;
  108888. __decorate([
  108889. BABYLON.serialize()
  108890. ], GlowLayer.prototype, "blurKernelSize", null);
  108891. __decorate([
  108892. BABYLON.serialize()
  108893. ], GlowLayer.prototype, "intensity", null);
  108894. __decorate([
  108895. BABYLON.serialize("options")
  108896. ], GlowLayer.prototype, "_options", void 0);
  108897. return GlowLayer;
  108898. }(BABYLON.EffectLayer));
  108899. BABYLON.GlowLayer = GlowLayer;
  108900. })(BABYLON || (BABYLON = {}));
  108901. //# sourceMappingURL=babylon.glowLayer.js.map
  108902. var BABYLON;
  108903. (function (BABYLON) {
  108904. /**
  108905. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  108906. */
  108907. var AssetTaskState;
  108908. (function (AssetTaskState) {
  108909. /**
  108910. * Initialization
  108911. */
  108912. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  108913. /**
  108914. * Running
  108915. */
  108916. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  108917. /**
  108918. * Done
  108919. */
  108920. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  108921. /**
  108922. * Error
  108923. */
  108924. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  108925. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  108926. /**
  108927. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  108928. */
  108929. var AbstractAssetTask = /** @class */ (function () {
  108930. /**
  108931. * Creates a new {BABYLON.AssetsManager}
  108932. * @param name defines the name of the task
  108933. */
  108934. function AbstractAssetTask(
  108935. /**
  108936. * Task name
  108937. */ name) {
  108938. this.name = name;
  108939. this._isCompleted = false;
  108940. this._taskState = AssetTaskState.INIT;
  108941. }
  108942. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  108943. /**
  108944. * Get if the task is completed
  108945. */
  108946. get: function () {
  108947. return this._isCompleted;
  108948. },
  108949. enumerable: true,
  108950. configurable: true
  108951. });
  108952. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  108953. /**
  108954. * Gets the current state of the task
  108955. */
  108956. get: function () {
  108957. return this._taskState;
  108958. },
  108959. enumerable: true,
  108960. configurable: true
  108961. });
  108962. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  108963. /**
  108964. * Gets the current error object (if task is in error)
  108965. */
  108966. get: function () {
  108967. return this._errorObject;
  108968. },
  108969. enumerable: true,
  108970. configurable: true
  108971. });
  108972. /**
  108973. * Internal only
  108974. * @hidden
  108975. */
  108976. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  108977. if (this._errorObject) {
  108978. return;
  108979. }
  108980. this._errorObject = {
  108981. message: message,
  108982. exception: exception
  108983. };
  108984. };
  108985. /**
  108986. * Execute the current task
  108987. * @param scene defines the scene where you want your assets to be loaded
  108988. * @param onSuccess is a callback called when the task is successfully executed
  108989. * @param onError is a callback called if an error occurs
  108990. */
  108991. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  108992. var _this = this;
  108993. this._taskState = AssetTaskState.RUNNING;
  108994. this.runTask(scene, function () {
  108995. _this.onDoneCallback(onSuccess, onError);
  108996. }, function (msg, exception) {
  108997. _this.onErrorCallback(onError, msg, exception);
  108998. });
  108999. };
  109000. /**
  109001. * Execute the current task
  109002. * @param scene defines the scene where you want your assets to be loaded
  109003. * @param onSuccess is a callback called when the task is successfully executed
  109004. * @param onError is a callback called if an error occurs
  109005. */
  109006. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109007. throw new Error("runTask is not implemented");
  109008. };
  109009. /**
  109010. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  109011. * This can be used with failed tasks that have the reason for failure fixed.
  109012. */
  109013. AbstractAssetTask.prototype.reset = function () {
  109014. this._taskState = AssetTaskState.INIT;
  109015. };
  109016. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  109017. this._taskState = AssetTaskState.ERROR;
  109018. this._errorObject = {
  109019. message: message,
  109020. exception: exception
  109021. };
  109022. if (this.onError) {
  109023. this.onError(this, message, exception);
  109024. }
  109025. onError();
  109026. };
  109027. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  109028. try {
  109029. this._taskState = AssetTaskState.DONE;
  109030. this._isCompleted = true;
  109031. if (this.onSuccess) {
  109032. this.onSuccess(this);
  109033. }
  109034. onSuccess();
  109035. }
  109036. catch (e) {
  109037. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  109038. }
  109039. };
  109040. return AbstractAssetTask;
  109041. }());
  109042. BABYLON.AbstractAssetTask = AbstractAssetTask;
  109043. /**
  109044. * Class used to share progress information about assets loading
  109045. */
  109046. var AssetsProgressEvent = /** @class */ (function () {
  109047. /**
  109048. * Creates a {BABYLON.AssetsProgressEvent}
  109049. * @param remainingCount defines the number of remaining tasks to process
  109050. * @param totalCount defines the total number of tasks
  109051. * @param task defines the task that was just processed
  109052. */
  109053. function AssetsProgressEvent(remainingCount, totalCount, task) {
  109054. this.remainingCount = remainingCount;
  109055. this.totalCount = totalCount;
  109056. this.task = task;
  109057. }
  109058. return AssetsProgressEvent;
  109059. }());
  109060. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  109061. /**
  109062. * Define a task used by {BABYLON.AssetsManager} to load meshes
  109063. */
  109064. var MeshAssetTask = /** @class */ (function (_super) {
  109065. __extends(MeshAssetTask, _super);
  109066. /**
  109067. * Creates a new {BABYLON.MeshAssetTask}
  109068. * @param name defines the name of the task
  109069. * @param meshesNames defines the list of mesh's names you want to load
  109070. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  109071. * @param sceneFilename defines the filename of the scene to load from
  109072. */
  109073. function MeshAssetTask(
  109074. /**
  109075. * Defines the name of the task
  109076. */
  109077. name,
  109078. /**
  109079. * Defines the list of mesh's names you want to load
  109080. */
  109081. meshesNames,
  109082. /**
  109083. * Defines the root url to use as a base to load your meshes and associated resources
  109084. */
  109085. rootUrl,
  109086. /**
  109087. * Defines the filename of the scene to load from
  109088. */
  109089. sceneFilename) {
  109090. var _this = _super.call(this, name) || this;
  109091. _this.name = name;
  109092. _this.meshesNames = meshesNames;
  109093. _this.rootUrl = rootUrl;
  109094. _this.sceneFilename = sceneFilename;
  109095. return _this;
  109096. }
  109097. /**
  109098. * Execute the current task
  109099. * @param scene defines the scene where you want your assets to be loaded
  109100. * @param onSuccess is a callback called when the task is successfully executed
  109101. * @param onError is a callback called if an error occurs
  109102. */
  109103. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109104. var _this = this;
  109105. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  109106. _this.loadedMeshes = meshes;
  109107. _this.loadedParticleSystems = particleSystems;
  109108. _this.loadedSkeletons = skeletons;
  109109. onSuccess();
  109110. }, null, function (scene, message, exception) {
  109111. onError(message, exception);
  109112. });
  109113. };
  109114. return MeshAssetTask;
  109115. }(AbstractAssetTask));
  109116. BABYLON.MeshAssetTask = MeshAssetTask;
  109117. /**
  109118. * Define a task used by {BABYLON.AssetsManager} to load text content
  109119. */
  109120. var TextFileAssetTask = /** @class */ (function (_super) {
  109121. __extends(TextFileAssetTask, _super);
  109122. /**
  109123. * Creates a new TextFileAssetTask object
  109124. * @param name defines the name of the task
  109125. * @param url defines the location of the file to load
  109126. */
  109127. function TextFileAssetTask(
  109128. /**
  109129. * Defines the name of the task
  109130. */
  109131. name,
  109132. /**
  109133. * Defines the location of the file to load
  109134. */
  109135. url) {
  109136. var _this = _super.call(this, name) || this;
  109137. _this.name = name;
  109138. _this.url = url;
  109139. return _this;
  109140. }
  109141. /**
  109142. * Execute the current task
  109143. * @param scene defines the scene where you want your assets to be loaded
  109144. * @param onSuccess is a callback called when the task is successfully executed
  109145. * @param onError is a callback called if an error occurs
  109146. */
  109147. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109148. var _this = this;
  109149. scene._loadFile(this.url, function (data) {
  109150. _this.text = data;
  109151. onSuccess();
  109152. }, undefined, false, false, function (request, exception) {
  109153. if (request) {
  109154. onError(request.status + " " + request.statusText, exception);
  109155. }
  109156. });
  109157. };
  109158. return TextFileAssetTask;
  109159. }(AbstractAssetTask));
  109160. BABYLON.TextFileAssetTask = TextFileAssetTask;
  109161. /**
  109162. * Define a task used by {BABYLON.AssetsManager} to load binary data
  109163. */
  109164. var BinaryFileAssetTask = /** @class */ (function (_super) {
  109165. __extends(BinaryFileAssetTask, _super);
  109166. /**
  109167. * Creates a new BinaryFileAssetTask object
  109168. * @param name defines the name of the new task
  109169. * @param url defines the location of the file to load
  109170. */
  109171. function BinaryFileAssetTask(
  109172. /**
  109173. * Defines the name of the task
  109174. */
  109175. name,
  109176. /**
  109177. * Defines the location of the file to load
  109178. */
  109179. url) {
  109180. var _this = _super.call(this, name) || this;
  109181. _this.name = name;
  109182. _this.url = url;
  109183. return _this;
  109184. }
  109185. /**
  109186. * Execute the current task
  109187. * @param scene defines the scene where you want your assets to be loaded
  109188. * @param onSuccess is a callback called when the task is successfully executed
  109189. * @param onError is a callback called if an error occurs
  109190. */
  109191. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109192. var _this = this;
  109193. scene._loadFile(this.url, function (data) {
  109194. _this.data = data;
  109195. onSuccess();
  109196. }, undefined, true, true, function (request, exception) {
  109197. if (request) {
  109198. onError(request.status + " " + request.statusText, exception);
  109199. }
  109200. });
  109201. };
  109202. return BinaryFileAssetTask;
  109203. }(AbstractAssetTask));
  109204. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  109205. /**
  109206. * Define a task used by {BABYLON.AssetsManager} to load images
  109207. */
  109208. var ImageAssetTask = /** @class */ (function (_super) {
  109209. __extends(ImageAssetTask, _super);
  109210. /**
  109211. * Creates a new ImageAssetTask
  109212. * @param name defines the name of the task
  109213. * @param url defines the location of the image to load
  109214. */
  109215. function ImageAssetTask(
  109216. /**
  109217. * Defines the name of the task
  109218. */
  109219. name,
  109220. /**
  109221. * Defines the location of the image to load
  109222. */
  109223. url) {
  109224. var _this = _super.call(this, name) || this;
  109225. _this.name = name;
  109226. _this.url = url;
  109227. return _this;
  109228. }
  109229. /**
  109230. * Execute the current task
  109231. * @param scene defines the scene where you want your assets to be loaded
  109232. * @param onSuccess is a callback called when the task is successfully executed
  109233. * @param onError is a callback called if an error occurs
  109234. */
  109235. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109236. var _this = this;
  109237. var img = new Image();
  109238. BABYLON.Tools.SetCorsBehavior(this.url, img);
  109239. img.onload = function () {
  109240. _this.image = img;
  109241. onSuccess();
  109242. };
  109243. img.onerror = function (err) {
  109244. onError("Error loading image", err);
  109245. };
  109246. img.src = this.url;
  109247. };
  109248. return ImageAssetTask;
  109249. }(AbstractAssetTask));
  109250. BABYLON.ImageAssetTask = ImageAssetTask;
  109251. /**
  109252. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  109253. */
  109254. var TextureAssetTask = /** @class */ (function (_super) {
  109255. __extends(TextureAssetTask, _super);
  109256. /**
  109257. * Creates a new TextureAssetTask object
  109258. * @param name defines the name of the task
  109259. * @param url defines the location of the file to load
  109260. * @param noMipmap defines if mipmap should not be generated (default is false)
  109261. * @param invertY defines if texture must be inverted on Y axis (default is false)
  109262. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  109263. */
  109264. function TextureAssetTask(
  109265. /**
  109266. * Defines the name of the task
  109267. */
  109268. name,
  109269. /**
  109270. * Defines the location of the file to load
  109271. */
  109272. url,
  109273. /**
  109274. * Defines if mipmap should not be generated (default is false)
  109275. */
  109276. noMipmap,
  109277. /**
  109278. * Defines if texture must be inverted on Y axis (default is false)
  109279. */
  109280. invertY,
  109281. /**
  109282. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  109283. */
  109284. samplingMode) {
  109285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109286. var _this = _super.call(this, name) || this;
  109287. _this.name = name;
  109288. _this.url = url;
  109289. _this.noMipmap = noMipmap;
  109290. _this.invertY = invertY;
  109291. _this.samplingMode = samplingMode;
  109292. return _this;
  109293. }
  109294. /**
  109295. * Execute the current task
  109296. * @param scene defines the scene where you want your assets to be loaded
  109297. * @param onSuccess is a callback called when the task is successfully executed
  109298. * @param onError is a callback called if an error occurs
  109299. */
  109300. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109301. var onload = function () {
  109302. onSuccess();
  109303. };
  109304. var onerror = function (message, exception) {
  109305. onError(message, exception);
  109306. };
  109307. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  109308. };
  109309. return TextureAssetTask;
  109310. }(AbstractAssetTask));
  109311. BABYLON.TextureAssetTask = TextureAssetTask;
  109312. /**
  109313. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  109314. */
  109315. var CubeTextureAssetTask = /** @class */ (function (_super) {
  109316. __extends(CubeTextureAssetTask, _super);
  109317. /**
  109318. * Creates a new CubeTextureAssetTask
  109319. * @param name defines the name of the task
  109320. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  109321. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  109322. * @param noMipmap defines if mipmaps should not be generated (default is false)
  109323. * @param files defines the explicit list of files (undefined by default)
  109324. */
  109325. function CubeTextureAssetTask(
  109326. /**
  109327. * Defines the name of the task
  109328. */
  109329. name,
  109330. /**
  109331. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  109332. */
  109333. url,
  109334. /**
  109335. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  109336. */
  109337. extensions,
  109338. /**
  109339. * Defines if mipmaps should not be generated (default is false)
  109340. */
  109341. noMipmap,
  109342. /**
  109343. * Defines the explicit list of files (undefined by default)
  109344. */
  109345. files) {
  109346. var _this = _super.call(this, name) || this;
  109347. _this.name = name;
  109348. _this.url = url;
  109349. _this.extensions = extensions;
  109350. _this.noMipmap = noMipmap;
  109351. _this.files = files;
  109352. return _this;
  109353. }
  109354. /**
  109355. * Execute the current task
  109356. * @param scene defines the scene where you want your assets to be loaded
  109357. * @param onSuccess is a callback called when the task is successfully executed
  109358. * @param onError is a callback called if an error occurs
  109359. */
  109360. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109361. var onload = function () {
  109362. onSuccess();
  109363. };
  109364. var onerror = function (message, exception) {
  109365. onError(message, exception);
  109366. };
  109367. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  109368. };
  109369. return CubeTextureAssetTask;
  109370. }(AbstractAssetTask));
  109371. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  109372. /**
  109373. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  109374. */
  109375. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  109376. __extends(HDRCubeTextureAssetTask, _super);
  109377. /**
  109378. * Creates a new HDRCubeTextureAssetTask object
  109379. * @param name defines the name of the task
  109380. * @param url defines the location of the file to load
  109381. * @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.
  109382. * @param noMipmap defines if mipmaps should not be generated (default is false)
  109383. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  109384. * @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)
  109385. * @param reserved Internal use only
  109386. */
  109387. function HDRCubeTextureAssetTask(
  109388. /**
  109389. * Defines the name of the task
  109390. */
  109391. name,
  109392. /**
  109393. * Defines the location of the file to load
  109394. */
  109395. url,
  109396. /**
  109397. * Defines the desired size (the more it increases the longer the generation will be)
  109398. */
  109399. size,
  109400. /**
  109401. * Defines if mipmaps should not be generated (default is false)
  109402. */
  109403. noMipmap,
  109404. /**
  109405. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  109406. */
  109407. generateHarmonics,
  109408. /**
  109409. * 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)
  109410. */
  109411. gammaSpace,
  109412. /**
  109413. * Internal Use Only
  109414. */
  109415. reserved) {
  109416. if (noMipmap === void 0) { noMipmap = false; }
  109417. if (generateHarmonics === void 0) { generateHarmonics = true; }
  109418. if (gammaSpace === void 0) { gammaSpace = false; }
  109419. if (reserved === void 0) { reserved = false; }
  109420. var _this = _super.call(this, name) || this;
  109421. _this.name = name;
  109422. _this.url = url;
  109423. _this.size = size;
  109424. _this.noMipmap = noMipmap;
  109425. _this.generateHarmonics = generateHarmonics;
  109426. _this.gammaSpace = gammaSpace;
  109427. _this.reserved = reserved;
  109428. return _this;
  109429. }
  109430. /**
  109431. * Execute the current task
  109432. * @param scene defines the scene where you want your assets to be loaded
  109433. * @param onSuccess is a callback called when the task is successfully executed
  109434. * @param onError is a callback called if an error occurs
  109435. */
  109436. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  109437. var onload = function () {
  109438. onSuccess();
  109439. };
  109440. var onerror = function (message, exception) {
  109441. onError(message, exception);
  109442. };
  109443. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  109444. };
  109445. return HDRCubeTextureAssetTask;
  109446. }(AbstractAssetTask));
  109447. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  109448. /**
  109449. * This class can be used to easily import assets into a scene
  109450. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  109451. */
  109452. var AssetsManager = /** @class */ (function () {
  109453. /**
  109454. * Creates a new AssetsManager
  109455. * @param scene defines the scene to work on
  109456. */
  109457. function AssetsManager(scene) {
  109458. this._isLoading = false;
  109459. this._tasks = new Array();
  109460. this._waitingTasksCount = 0;
  109461. this._totalTasksCount = 0;
  109462. /**
  109463. * Observable called when all tasks are processed
  109464. */
  109465. this.onTaskSuccessObservable = new BABYLON.Observable();
  109466. /**
  109467. * Observable called when a task had an error
  109468. */
  109469. this.onTaskErrorObservable = new BABYLON.Observable();
  109470. /**
  109471. * Observable called when a task is successful
  109472. */
  109473. this.onTasksDoneObservable = new BABYLON.Observable();
  109474. /**
  109475. * Observable called when a task is done (whatever the result is)
  109476. */
  109477. this.onProgressObservable = new BABYLON.Observable();
  109478. /**
  109479. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  109480. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  109481. */
  109482. this.useDefaultLoadingScreen = true;
  109483. this._scene = scene;
  109484. }
  109485. /**
  109486. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  109487. * @param taskName defines the name of the new task
  109488. * @param meshesNames defines the name of meshes to load
  109489. * @param rootUrl defines the root url to use to locate files
  109490. * @param sceneFilename defines the filename of the scene file
  109491. * @returns a new {BABYLON.MeshAssetTask} object
  109492. */
  109493. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  109494. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  109495. this._tasks.push(task);
  109496. return task;
  109497. };
  109498. /**
  109499. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  109500. * @param taskName defines the name of the new task
  109501. * @param url defines the url of the file to load
  109502. * @returns a new {BABYLON.TextFileAssetTask} object
  109503. */
  109504. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  109505. var task = new TextFileAssetTask(taskName, url);
  109506. this._tasks.push(task);
  109507. return task;
  109508. };
  109509. /**
  109510. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  109511. * @param taskName defines the name of the new task
  109512. * @param url defines the url of the file to load
  109513. * @returns a new {BABYLON.BinaryFileAssetTask} object
  109514. */
  109515. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  109516. var task = new BinaryFileAssetTask(taskName, url);
  109517. this._tasks.push(task);
  109518. return task;
  109519. };
  109520. /**
  109521. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  109522. * @param taskName defines the name of the new task
  109523. * @param url defines the url of the file to load
  109524. * @returns a new {BABYLON.ImageAssetTask} object
  109525. */
  109526. AssetsManager.prototype.addImageTask = function (taskName, url) {
  109527. var task = new ImageAssetTask(taskName, url);
  109528. this._tasks.push(task);
  109529. return task;
  109530. };
  109531. /**
  109532. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  109533. * @param taskName defines the name of the new task
  109534. * @param url defines the url of the file to load
  109535. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109536. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  109537. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  109538. * @returns a new {BABYLON.TextureAssetTask} object
  109539. */
  109540. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  109541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109542. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  109543. this._tasks.push(task);
  109544. return task;
  109545. };
  109546. /**
  109547. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  109548. * @param taskName defines the name of the new task
  109549. * @param url defines the url of the file to load
  109550. * @param extensions defines the extension to use to load the cube map (can be null)
  109551. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109552. * @param files defines the list of files to load (can be null)
  109553. * @returns a new {BABYLON.CubeTextureAssetTask} object
  109554. */
  109555. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  109556. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  109557. this._tasks.push(task);
  109558. return task;
  109559. };
  109560. /**
  109561. *
  109562. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  109563. * @param taskName defines the name of the new task
  109564. * @param url defines the url of the file to load
  109565. * @param size defines the size you want for the cubemap (can be null)
  109566. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109567. * @param generateHarmonics defines if you want to automatically generate (true by default)
  109568. * @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)
  109569. * @param reserved Internal use only
  109570. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  109571. */
  109572. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  109573. if (noMipmap === void 0) { noMipmap = false; }
  109574. if (generateHarmonics === void 0) { generateHarmonics = true; }
  109575. if (gammaSpace === void 0) { gammaSpace = false; }
  109576. if (reserved === void 0) { reserved = false; }
  109577. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  109578. this._tasks.push(task);
  109579. return task;
  109580. };
  109581. /**
  109582. * Remove a task from the assets manager.
  109583. * @param task the task to remove
  109584. */
  109585. AssetsManager.prototype.removeTask = function (task) {
  109586. var index = this._tasks.indexOf(task);
  109587. if (index > -1) {
  109588. this._tasks.splice(index, 1);
  109589. }
  109590. };
  109591. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  109592. this._waitingTasksCount--;
  109593. try {
  109594. if (this.onProgress) {
  109595. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  109596. }
  109597. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  109598. }
  109599. catch (e) {
  109600. BABYLON.Tools.Error("Error running progress callbacks.");
  109601. console.log(e);
  109602. }
  109603. if (this._waitingTasksCount === 0) {
  109604. try {
  109605. if (this.onFinish) {
  109606. this.onFinish(this._tasks);
  109607. }
  109608. // Let's remove successfull tasks
  109609. var currentTasks = this._tasks.slice();
  109610. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  109611. var task = currentTasks_1[_i];
  109612. if (task.taskState === AssetTaskState.DONE) {
  109613. var index = this._tasks.indexOf(task);
  109614. if (index > -1) {
  109615. this._tasks.splice(index, 1);
  109616. }
  109617. }
  109618. }
  109619. this.onTasksDoneObservable.notifyObservers(this._tasks);
  109620. }
  109621. catch (e) {
  109622. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  109623. console.log(e);
  109624. }
  109625. this._isLoading = false;
  109626. this._scene.getEngine().hideLoadingUI();
  109627. }
  109628. };
  109629. AssetsManager.prototype._runTask = function (task) {
  109630. var _this = this;
  109631. var done = function () {
  109632. try {
  109633. if (_this.onTaskSuccess) {
  109634. _this.onTaskSuccess(task);
  109635. }
  109636. _this.onTaskSuccessObservable.notifyObservers(task);
  109637. _this._decreaseWaitingTasksCount(task);
  109638. }
  109639. catch (e) {
  109640. error("Error executing task success callbacks", e);
  109641. }
  109642. };
  109643. var error = function (message, exception) {
  109644. task._setErrorObject(message, exception);
  109645. if (_this.onTaskError) {
  109646. _this.onTaskError(task);
  109647. }
  109648. _this.onTaskErrorObservable.notifyObservers(task);
  109649. _this._decreaseWaitingTasksCount(task);
  109650. };
  109651. task.run(this._scene, done, error);
  109652. };
  109653. /**
  109654. * Reset the {BABYLON.AssetsManager} and remove all tasks
  109655. * @return the current instance of the {BABYLON.AssetsManager}
  109656. */
  109657. AssetsManager.prototype.reset = function () {
  109658. this._isLoading = false;
  109659. this._tasks = new Array();
  109660. return this;
  109661. };
  109662. /**
  109663. * Start the loading process
  109664. * @return the current instance of the {BABYLON.AssetsManager}
  109665. */
  109666. AssetsManager.prototype.load = function () {
  109667. if (this._isLoading) {
  109668. return this;
  109669. }
  109670. this._isLoading = true;
  109671. this._waitingTasksCount = this._tasks.length;
  109672. this._totalTasksCount = this._tasks.length;
  109673. if (this._waitingTasksCount === 0) {
  109674. this._isLoading = false;
  109675. if (this.onFinish) {
  109676. this.onFinish(this._tasks);
  109677. }
  109678. this.onTasksDoneObservable.notifyObservers(this._tasks);
  109679. return this;
  109680. }
  109681. if (this.useDefaultLoadingScreen) {
  109682. this._scene.getEngine().displayLoadingUI();
  109683. }
  109684. for (var index = 0; index < this._tasks.length; index++) {
  109685. var task = this._tasks[index];
  109686. if (task.taskState === AssetTaskState.INIT) {
  109687. this._runTask(task);
  109688. }
  109689. }
  109690. return this;
  109691. };
  109692. return AssetsManager;
  109693. }());
  109694. BABYLON.AssetsManager = AssetsManager;
  109695. })(BABYLON || (BABYLON = {}));
  109696. //# sourceMappingURL=babylon.assetsManager.js.map
  109697. var BABYLON;
  109698. (function (BABYLON) {
  109699. var serializedGeometries = [];
  109700. var serializeGeometry = function (geometry, serializationGeometries) {
  109701. if (serializedGeometries[geometry.id]) {
  109702. return;
  109703. }
  109704. if (geometry.doNotSerialize) {
  109705. return;
  109706. }
  109707. if (geometry instanceof BABYLON.BoxGeometry) {
  109708. serializationGeometries.boxes.push(geometry.serialize());
  109709. }
  109710. else if (geometry instanceof BABYLON.SphereGeometry) {
  109711. serializationGeometries.spheres.push(geometry.serialize());
  109712. }
  109713. else if (geometry instanceof BABYLON.CylinderGeometry) {
  109714. serializationGeometries.cylinders.push(geometry.serialize());
  109715. }
  109716. else if (geometry instanceof BABYLON.TorusGeometry) {
  109717. serializationGeometries.toruses.push(geometry.serialize());
  109718. }
  109719. else if (geometry instanceof BABYLON.GroundGeometry) {
  109720. serializationGeometries.grounds.push(geometry.serialize());
  109721. }
  109722. else if (geometry instanceof BABYLON.Plane) {
  109723. serializationGeometries.planes.push(geometry.serialize());
  109724. }
  109725. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  109726. serializationGeometries.torusKnots.push(geometry.serialize());
  109727. }
  109728. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  109729. throw new Error("Unknown primitive type");
  109730. }
  109731. else {
  109732. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  109733. }
  109734. serializedGeometries[geometry.id] = true;
  109735. };
  109736. var serializeMesh = function (mesh, serializationScene) {
  109737. var serializationObject = {};
  109738. // Geometry
  109739. var geometry = mesh._geometry;
  109740. if (geometry) {
  109741. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  109742. // 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
  109743. serializeGeometry(geometry, serializationScene.geometries);
  109744. }
  109745. }
  109746. // Custom
  109747. if (mesh.serialize) {
  109748. mesh.serialize(serializationObject);
  109749. }
  109750. return serializationObject;
  109751. };
  109752. var finalizeSingleMesh = function (mesh, serializationObject) {
  109753. //only works if the mesh is already loaded
  109754. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109755. //serialize material
  109756. if (mesh.material) {
  109757. if (mesh.material instanceof BABYLON.MultiMaterial) {
  109758. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  109759. serializationObject.materials = serializationObject.materials || [];
  109760. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  109761. serializationObject.multiMaterials.push(mesh.material.serialize());
  109762. var _loop_1 = function (submaterial) {
  109763. if (submaterial) {
  109764. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  109765. serializationObject.materials.push(submaterial.serialize());
  109766. }
  109767. }
  109768. };
  109769. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  109770. var submaterial = _a[_i];
  109771. _loop_1(submaterial);
  109772. }
  109773. }
  109774. }
  109775. else {
  109776. serializationObject.materials = serializationObject.materials || [];
  109777. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  109778. serializationObject.materials.push(mesh.material.serialize());
  109779. }
  109780. }
  109781. }
  109782. //serialize geometry
  109783. var geometry = mesh._geometry;
  109784. if (geometry) {
  109785. if (!serializationObject.geometries) {
  109786. serializationObject.geometries = {};
  109787. serializationObject.geometries.boxes = [];
  109788. serializationObject.geometries.spheres = [];
  109789. serializationObject.geometries.cylinders = [];
  109790. serializationObject.geometries.toruses = [];
  109791. serializationObject.geometries.grounds = [];
  109792. serializationObject.geometries.planes = [];
  109793. serializationObject.geometries.torusKnots = [];
  109794. serializationObject.geometries.vertexData = [];
  109795. }
  109796. serializeGeometry(geometry, serializationObject.geometries);
  109797. }
  109798. // Skeletons
  109799. if (mesh.skeleton) {
  109800. serializationObject.skeletons = serializationObject.skeletons || [];
  109801. serializationObject.skeletons.push(mesh.skeleton.serialize());
  109802. }
  109803. //serialize the actual mesh
  109804. serializationObject.meshes = serializationObject.meshes || [];
  109805. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109806. }
  109807. };
  109808. /**
  109809. * Class used to serialize a scene into a string
  109810. */
  109811. var SceneSerializer = /** @class */ (function () {
  109812. function SceneSerializer() {
  109813. }
  109814. /**
  109815. * Clear cache used by a previous serialization
  109816. */
  109817. SceneSerializer.ClearCache = function () {
  109818. serializedGeometries = [];
  109819. };
  109820. /**
  109821. * Serialize a scene into a JSON compatible object
  109822. * @param scene defines the scene to serialize
  109823. * @returns a JSON compatible object
  109824. */
  109825. SceneSerializer.Serialize = function (scene) {
  109826. var serializationObject = {};
  109827. SceneSerializer.ClearCache();
  109828. // Scene
  109829. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  109830. serializationObject.autoClear = scene.autoClear;
  109831. serializationObject.clearColor = scene.clearColor.asArray();
  109832. serializationObject.ambientColor = scene.ambientColor.asArray();
  109833. serializationObject.gravity = scene.gravity.asArray();
  109834. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  109835. serializationObject.workerCollisions = scene.workerCollisions;
  109836. // Fog
  109837. if (scene.fogMode && scene.fogMode !== 0) {
  109838. serializationObject.fogMode = scene.fogMode;
  109839. serializationObject.fogColor = scene.fogColor.asArray();
  109840. serializationObject.fogStart = scene.fogStart;
  109841. serializationObject.fogEnd = scene.fogEnd;
  109842. serializationObject.fogDensity = scene.fogDensity;
  109843. }
  109844. //Physics
  109845. if (scene.isPhysicsEnabled()) {
  109846. var physicEngine = scene.getPhysicsEngine();
  109847. if (physicEngine) {
  109848. serializationObject.physicsEnabled = true;
  109849. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  109850. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  109851. }
  109852. }
  109853. // Metadata
  109854. if (scene.metadata) {
  109855. serializationObject.metadata = scene.metadata;
  109856. }
  109857. // Morph targets
  109858. serializationObject.morphTargetManagers = [];
  109859. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  109860. var abstractMesh = _a[_i];
  109861. var manager = abstractMesh.morphTargetManager;
  109862. if (manager) {
  109863. serializationObject.morphTargetManagers.push(manager.serialize());
  109864. }
  109865. }
  109866. // Lights
  109867. serializationObject.lights = [];
  109868. var index;
  109869. var light;
  109870. for (index = 0; index < scene.lights.length; index++) {
  109871. light = scene.lights[index];
  109872. if (!light.doNotSerialize) {
  109873. serializationObject.lights.push(light.serialize());
  109874. }
  109875. }
  109876. // Cameras
  109877. serializationObject.cameras = [];
  109878. for (index = 0; index < scene.cameras.length; index++) {
  109879. var camera = scene.cameras[index];
  109880. if (!camera.doNotSerialize) {
  109881. serializationObject.cameras.push(camera.serialize());
  109882. }
  109883. }
  109884. if (scene.activeCamera) {
  109885. serializationObject.activeCameraID = scene.activeCamera.id;
  109886. }
  109887. // Animations
  109888. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  109889. // Materials
  109890. serializationObject.materials = [];
  109891. serializationObject.multiMaterials = [];
  109892. var material;
  109893. for (index = 0; index < scene.materials.length; index++) {
  109894. material = scene.materials[index];
  109895. if (!material.doNotSerialize) {
  109896. serializationObject.materials.push(material.serialize());
  109897. }
  109898. }
  109899. // MultiMaterials
  109900. serializationObject.multiMaterials = [];
  109901. for (index = 0; index < scene.multiMaterials.length; index++) {
  109902. var multiMaterial = scene.multiMaterials[index];
  109903. serializationObject.multiMaterials.push(multiMaterial.serialize());
  109904. }
  109905. // Environment texture
  109906. if (scene.environmentTexture) {
  109907. serializationObject.environmentTexture = scene.environmentTexture.name;
  109908. }
  109909. // Skeletons
  109910. serializationObject.skeletons = [];
  109911. for (index = 0; index < scene.skeletons.length; index++) {
  109912. var skeleton = scene.skeletons[index];
  109913. if (!skeleton.doNotSerialize) {
  109914. serializationObject.skeletons.push(skeleton.serialize());
  109915. }
  109916. }
  109917. // Transform nodes
  109918. serializationObject.transformNodes = [];
  109919. for (index = 0; index < scene.transformNodes.length; index++) {
  109920. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  109921. }
  109922. // Geometries
  109923. serializationObject.geometries = {};
  109924. serializationObject.geometries.boxes = [];
  109925. serializationObject.geometries.spheres = [];
  109926. serializationObject.geometries.cylinders = [];
  109927. serializationObject.geometries.toruses = [];
  109928. serializationObject.geometries.grounds = [];
  109929. serializationObject.geometries.planes = [];
  109930. serializationObject.geometries.torusKnots = [];
  109931. serializationObject.geometries.vertexData = [];
  109932. serializedGeometries = [];
  109933. var geometries = scene.getGeometries();
  109934. for (index = 0; index < geometries.length; index++) {
  109935. var geometry = geometries[index];
  109936. if (geometry.isReady()) {
  109937. serializeGeometry(geometry, serializationObject.geometries);
  109938. }
  109939. }
  109940. // Meshes
  109941. serializationObject.meshes = [];
  109942. for (index = 0; index < scene.meshes.length; index++) {
  109943. var abstractMesh = scene.meshes[index];
  109944. if (abstractMesh instanceof BABYLON.Mesh) {
  109945. var mesh = abstractMesh;
  109946. if (!mesh.doNotSerialize) {
  109947. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109948. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109949. }
  109950. }
  109951. }
  109952. }
  109953. // Particles Systems
  109954. serializationObject.particleSystems = [];
  109955. for (index = 0; index < scene.particleSystems.length; index++) {
  109956. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  109957. }
  109958. // Action Manager
  109959. if (scene.actionManager) {
  109960. serializationObject.actions = scene.actionManager.serialize("scene");
  109961. }
  109962. // Components
  109963. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  109964. var component = _c[_b];
  109965. component.serialize(serializationObject);
  109966. }
  109967. return serializationObject;
  109968. };
  109969. /**
  109970. * Serialize a mesh into a JSON compatible object
  109971. * @param toSerialize defines the mesh to serialize
  109972. * @param withParents defines if parents must be serialized as well
  109973. * @param withChildren defines if children must be serialized as well
  109974. * @returns a JSON compatible object
  109975. */
  109976. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  109977. if (withParents === void 0) { withParents = false; }
  109978. if (withChildren === void 0) { withChildren = false; }
  109979. var serializationObject = {};
  109980. SceneSerializer.ClearCache();
  109981. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  109982. if (withParents || withChildren) {
  109983. //deliberate for loop! not for each, appended should be processed as well.
  109984. for (var i = 0; i < toSerialize.length; ++i) {
  109985. if (withChildren) {
  109986. toSerialize[i].getDescendants().forEach(function (node) {
  109987. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  109988. toSerialize.push(node);
  109989. }
  109990. });
  109991. }
  109992. //make sure the array doesn't contain the object already
  109993. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  109994. toSerialize.push(toSerialize[i].parent);
  109995. }
  109996. }
  109997. }
  109998. toSerialize.forEach(function (mesh) {
  109999. finalizeSingleMesh(mesh, serializationObject);
  110000. });
  110001. return serializationObject;
  110002. };
  110003. return SceneSerializer;
  110004. }());
  110005. BABYLON.SceneSerializer = SceneSerializer;
  110006. })(BABYLON || (BABYLON = {}));
  110007. //# sourceMappingURL=babylon.sceneSerializer.js.map
  110008. var BABYLON;
  110009. (function (BABYLON) {
  110010. /**
  110011. * Class used to generate realtime reflection / refraction cube textures
  110012. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  110013. */
  110014. var ReflectionProbe = /** @class */ (function () {
  110015. /**
  110016. * Creates a new reflection probe
  110017. * @param name defines the name of the probe
  110018. * @param size defines the texture resolution (for each face)
  110019. * @param scene defines the hosting scene
  110020. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  110021. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  110022. */
  110023. function ReflectionProbe(
  110024. /** defines the name of the probe */
  110025. name, size, scene, generateMipMaps, useFloat) {
  110026. if (generateMipMaps === void 0) { generateMipMaps = true; }
  110027. if (useFloat === void 0) { useFloat = false; }
  110028. var _this = this;
  110029. this.name = name;
  110030. this._viewMatrix = BABYLON.Matrix.Identity();
  110031. this._target = BABYLON.Vector3.Zero();
  110032. this._add = BABYLON.Vector3.Zero();
  110033. this._invertYAxis = false;
  110034. /** Gets or sets probe position (center of the cube map) */
  110035. this.position = BABYLON.Vector3.Zero();
  110036. this._scene = scene;
  110037. // Create the scene field if not exist.
  110038. if (!this._scene.reflectionProbes) {
  110039. this._scene.reflectionProbes = new Array();
  110040. }
  110041. this._scene.reflectionProbes.push(this);
  110042. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  110043. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  110044. switch (faceIndex) {
  110045. case 0:
  110046. _this._add.copyFromFloats(1, 0, 0);
  110047. break;
  110048. case 1:
  110049. _this._add.copyFromFloats(-1, 0, 0);
  110050. break;
  110051. case 2:
  110052. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  110053. break;
  110054. case 3:
  110055. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  110056. break;
  110057. case 4:
  110058. _this._add.copyFromFloats(0, 0, 1);
  110059. break;
  110060. case 5:
  110061. _this._add.copyFromFloats(0, 0, -1);
  110062. break;
  110063. }
  110064. if (_this._attachedMesh) {
  110065. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  110066. }
  110067. _this.position.addToRef(_this._add, _this._target);
  110068. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  110069. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  110070. scene._forcedViewPosition = _this.position;
  110071. });
  110072. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  110073. scene._forcedViewPosition = null;
  110074. scene.updateTransformMatrix(true);
  110075. });
  110076. if (scene.activeCamera) {
  110077. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  110078. }
  110079. }
  110080. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  110081. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  110082. get: function () {
  110083. return this._renderTargetTexture.samples;
  110084. },
  110085. set: function (value) {
  110086. this._renderTargetTexture.samples = value;
  110087. },
  110088. enumerable: true,
  110089. configurable: true
  110090. });
  110091. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  110092. /** Gets or sets the refresh rate to use (on every frame by default) */
  110093. get: function () {
  110094. return this._renderTargetTexture.refreshRate;
  110095. },
  110096. set: function (value) {
  110097. this._renderTargetTexture.refreshRate = value;
  110098. },
  110099. enumerable: true,
  110100. configurable: true
  110101. });
  110102. /**
  110103. * Gets the hosting scene
  110104. * @returns a Scene
  110105. */
  110106. ReflectionProbe.prototype.getScene = function () {
  110107. return this._scene;
  110108. };
  110109. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  110110. /** Gets the internal CubeTexture used to render to */
  110111. get: function () {
  110112. return this._renderTargetTexture;
  110113. },
  110114. enumerable: true,
  110115. configurable: true
  110116. });
  110117. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  110118. /** Gets the list of meshes to render */
  110119. get: function () {
  110120. return this._renderTargetTexture.renderList;
  110121. },
  110122. enumerable: true,
  110123. configurable: true
  110124. });
  110125. /**
  110126. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  110127. * @param mesh defines the mesh to attach to
  110128. */
  110129. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  110130. this._attachedMesh = mesh;
  110131. };
  110132. /**
  110133. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  110134. * @param renderingGroupId The rendering group id corresponding to its index
  110135. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  110136. */
  110137. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  110138. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  110139. };
  110140. /**
  110141. * Clean all associated resources
  110142. */
  110143. ReflectionProbe.prototype.dispose = function () {
  110144. var index = this._scene.reflectionProbes.indexOf(this);
  110145. if (index !== -1) {
  110146. // Remove from the scene if found
  110147. this._scene.reflectionProbes.splice(index, 1);
  110148. }
  110149. if (this._renderTargetTexture) {
  110150. this._renderTargetTexture.dispose();
  110151. this._renderTargetTexture = null;
  110152. }
  110153. };
  110154. return ReflectionProbe;
  110155. }());
  110156. BABYLON.ReflectionProbe = ReflectionProbe;
  110157. })(BABYLON || (BABYLON = {}));
  110158. //# sourceMappingURL=babylon.reflectionProbe.js.map
  110159. var BABYLON;
  110160. (function (BABYLON) {
  110161. /**
  110162. * Defines the layer scene component responsible to manage any layers
  110163. * in a given scene.
  110164. */
  110165. var LayerSceneComponent = /** @class */ (function () {
  110166. /**
  110167. * Creates a new instance of the component for the given scene
  110168. * @param scene Defines the scene to register the component in
  110169. */
  110170. function LayerSceneComponent(scene) {
  110171. /**
  110172. * The component name helpfull to identify the component in the list of scene components.
  110173. */
  110174. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  110175. this.scene = scene;
  110176. this._engine = scene.getEngine();
  110177. scene.layers = new Array();
  110178. }
  110179. /**
  110180. * Registers the component in a given scene
  110181. */
  110182. LayerSceneComponent.prototype.register = function () {
  110183. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  110184. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  110185. };
  110186. /**
  110187. * Rebuilds the elements related to this component in case of
  110188. * context lost for instance.
  110189. */
  110190. LayerSceneComponent.prototype.rebuild = function () {
  110191. var layers = this.scene.layers;
  110192. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  110193. var layer = layers_1[_i];
  110194. layer._rebuild();
  110195. }
  110196. };
  110197. /**
  110198. * Disposes the component and the associated ressources.
  110199. */
  110200. LayerSceneComponent.prototype.dispose = function () {
  110201. var layers = this.scene.layers;
  110202. while (layers.length) {
  110203. layers[0].dispose();
  110204. }
  110205. };
  110206. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  110207. var layers = this.scene.layers;
  110208. if (layers.length) {
  110209. this._engine.setDepthBuffer(false);
  110210. var cameraLayerMask = camera.layerMask;
  110211. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  110212. var layer = layers_2[_i];
  110213. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  110214. layer.render();
  110215. }
  110216. }
  110217. this._engine.setDepthBuffer(true);
  110218. }
  110219. };
  110220. LayerSceneComponent.prototype._drawBackground = function (camera) {
  110221. this._draw(camera, true);
  110222. };
  110223. LayerSceneComponent.prototype._drawForeground = function (camera) {
  110224. this._draw(camera, false);
  110225. };
  110226. return LayerSceneComponent;
  110227. }());
  110228. BABYLON.LayerSceneComponent = LayerSceneComponent;
  110229. })(BABYLON || (BABYLON = {}));
  110230. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  110231. var BABYLON;
  110232. (function (BABYLON) {
  110233. /**
  110234. * This represents a full screen 2d layer.
  110235. * This can be usefull to display a picture in the background of your scene for instance.
  110236. * @see https://www.babylonjs-playground.com/#08A2BS#1
  110237. */
  110238. var Layer = /** @class */ (function () {
  110239. /**
  110240. * Instantiates a new layer.
  110241. * This represents a full screen 2d layer.
  110242. * This can be usefull to display a picture in the background of your scene for instance.
  110243. * @see https://www.babylonjs-playground.com/#08A2BS#1
  110244. * @param name Define the name of the layer in the scene
  110245. * @param imgUrl Define the url of the texture to display in the layer
  110246. * @param scene Define the scene the layer belongs to
  110247. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  110248. * @param color Defines a color for the layer
  110249. */
  110250. function Layer(
  110251. /**
  110252. * Define the name of the layer.
  110253. */
  110254. name, imgUrl, scene, isBackground, color) {
  110255. this.name = name;
  110256. /**
  110257. * Define the scale of the layer in order to zoom in out of the texture.
  110258. */
  110259. this.scale = new BABYLON.Vector2(1, 1);
  110260. /**
  110261. * Define an offset for the layer in order to shift the texture.
  110262. */
  110263. this.offset = new BABYLON.Vector2(0, 0);
  110264. /**
  110265. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  110266. */
  110267. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  110268. /**
  110269. * Define a mask to restrict the layer to only some of the scene cameras.
  110270. */
  110271. this.layerMask = 0x0FFFFFFF;
  110272. this._vertexBuffers = {};
  110273. /**
  110274. * An event triggered when the layer is disposed.
  110275. */
  110276. this.onDisposeObservable = new BABYLON.Observable();
  110277. /**
  110278. * An event triggered before rendering the scene
  110279. */
  110280. this.onBeforeRenderObservable = new BABYLON.Observable();
  110281. /**
  110282. * An event triggered after rendering the scene
  110283. */
  110284. this.onAfterRenderObservable = new BABYLON.Observable();
  110285. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  110286. this.isBackground = isBackground === undefined ? true : isBackground;
  110287. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  110288. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  110289. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  110290. if (!layerComponent) {
  110291. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  110292. this._scene._addComponent(layerComponent);
  110293. }
  110294. this._scene.layers.push(this);
  110295. var engine = this._scene.getEngine();
  110296. // VBO
  110297. var vertices = [];
  110298. vertices.push(1, 1);
  110299. vertices.push(-1, 1);
  110300. vertices.push(-1, -1);
  110301. vertices.push(1, -1);
  110302. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  110303. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  110304. this._createIndexBuffer();
  110305. // Effects
  110306. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  110307. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  110308. }
  110309. Object.defineProperty(Layer.prototype, "onDispose", {
  110310. /**
  110311. * Back compatibility with callback before the onDisposeObservable existed.
  110312. * The set callback will be triggered when the layer has been disposed.
  110313. */
  110314. set: function (callback) {
  110315. if (this._onDisposeObserver) {
  110316. this.onDisposeObservable.remove(this._onDisposeObserver);
  110317. }
  110318. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  110319. },
  110320. enumerable: true,
  110321. configurable: true
  110322. });
  110323. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  110324. /**
  110325. * Back compatibility with callback before the onBeforeRenderObservable existed.
  110326. * The set callback will be triggered just before rendering the layer.
  110327. */
  110328. set: function (callback) {
  110329. if (this._onBeforeRenderObserver) {
  110330. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  110331. }
  110332. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  110333. },
  110334. enumerable: true,
  110335. configurable: true
  110336. });
  110337. Object.defineProperty(Layer.prototype, "onAfterRender", {
  110338. /**
  110339. * Back compatibility with callback before the onAfterRenderObservable existed.
  110340. * The set callback will be triggered just after rendering the layer.
  110341. */
  110342. set: function (callback) {
  110343. if (this._onAfterRenderObserver) {
  110344. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110345. }
  110346. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  110347. },
  110348. enumerable: true,
  110349. configurable: true
  110350. });
  110351. Layer.prototype._createIndexBuffer = function () {
  110352. var engine = this._scene.getEngine();
  110353. // Indices
  110354. var indices = [];
  110355. indices.push(0);
  110356. indices.push(1);
  110357. indices.push(2);
  110358. indices.push(0);
  110359. indices.push(2);
  110360. indices.push(3);
  110361. this._indexBuffer = engine.createIndexBuffer(indices);
  110362. };
  110363. /** @hidden */
  110364. Layer.prototype._rebuild = function () {
  110365. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110366. if (vb) {
  110367. vb._rebuild();
  110368. }
  110369. this._createIndexBuffer();
  110370. };
  110371. /**
  110372. * Renders the layer in the scene.
  110373. */
  110374. Layer.prototype.render = function () {
  110375. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  110376. // Check
  110377. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  110378. return;
  110379. var engine = this._scene.getEngine();
  110380. this.onBeforeRenderObservable.notifyObservers(this);
  110381. // Render
  110382. engine.enableEffect(currentEffect);
  110383. engine.setState(false);
  110384. // Texture
  110385. currentEffect.setTexture("textureSampler", this.texture);
  110386. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  110387. // Color
  110388. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  110389. // Scale / offset
  110390. currentEffect.setVector2("offset", this.offset);
  110391. currentEffect.setVector2("scale", this.scale);
  110392. // VBOs
  110393. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  110394. // Draw order
  110395. if (!this.alphaTest) {
  110396. engine.setAlphaMode(this.alphaBlendingMode);
  110397. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110398. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  110399. }
  110400. else {
  110401. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110402. }
  110403. this.onAfterRenderObservable.notifyObservers(this);
  110404. };
  110405. /**
  110406. * Disposes and releases the associated ressources.
  110407. */
  110408. Layer.prototype.dispose = function () {
  110409. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110410. if (vertexBuffer) {
  110411. vertexBuffer.dispose();
  110412. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  110413. }
  110414. if (this._indexBuffer) {
  110415. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  110416. this._indexBuffer = null;
  110417. }
  110418. if (this.texture) {
  110419. this.texture.dispose();
  110420. this.texture = null;
  110421. }
  110422. // Remove from scene
  110423. var index = this._scene.layers.indexOf(this);
  110424. this._scene.layers.splice(index, 1);
  110425. // Callback
  110426. this.onDisposeObservable.notifyObservers(this);
  110427. this.onDisposeObservable.clear();
  110428. this.onAfterRenderObservable.clear();
  110429. this.onBeforeRenderObservable.clear();
  110430. };
  110431. return Layer;
  110432. }());
  110433. BABYLON.Layer = Layer;
  110434. })(BABYLON || (BABYLON = {}));
  110435. //# sourceMappingURL=babylon.layer.js.map
  110436. var BABYLON;
  110437. (function (BABYLON) {
  110438. /**
  110439. * Class used to host texture specific utilities
  110440. */
  110441. var TextureTools = /** @class */ (function () {
  110442. function TextureTools() {
  110443. }
  110444. /**
  110445. * Uses the GPU to create a copy texture rescaled at a given size
  110446. * @param texture Texture to copy from
  110447. * @param width defines the desired width
  110448. * @param height defines the desired height
  110449. * @param useBilinearMode defines if bilinear mode has to be used
  110450. * @return the generated texture
  110451. */
  110452. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  110453. if (useBilinearMode === void 0) { useBilinearMode = true; }
  110454. var scene = texture.getScene();
  110455. var engine = scene.getEngine();
  110456. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  110457. rtt.wrapU = texture.wrapU;
  110458. rtt.wrapV = texture.wrapV;
  110459. rtt.uOffset = texture.uOffset;
  110460. rtt.vOffset = texture.vOffset;
  110461. rtt.uScale = texture.uScale;
  110462. rtt.vScale = texture.vScale;
  110463. rtt.uAng = texture.uAng;
  110464. rtt.vAng = texture.vAng;
  110465. rtt.wAng = texture.wAng;
  110466. rtt.coordinatesIndex = texture.coordinatesIndex;
  110467. rtt.level = texture.level;
  110468. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  110469. rtt._texture.isReady = false;
  110470. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110471. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110472. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  110473. passPostProcess.getEffect().executeWhenCompiled(function () {
  110474. passPostProcess.onApply = function (effect) {
  110475. effect.setTexture("textureSampler", texture);
  110476. };
  110477. var internalTexture = rtt.getInternalTexture();
  110478. if (internalTexture) {
  110479. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  110480. engine.unBindFramebuffer(internalTexture);
  110481. rtt.disposeFramebufferObjects();
  110482. passPostProcess.dispose();
  110483. internalTexture.isReady = true;
  110484. }
  110485. });
  110486. return rtt;
  110487. };
  110488. /**
  110489. * Gets an environment BRDF texture for a given scene
  110490. * @param scene defines the hosting scene
  110491. * @returns the environment BRDF texture
  110492. */
  110493. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  110494. if (!scene._environmentBRDFTexture) {
  110495. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110496. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110497. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110498. scene._environmentBRDFTexture = texture;
  110499. }
  110500. return scene._environmentBRDFTexture;
  110501. };
  110502. 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=";
  110503. return TextureTools;
  110504. }());
  110505. BABYLON.TextureTools = TextureTools;
  110506. })(BABYLON || (BABYLON = {}));
  110507. //# sourceMappingURL=babylon.textureTools.js.map
  110508. var BABYLON;
  110509. (function (BABYLON) {
  110510. /**
  110511. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  110512. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  110513. */
  110514. var FramingBehavior = /** @class */ (function () {
  110515. function FramingBehavior() {
  110516. this._mode = FramingBehavior.FitFrustumSidesMode;
  110517. this._radiusScale = 1.0;
  110518. this._positionScale = 0.5;
  110519. this._defaultElevation = 0.3;
  110520. this._elevationReturnTime = 1500;
  110521. this._elevationReturnWaitTime = 1000;
  110522. this._zoomStopsAnimation = false;
  110523. this._framingTime = 1500;
  110524. /**
  110525. * Define if the behavior should automatically change the configured
  110526. * camera limits and sensibilities.
  110527. */
  110528. this.autoCorrectCameraLimitsAndSensibility = true;
  110529. this._isPointerDown = false;
  110530. this._lastInteractionTime = -Infinity;
  110531. // Framing control
  110532. this._animatables = new Array();
  110533. this._betaIsAnimating = false;
  110534. }
  110535. Object.defineProperty(FramingBehavior.prototype, "name", {
  110536. /**
  110537. * Gets the name of the behavior.
  110538. */
  110539. get: function () {
  110540. return "Framing";
  110541. },
  110542. enumerable: true,
  110543. configurable: true
  110544. });
  110545. Object.defineProperty(FramingBehavior.prototype, "mode", {
  110546. /**
  110547. * Gets current mode used by the behavior.
  110548. */
  110549. get: function () {
  110550. return this._mode;
  110551. },
  110552. /**
  110553. * Sets the current mode used by the behavior
  110554. */
  110555. set: function (mode) {
  110556. this._mode = mode;
  110557. },
  110558. enumerable: true,
  110559. configurable: true
  110560. });
  110561. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  110562. /**
  110563. * Gets the scale applied to the radius
  110564. */
  110565. get: function () {
  110566. return this._radiusScale;
  110567. },
  110568. /**
  110569. * Sets the scale applied to the radius (1 by default)
  110570. */
  110571. set: function (radius) {
  110572. this._radiusScale = radius;
  110573. },
  110574. enumerable: true,
  110575. configurable: true
  110576. });
  110577. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  110578. /**
  110579. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  110580. */
  110581. get: function () {
  110582. return this._positionScale;
  110583. },
  110584. /**
  110585. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  110586. */
  110587. set: function (scale) {
  110588. this._positionScale = scale;
  110589. },
  110590. enumerable: true,
  110591. configurable: true
  110592. });
  110593. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  110594. /**
  110595. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  110596. * behaviour is triggered, in radians.
  110597. */
  110598. get: function () {
  110599. return this._defaultElevation;
  110600. },
  110601. /**
  110602. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  110603. * behaviour is triggered, in radians.
  110604. */
  110605. set: function (elevation) {
  110606. this._defaultElevation = elevation;
  110607. },
  110608. enumerable: true,
  110609. configurable: true
  110610. });
  110611. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  110612. /**
  110613. * Gets the time (in milliseconds) taken to return to the default beta position.
  110614. * Negative value indicates camera should not return to default.
  110615. */
  110616. get: function () {
  110617. return this._elevationReturnTime;
  110618. },
  110619. /**
  110620. * Sets the time (in milliseconds) taken to return to the default beta position.
  110621. * Negative value indicates camera should not return to default.
  110622. */
  110623. set: function (speed) {
  110624. this._elevationReturnTime = speed;
  110625. },
  110626. enumerable: true,
  110627. configurable: true
  110628. });
  110629. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  110630. /**
  110631. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  110632. */
  110633. get: function () {
  110634. return this._elevationReturnWaitTime;
  110635. },
  110636. /**
  110637. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  110638. */
  110639. set: function (time) {
  110640. this._elevationReturnWaitTime = time;
  110641. },
  110642. enumerable: true,
  110643. configurable: true
  110644. });
  110645. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  110646. /**
  110647. * Gets the flag that indicates if user zooming should stop animation.
  110648. */
  110649. get: function () {
  110650. return this._zoomStopsAnimation;
  110651. },
  110652. /**
  110653. * Sets the flag that indicates if user zooming should stop animation.
  110654. */
  110655. set: function (flag) {
  110656. this._zoomStopsAnimation = flag;
  110657. },
  110658. enumerable: true,
  110659. configurable: true
  110660. });
  110661. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  110662. /**
  110663. * Gets the transition time when framing the mesh, in milliseconds
  110664. */
  110665. get: function () {
  110666. return this._framingTime;
  110667. },
  110668. /**
  110669. * Sets the transition time when framing the mesh, in milliseconds
  110670. */
  110671. set: function (time) {
  110672. this._framingTime = time;
  110673. },
  110674. enumerable: true,
  110675. configurable: true
  110676. });
  110677. /**
  110678. * Initializes the behavior.
  110679. */
  110680. FramingBehavior.prototype.init = function () {
  110681. // Do notihng
  110682. };
  110683. /**
  110684. * Attaches the behavior to its arc rotate camera.
  110685. * @param camera Defines the camera to attach the behavior to
  110686. */
  110687. FramingBehavior.prototype.attach = function (camera) {
  110688. var _this = this;
  110689. this._attachedCamera = camera;
  110690. var scene = this._attachedCamera.getScene();
  110691. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  110692. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  110693. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  110694. _this._isPointerDown = true;
  110695. return;
  110696. }
  110697. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  110698. _this._isPointerDown = false;
  110699. }
  110700. });
  110701. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  110702. if (mesh) {
  110703. _this.zoomOnMesh(mesh);
  110704. }
  110705. });
  110706. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  110707. // Stop the animation if there is user interaction and the animation should stop for this interaction
  110708. _this._applyUserInteraction();
  110709. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  110710. // back to the default position after a given timeout
  110711. _this._maintainCameraAboveGround();
  110712. });
  110713. };
  110714. /**
  110715. * Detaches the behavior from its current arc rotate camera.
  110716. */
  110717. FramingBehavior.prototype.detach = function () {
  110718. if (!this._attachedCamera) {
  110719. return;
  110720. }
  110721. var scene = this._attachedCamera.getScene();
  110722. if (this._onPrePointerObservableObserver) {
  110723. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  110724. }
  110725. if (this._onAfterCheckInputsObserver) {
  110726. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  110727. }
  110728. if (this._onMeshTargetChangedObserver) {
  110729. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  110730. }
  110731. this._attachedCamera = null;
  110732. };
  110733. /**
  110734. * Targets the given mesh and updates zoom level accordingly.
  110735. * @param mesh The mesh to target.
  110736. * @param radius Optional. If a cached radius position already exists, overrides default.
  110737. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110738. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110739. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110740. */
  110741. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  110742. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110743. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110744. mesh.computeWorldMatrix(true);
  110745. var boundingBox = mesh.getBoundingInfo().boundingBox;
  110746. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  110747. };
  110748. /**
  110749. * Targets the given mesh with its children and updates zoom level accordingly.
  110750. * @param mesh The mesh to target.
  110751. * @param radius Optional. If a cached radius position already exists, overrides default.
  110752. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110753. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110754. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110755. */
  110756. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  110757. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110758. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110759. mesh.computeWorldMatrix(true);
  110760. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  110761. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  110762. };
  110763. /**
  110764. * Targets the given meshes with their children and updates zoom level accordingly.
  110765. * @param meshes The mesh to target.
  110766. * @param radius Optional. If a cached radius position already exists, overrides default.
  110767. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110768. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110769. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110770. */
  110771. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  110772. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110773. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110774. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  110775. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  110776. for (var i = 0; i < meshes.length; i++) {
  110777. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  110778. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  110779. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  110780. }
  110781. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  110782. };
  110783. /**
  110784. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  110785. * @param minimumWorld Determines the smaller position of the bounding box extend
  110786. * @param maximumWorld Determines the bigger position of the bounding box extend
  110787. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110788. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110789. */
  110790. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  110791. var _this = this;
  110792. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110793. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110794. var zoomTarget;
  110795. if (!this._attachedCamera) {
  110796. return;
  110797. }
  110798. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  110799. var bottom = minimumWorld.y;
  110800. var top = maximumWorld.y;
  110801. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  110802. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  110803. if (focusOnOriginXZ) {
  110804. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  110805. }
  110806. else {
  110807. var centerWorld = minimumWorld.add(radiusWorld);
  110808. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  110809. }
  110810. if (!this._vectorTransition) {
  110811. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  110812. }
  110813. this._betaIsAnimating = true;
  110814. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  110815. if (animatable) {
  110816. this._animatables.push(animatable);
  110817. }
  110818. // sets the radius and lower radius bounds
  110819. // Small delta ensures camera is not always at lower zoom limit.
  110820. var radius = 0;
  110821. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  110822. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  110823. if (this.autoCorrectCameraLimitsAndSensibility) {
  110824. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  110825. }
  110826. radius = position;
  110827. }
  110828. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110829. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  110830. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  110831. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  110832. }
  110833. }
  110834. // Set sensibilities
  110835. if (this.autoCorrectCameraLimitsAndSensibility) {
  110836. var extend = maximumWorld.subtract(minimumWorld).length();
  110837. this._attachedCamera.panningSensibility = 5000 / extend;
  110838. this._attachedCamera.wheelPrecision = 100 / radius;
  110839. }
  110840. // transition to new radius
  110841. if (!this._radiusTransition) {
  110842. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110843. }
  110844. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  110845. _this.stopAllAnimations();
  110846. if (onAnimationEnd) {
  110847. onAnimationEnd();
  110848. }
  110849. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  110850. _this._attachedCamera.storeState();
  110851. }
  110852. });
  110853. if (animatable) {
  110854. this._animatables.push(animatable);
  110855. }
  110856. };
  110857. /**
  110858. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  110859. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  110860. * frustum width.
  110861. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  110862. * to fully enclose the mesh in the viewing frustum.
  110863. */
  110864. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  110865. var size = maximumWorld.subtract(minimumWorld);
  110866. var boxVectorGlobalDiagonal = size.length();
  110867. var frustumSlope = this._getFrustumSlope();
  110868. // Formula for setting distance
  110869. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  110870. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  110871. // Horizon distance
  110872. var radius = radiusWithoutFraming * this._radiusScale;
  110873. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  110874. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  110875. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  110876. var camera = this._attachedCamera;
  110877. if (!camera) {
  110878. return 0;
  110879. }
  110880. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110881. // Don't exceed the requested limit
  110882. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  110883. }
  110884. // Don't exceed the upper radius limit
  110885. if (camera.upperRadiusLimit) {
  110886. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  110887. }
  110888. return distance;
  110889. };
  110890. /**
  110891. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  110892. * is automatically returned to its default position (expected to be above ground plane).
  110893. */
  110894. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  110895. var _this = this;
  110896. if (this._elevationReturnTime < 0) {
  110897. return;
  110898. }
  110899. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  110900. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  110901. var limitBeta = Math.PI * 0.5;
  110902. // Bring the camera back up if below the ground plane
  110903. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  110904. this._betaIsAnimating = true;
  110905. //Transition to new position
  110906. this.stopAllAnimations();
  110907. if (!this._betaTransition) {
  110908. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110909. }
  110910. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  110911. _this._clearAnimationLocks();
  110912. _this.stopAllAnimations();
  110913. });
  110914. if (animatabe) {
  110915. this._animatables.push(animatabe);
  110916. }
  110917. }
  110918. };
  110919. /**
  110920. * Returns the frustum slope based on the canvas ratio and camera FOV
  110921. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  110922. */
  110923. FramingBehavior.prototype._getFrustumSlope = function () {
  110924. // Calculate the viewport ratio
  110925. // Aspect Ratio is Height/Width.
  110926. var camera = this._attachedCamera;
  110927. if (!camera) {
  110928. return BABYLON.Vector2.Zero();
  110929. }
  110930. var engine = camera.getScene().getEngine();
  110931. var aspectRatio = engine.getAspectRatio(camera);
  110932. // Camera FOV is the vertical field of view (top-bottom) in radians.
  110933. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  110934. var frustumSlopeY = Math.tan(camera.fov / 2);
  110935. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  110936. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  110937. // along the forward vector.
  110938. var frustumSlopeX = frustumSlopeY * aspectRatio;
  110939. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  110940. };
  110941. /**
  110942. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  110943. */
  110944. FramingBehavior.prototype._clearAnimationLocks = function () {
  110945. this._betaIsAnimating = false;
  110946. };
  110947. /**
  110948. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  110949. */
  110950. FramingBehavior.prototype._applyUserInteraction = function () {
  110951. if (this.isUserIsMoving) {
  110952. this._lastInteractionTime = BABYLON.Tools.Now;
  110953. this.stopAllAnimations();
  110954. this._clearAnimationLocks();
  110955. }
  110956. };
  110957. /**
  110958. * Stops and removes all animations that have been applied to the camera
  110959. */
  110960. FramingBehavior.prototype.stopAllAnimations = function () {
  110961. if (this._attachedCamera) {
  110962. this._attachedCamera.animations = [];
  110963. }
  110964. while (this._animatables.length) {
  110965. if (this._animatables[0]) {
  110966. this._animatables[0].onAnimationEnd = null;
  110967. this._animatables[0].stop();
  110968. }
  110969. this._animatables.shift();
  110970. }
  110971. };
  110972. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  110973. /**
  110974. * Gets a value indicating if the user is moving the camera
  110975. */
  110976. get: function () {
  110977. if (!this._attachedCamera) {
  110978. return false;
  110979. }
  110980. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  110981. this._attachedCamera.inertialBetaOffset !== 0 ||
  110982. this._attachedCamera.inertialRadiusOffset !== 0 ||
  110983. this._attachedCamera.inertialPanningX !== 0 ||
  110984. this._attachedCamera.inertialPanningY !== 0 ||
  110985. this._isPointerDown;
  110986. },
  110987. enumerable: true,
  110988. configurable: true
  110989. });
  110990. /**
  110991. * The easing function used by animations
  110992. */
  110993. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  110994. /**
  110995. * The easing mode used by animations
  110996. */
  110997. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  110998. // Statics
  110999. /**
  111000. * The camera can move all the way towards the mesh.
  111001. */
  111002. FramingBehavior.IgnoreBoundsSizeMode = 0;
  111003. /**
  111004. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  111005. */
  111006. FramingBehavior.FitFrustumSidesMode = 1;
  111007. return FramingBehavior;
  111008. }());
  111009. BABYLON.FramingBehavior = FramingBehavior;
  111010. })(BABYLON || (BABYLON = {}));
  111011. //# sourceMappingURL=babylon.framingBehavior.js.map
  111012. var BABYLON;
  111013. (function (BABYLON) {
  111014. /**
  111015. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  111016. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  111017. */
  111018. var BouncingBehavior = /** @class */ (function () {
  111019. function BouncingBehavior() {
  111020. /**
  111021. * The duration of the animation, in milliseconds
  111022. */
  111023. this.transitionDuration = 450;
  111024. /**
  111025. * Length of the distance animated by the transition when lower radius is reached
  111026. */
  111027. this.lowerRadiusTransitionRange = 2;
  111028. /**
  111029. * Length of the distance animated by the transition when upper radius is reached
  111030. */
  111031. this.upperRadiusTransitionRange = -2;
  111032. this._autoTransitionRange = false;
  111033. // Animations
  111034. this._radiusIsAnimating = false;
  111035. this._radiusBounceTransition = null;
  111036. this._animatables = new Array();
  111037. }
  111038. Object.defineProperty(BouncingBehavior.prototype, "name", {
  111039. /**
  111040. * Gets the name of the behavior.
  111041. */
  111042. get: function () {
  111043. return "Bouncing";
  111044. },
  111045. enumerable: true,
  111046. configurable: true
  111047. });
  111048. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  111049. /**
  111050. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  111051. */
  111052. get: function () {
  111053. return this._autoTransitionRange;
  111054. },
  111055. /**
  111056. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  111057. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  111058. */
  111059. set: function (value) {
  111060. var _this = this;
  111061. if (this._autoTransitionRange === value) {
  111062. return;
  111063. }
  111064. this._autoTransitionRange = value;
  111065. var camera = this._attachedCamera;
  111066. if (!camera) {
  111067. return;
  111068. }
  111069. if (value) {
  111070. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  111071. if (!mesh) {
  111072. return;
  111073. }
  111074. mesh.computeWorldMatrix(true);
  111075. var diagonal = mesh.getBoundingInfo().diagonalLength;
  111076. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  111077. _this.upperRadiusTransitionRange = diagonal * 0.05;
  111078. });
  111079. }
  111080. else if (this._onMeshTargetChangedObserver) {
  111081. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  111082. }
  111083. },
  111084. enumerable: true,
  111085. configurable: true
  111086. });
  111087. /**
  111088. * Initializes the behavior.
  111089. */
  111090. BouncingBehavior.prototype.init = function () {
  111091. // Do notihng
  111092. };
  111093. /**
  111094. * Attaches the behavior to its arc rotate camera.
  111095. * @param camera Defines the camera to attach the behavior to
  111096. */
  111097. BouncingBehavior.prototype.attach = function (camera) {
  111098. var _this = this;
  111099. this._attachedCamera = camera;
  111100. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  111101. if (!_this._attachedCamera) {
  111102. return;
  111103. }
  111104. // Add the bounce animation to the lower radius limit
  111105. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  111106. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  111107. }
  111108. // Add the bounce animation to the upper radius limit
  111109. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  111110. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  111111. }
  111112. });
  111113. };
  111114. /**
  111115. * Detaches the behavior from its current arc rotate camera.
  111116. */
  111117. BouncingBehavior.prototype.detach = function () {
  111118. if (!this._attachedCamera) {
  111119. return;
  111120. }
  111121. if (this._onAfterCheckInputsObserver) {
  111122. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  111123. }
  111124. if (this._onMeshTargetChangedObserver) {
  111125. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  111126. }
  111127. this._attachedCamera = null;
  111128. };
  111129. /**
  111130. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  111131. * @param radiusLimit The limit to check against.
  111132. * @return Bool to indicate if at limit.
  111133. */
  111134. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  111135. if (!this._attachedCamera) {
  111136. return false;
  111137. }
  111138. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  111139. return true;
  111140. }
  111141. return false;
  111142. };
  111143. /**
  111144. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  111145. * @param radiusDelta The delta by which to animate to. Can be negative.
  111146. */
  111147. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  111148. var _this = this;
  111149. if (!this._attachedCamera) {
  111150. return;
  111151. }
  111152. if (!this._radiusBounceTransition) {
  111153. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  111154. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  111155. }
  111156. // Prevent zoom until bounce has completed
  111157. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  111158. this._attachedCamera.wheelPrecision = Infinity;
  111159. this._attachedCamera.inertialRadiusOffset = 0;
  111160. // Animate to the radius limit
  111161. this.stopAllAnimations();
  111162. this._radiusIsAnimating = true;
  111163. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  111164. if (animatable) {
  111165. this._animatables.push(animatable);
  111166. }
  111167. };
  111168. /**
  111169. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  111170. */
  111171. BouncingBehavior.prototype._clearAnimationLocks = function () {
  111172. this._radiusIsAnimating = false;
  111173. if (this._attachedCamera) {
  111174. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  111175. }
  111176. };
  111177. /**
  111178. * Stops and removes all animations that have been applied to the camera
  111179. */
  111180. BouncingBehavior.prototype.stopAllAnimations = function () {
  111181. if (this._attachedCamera) {
  111182. this._attachedCamera.animations = [];
  111183. }
  111184. while (this._animatables.length) {
  111185. this._animatables[0].onAnimationEnd = null;
  111186. this._animatables[0].stop();
  111187. this._animatables.shift();
  111188. }
  111189. };
  111190. /**
  111191. * The easing function used by animations
  111192. */
  111193. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  111194. /**
  111195. * The easing mode used by animations
  111196. */
  111197. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  111198. return BouncingBehavior;
  111199. }());
  111200. BABYLON.BouncingBehavior = BouncingBehavior;
  111201. })(BABYLON || (BABYLON = {}));
  111202. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  111203. var BABYLON;
  111204. (function (BABYLON) {
  111205. /**
  111206. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  111207. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  111208. */
  111209. var AutoRotationBehavior = /** @class */ (function () {
  111210. function AutoRotationBehavior() {
  111211. this._zoomStopsAnimation = false;
  111212. this._idleRotationSpeed = 0.05;
  111213. this._idleRotationWaitTime = 2000;
  111214. this._idleRotationSpinupTime = 2000;
  111215. this._isPointerDown = false;
  111216. this._lastFrameTime = null;
  111217. this._lastInteractionTime = -Infinity;
  111218. this._cameraRotationSpeed = 0;
  111219. this._lastFrameRadius = 0;
  111220. }
  111221. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  111222. /**
  111223. * Gets the name of the behavior.
  111224. */
  111225. get: function () {
  111226. return "AutoRotation";
  111227. },
  111228. enumerable: true,
  111229. configurable: true
  111230. });
  111231. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  111232. /**
  111233. * Gets the flag that indicates if user zooming should stop animation.
  111234. */
  111235. get: function () {
  111236. return this._zoomStopsAnimation;
  111237. },
  111238. /**
  111239. * Sets the flag that indicates if user zooming should stop animation.
  111240. */
  111241. set: function (flag) {
  111242. this._zoomStopsAnimation = flag;
  111243. },
  111244. enumerable: true,
  111245. configurable: true
  111246. });
  111247. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  111248. /**
  111249. * Gets the default speed at which the camera rotates around the model.
  111250. */
  111251. get: function () {
  111252. return this._idleRotationSpeed;
  111253. },
  111254. /**
  111255. * Sets the default speed at which the camera rotates around the model.
  111256. */
  111257. set: function (speed) {
  111258. this._idleRotationSpeed = speed;
  111259. },
  111260. enumerable: true,
  111261. configurable: true
  111262. });
  111263. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  111264. /**
  111265. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  111266. */
  111267. get: function () {
  111268. return this._idleRotationWaitTime;
  111269. },
  111270. /**
  111271. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  111272. */
  111273. set: function (time) {
  111274. this._idleRotationWaitTime = time;
  111275. },
  111276. enumerable: true,
  111277. configurable: true
  111278. });
  111279. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  111280. /**
  111281. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  111282. */
  111283. get: function () {
  111284. return this._idleRotationSpinupTime;
  111285. },
  111286. /**
  111287. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  111288. */
  111289. set: function (time) {
  111290. this._idleRotationSpinupTime = time;
  111291. },
  111292. enumerable: true,
  111293. configurable: true
  111294. });
  111295. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  111296. /**
  111297. * Gets a value indicating if the camera is currently rotating because of this behavior
  111298. */
  111299. get: function () {
  111300. return Math.abs(this._cameraRotationSpeed) > 0;
  111301. },
  111302. enumerable: true,
  111303. configurable: true
  111304. });
  111305. /**
  111306. * Initializes the behavior.
  111307. */
  111308. AutoRotationBehavior.prototype.init = function () {
  111309. // Do notihng
  111310. };
  111311. /**
  111312. * Attaches the behavior to its arc rotate camera.
  111313. * @param camera Defines the camera to attach the behavior to
  111314. */
  111315. AutoRotationBehavior.prototype.attach = function (camera) {
  111316. var _this = this;
  111317. this._attachedCamera = camera;
  111318. var scene = this._attachedCamera.getScene();
  111319. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  111320. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  111321. _this._isPointerDown = true;
  111322. return;
  111323. }
  111324. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  111325. _this._isPointerDown = false;
  111326. }
  111327. });
  111328. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  111329. var now = BABYLON.Tools.Now;
  111330. var dt = 0;
  111331. if (_this._lastFrameTime != null) {
  111332. dt = now - _this._lastFrameTime;
  111333. }
  111334. _this._lastFrameTime = now;
  111335. // Stop the animation if there is user interaction and the animation should stop for this interaction
  111336. _this._applyUserInteraction();
  111337. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  111338. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  111339. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  111340. // Step camera rotation by rotation speed
  111341. if (_this._attachedCamera) {
  111342. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  111343. }
  111344. });
  111345. };
  111346. /**
  111347. * Detaches the behavior from its current arc rotate camera.
  111348. */
  111349. AutoRotationBehavior.prototype.detach = function () {
  111350. if (!this._attachedCamera) {
  111351. return;
  111352. }
  111353. var scene = this._attachedCamera.getScene();
  111354. if (this._onPrePointerObservableObserver) {
  111355. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  111356. }
  111357. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  111358. this._attachedCamera = null;
  111359. };
  111360. /**
  111361. * Returns true if user is scrolling.
  111362. * @return true if user is scrolling.
  111363. */
  111364. AutoRotationBehavior.prototype._userIsZooming = function () {
  111365. if (!this._attachedCamera) {
  111366. return false;
  111367. }
  111368. return this._attachedCamera.inertialRadiusOffset !== 0;
  111369. };
  111370. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  111371. if (!this._attachedCamera) {
  111372. return false;
  111373. }
  111374. var zoomHasHitLimit = false;
  111375. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  111376. zoomHasHitLimit = true;
  111377. }
  111378. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  111379. this._lastFrameRadius = this._attachedCamera.radius;
  111380. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  111381. };
  111382. /**
  111383. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  111384. */
  111385. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  111386. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  111387. this._lastInteractionTime = BABYLON.Tools.Now;
  111388. }
  111389. };
  111390. // Tools
  111391. AutoRotationBehavior.prototype._userIsMoving = function () {
  111392. if (!this._attachedCamera) {
  111393. return false;
  111394. }
  111395. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  111396. this._attachedCamera.inertialBetaOffset !== 0 ||
  111397. this._attachedCamera.inertialRadiusOffset !== 0 ||
  111398. this._attachedCamera.inertialPanningX !== 0 ||
  111399. this._attachedCamera.inertialPanningY !== 0 ||
  111400. this._isPointerDown;
  111401. };
  111402. return AutoRotationBehavior;
  111403. }());
  111404. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  111405. })(BABYLON || (BABYLON = {}));
  111406. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  111407. var BABYLON;
  111408. (function (BABYLON) {
  111409. var NullEngineOptions = /** @class */ (function () {
  111410. function NullEngineOptions() {
  111411. this.renderWidth = 512;
  111412. this.renderHeight = 256;
  111413. this.textureSize = 512;
  111414. this.deterministicLockstep = false;
  111415. this.lockstepMaxSteps = 4;
  111416. }
  111417. return NullEngineOptions;
  111418. }());
  111419. BABYLON.NullEngineOptions = NullEngineOptions;
  111420. /**
  111421. * The null engine class provides support for headless version of babylon.js.
  111422. * This can be used in server side scenario or for testing purposes
  111423. */
  111424. var NullEngine = /** @class */ (function (_super) {
  111425. __extends(NullEngine, _super);
  111426. function NullEngine(options) {
  111427. if (options === void 0) { options = new NullEngineOptions(); }
  111428. var _this = _super.call(this, null) || this;
  111429. if (options.deterministicLockstep === undefined) {
  111430. options.deterministicLockstep = false;
  111431. }
  111432. if (options.lockstepMaxSteps === undefined) {
  111433. options.lockstepMaxSteps = 4;
  111434. }
  111435. _this._options = options;
  111436. // Init caps
  111437. // We consider we are on a webgl1 capable device
  111438. _this._caps = new BABYLON.EngineCapabilities();
  111439. _this._caps.maxTexturesImageUnits = 16;
  111440. _this._caps.maxVertexTextureImageUnits = 16;
  111441. _this._caps.maxTextureSize = 512;
  111442. _this._caps.maxCubemapTextureSize = 512;
  111443. _this._caps.maxRenderTextureSize = 512;
  111444. _this._caps.maxVertexAttribs = 16;
  111445. _this._caps.maxVaryingVectors = 16;
  111446. _this._caps.maxFragmentUniformVectors = 16;
  111447. _this._caps.maxVertexUniformVectors = 16;
  111448. // Extensions
  111449. _this._caps.standardDerivatives = false;
  111450. _this._caps.astc = null;
  111451. _this._caps.s3tc = null;
  111452. _this._caps.pvrtc = null;
  111453. _this._caps.etc1 = null;
  111454. _this._caps.etc2 = null;
  111455. _this._caps.textureAnisotropicFilterExtension = null;
  111456. _this._caps.maxAnisotropy = 0;
  111457. _this._caps.uintIndices = false;
  111458. _this._caps.fragmentDepthSupported = false;
  111459. _this._caps.highPrecisionShaderSupported = true;
  111460. _this._caps.colorBufferFloat = false;
  111461. _this._caps.textureFloat = false;
  111462. _this._caps.textureFloatLinearFiltering = false;
  111463. _this._caps.textureFloatRender = false;
  111464. _this._caps.textureHalfFloat = false;
  111465. _this._caps.textureHalfFloatLinearFiltering = false;
  111466. _this._caps.textureHalfFloatRender = false;
  111467. _this._caps.textureLOD = false;
  111468. _this._caps.drawBuffersExtension = false;
  111469. _this._caps.depthTextureExtension = false;
  111470. _this._caps.vertexArrayObject = false;
  111471. _this._caps.instancedArrays = false;
  111472. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  111473. // Wrappers
  111474. if (typeof URL === "undefined") {
  111475. URL = {
  111476. createObjectURL: function () { },
  111477. revokeObjectURL: function () { }
  111478. };
  111479. }
  111480. if (typeof Blob === "undefined") {
  111481. Blob = function () { };
  111482. }
  111483. return _this;
  111484. }
  111485. NullEngine.prototype.isDeterministicLockStep = function () {
  111486. return this._options.deterministicLockstep;
  111487. };
  111488. NullEngine.prototype.getLockstepMaxSteps = function () {
  111489. return this._options.lockstepMaxSteps;
  111490. };
  111491. NullEngine.prototype.getHardwareScalingLevel = function () {
  111492. return 1.0;
  111493. };
  111494. NullEngine.prototype.createVertexBuffer = function (vertices) {
  111495. return {
  111496. capacity: 0,
  111497. references: 1,
  111498. is32Bits: false
  111499. };
  111500. };
  111501. NullEngine.prototype.createIndexBuffer = function (indices) {
  111502. return {
  111503. capacity: 0,
  111504. references: 1,
  111505. is32Bits: false
  111506. };
  111507. };
  111508. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  111509. if (stencil === void 0) { stencil = false; }
  111510. };
  111511. NullEngine.prototype.getRenderWidth = function (useScreen) {
  111512. if (useScreen === void 0) { useScreen = false; }
  111513. if (!useScreen && this._currentRenderTarget) {
  111514. return this._currentRenderTarget.width;
  111515. }
  111516. return this._options.renderWidth;
  111517. };
  111518. NullEngine.prototype.getRenderHeight = function (useScreen) {
  111519. if (useScreen === void 0) { useScreen = false; }
  111520. if (!useScreen && this._currentRenderTarget) {
  111521. return this._currentRenderTarget.height;
  111522. }
  111523. return this._options.renderHeight;
  111524. };
  111525. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  111526. this._cachedViewport = viewport;
  111527. };
  111528. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  111529. return {
  111530. transformFeedback: null,
  111531. __SPECTOR_rebuildProgram: null
  111532. };
  111533. };
  111534. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  111535. return [];
  111536. };
  111537. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  111538. return [];
  111539. };
  111540. NullEngine.prototype.bindSamplers = function (effect) {
  111541. this._currentEffect = null;
  111542. };
  111543. NullEngine.prototype.enableEffect = function (effect) {
  111544. this._currentEffect = effect;
  111545. if (effect.onBind) {
  111546. effect.onBind(effect);
  111547. }
  111548. if (effect._onBindObservable) {
  111549. effect._onBindObservable.notifyObservers(effect);
  111550. }
  111551. };
  111552. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  111553. if (zOffset === void 0) { zOffset = 0; }
  111554. if (reverseSide === void 0) { reverseSide = false; }
  111555. };
  111556. NullEngine.prototype.setIntArray = function (uniform, array) {
  111557. };
  111558. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  111559. };
  111560. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  111561. };
  111562. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  111563. };
  111564. NullEngine.prototype.setFloatArray = function (uniform, array) {
  111565. };
  111566. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  111567. };
  111568. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  111569. };
  111570. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  111571. };
  111572. NullEngine.prototype.setArray = function (uniform, array) {
  111573. };
  111574. NullEngine.prototype.setArray2 = function (uniform, array) {
  111575. };
  111576. NullEngine.prototype.setArray3 = function (uniform, array) {
  111577. };
  111578. NullEngine.prototype.setArray4 = function (uniform, array) {
  111579. };
  111580. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  111581. };
  111582. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  111583. };
  111584. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  111585. };
  111586. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  111587. };
  111588. NullEngine.prototype.setFloat = function (uniform, value) {
  111589. };
  111590. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  111591. };
  111592. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  111593. };
  111594. NullEngine.prototype.setBool = function (uniform, bool) {
  111595. };
  111596. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  111597. };
  111598. NullEngine.prototype.setColor3 = function (uniform, color3) {
  111599. };
  111600. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  111601. };
  111602. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  111603. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  111604. if (this._alphaMode === mode) {
  111605. return;
  111606. }
  111607. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  111608. if (!noDepthWriteChange) {
  111609. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  111610. }
  111611. this._alphaMode = mode;
  111612. };
  111613. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  111614. };
  111615. NullEngine.prototype.wipeCaches = function (bruteForce) {
  111616. if (this.preventCacheWipeBetweenFrames) {
  111617. return;
  111618. }
  111619. this.resetTextureCache();
  111620. this._currentEffect = null;
  111621. if (bruteForce) {
  111622. this._currentProgram = null;
  111623. this._stencilState.reset();
  111624. this._depthCullingState.reset();
  111625. this._alphaState.reset();
  111626. }
  111627. this._cachedVertexBuffers = null;
  111628. this._cachedIndexBuffer = null;
  111629. this._cachedEffectForVertexBuffers = null;
  111630. };
  111631. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  111632. };
  111633. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  111634. };
  111635. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  111636. };
  111637. /** @hidden */
  111638. NullEngine.prototype._createTexture = function () {
  111639. return {};
  111640. };
  111641. /** @hidden */
  111642. NullEngine.prototype._releaseTexture = function (texture) {
  111643. };
  111644. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  111645. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111646. if (onLoad === void 0) { onLoad = null; }
  111647. if (onError === void 0) { onError = null; }
  111648. if (buffer === void 0) { buffer = null; }
  111649. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  111650. var url = String(urlArg);
  111651. texture.url = url;
  111652. texture.generateMipMaps = !noMipmap;
  111653. texture.samplingMode = samplingMode;
  111654. texture.invertY = invertY;
  111655. texture.baseWidth = this._options.textureSize;
  111656. texture.baseHeight = this._options.textureSize;
  111657. texture.width = this._options.textureSize;
  111658. texture.height = this._options.textureSize;
  111659. if (format) {
  111660. texture.format = format;
  111661. }
  111662. texture.isReady = true;
  111663. if (onLoad) {
  111664. onLoad();
  111665. }
  111666. this._internalTexturesCache.push(texture);
  111667. return texture;
  111668. };
  111669. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  111670. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  111671. if (options !== undefined && typeof options === "object") {
  111672. fullOptions.generateMipMaps = options.generateMipMaps;
  111673. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  111674. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  111675. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  111676. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  111677. }
  111678. else {
  111679. fullOptions.generateMipMaps = options;
  111680. fullOptions.generateDepthBuffer = true;
  111681. fullOptions.generateStencilBuffer = false;
  111682. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111683. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  111684. }
  111685. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  111686. var width = size.width || size;
  111687. var height = size.height || size;
  111688. texture._depthStencilBuffer = {};
  111689. texture._framebuffer = {};
  111690. texture.baseWidth = width;
  111691. texture.baseHeight = height;
  111692. texture.width = width;
  111693. texture.height = height;
  111694. texture.isReady = true;
  111695. texture.samples = 1;
  111696. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  111697. texture.samplingMode = fullOptions.samplingMode;
  111698. texture.type = fullOptions.type;
  111699. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  111700. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  111701. this._internalTexturesCache.push(texture);
  111702. return texture;
  111703. };
  111704. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  111705. texture.samplingMode = samplingMode;
  111706. };
  111707. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  111708. if (this._currentRenderTarget) {
  111709. this.unBindFramebuffer(this._currentRenderTarget);
  111710. }
  111711. this._currentRenderTarget = texture;
  111712. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  111713. if (this._cachedViewport && !forceFullscreenViewport) {
  111714. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  111715. }
  111716. };
  111717. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  111718. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  111719. this._currentRenderTarget = null;
  111720. if (onBeforeUnbind) {
  111721. if (texture._MSAAFramebuffer) {
  111722. this._currentFramebuffer = texture._framebuffer;
  111723. }
  111724. onBeforeUnbind();
  111725. }
  111726. this._currentFramebuffer = null;
  111727. };
  111728. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  111729. var vbo = {
  111730. capacity: 1,
  111731. references: 1,
  111732. is32Bits: false
  111733. };
  111734. return vbo;
  111735. };
  111736. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  111737. if (premulAlpha === void 0) { premulAlpha = false; }
  111738. };
  111739. /**
  111740. * @hidden
  111741. * Get the current error code of the webGL context
  111742. * @returns the error code
  111743. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  111744. */
  111745. NullEngine.prototype.getError = function () {
  111746. return 0;
  111747. };
  111748. /** @hidden */
  111749. NullEngine.prototype._getUnpackAlignement = function () {
  111750. return 1;
  111751. };
  111752. /** @hidden */
  111753. NullEngine.prototype._unpackFlipY = function (value) {
  111754. };
  111755. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  111756. if (offset === void 0) { offset = 0; }
  111757. };
  111758. /**
  111759. * Updates a dynamic vertex buffer.
  111760. * @param vertexBuffer the vertex buffer to update
  111761. * @param data the data used to update the vertex buffer
  111762. * @param byteOffset the byte offset of the data (optional)
  111763. * @param byteLength the byte length of the data (optional)
  111764. */
  111765. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  111766. };
  111767. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  111768. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  111769. this._boundTexturesCache[this._activeChannel] = texture;
  111770. return true;
  111771. }
  111772. return false;
  111773. };
  111774. /** @hidden */
  111775. NullEngine.prototype._bindTexture = function (channel, texture) {
  111776. if (channel < 0) {
  111777. return;
  111778. }
  111779. this._bindTextureDirectly(0, texture);
  111780. };
  111781. /** @hidden */
  111782. NullEngine.prototype._releaseBuffer = function (buffer) {
  111783. buffer.references--;
  111784. if (buffer.references === 0) {
  111785. return true;
  111786. }
  111787. return false;
  111788. };
  111789. NullEngine.prototype.releaseEffects = function () {
  111790. };
  111791. NullEngine.prototype.displayLoadingUI = function () {
  111792. };
  111793. NullEngine.prototype.hideLoadingUI = function () {
  111794. };
  111795. /** @hidden */
  111796. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  111797. if (faceIndex === void 0) { faceIndex = 0; }
  111798. if (lod === void 0) { lod = 0; }
  111799. };
  111800. /** @hidden */
  111801. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  111802. if (faceIndex === void 0) { faceIndex = 0; }
  111803. if (lod === void 0) { lod = 0; }
  111804. };
  111805. /** @hidden */
  111806. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  111807. if (faceIndex === void 0) { faceIndex = 0; }
  111808. if (lod === void 0) { lod = 0; }
  111809. };
  111810. /** @hidden */
  111811. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  111812. if (faceIndex === void 0) { faceIndex = 0; }
  111813. if (lod === void 0) { lod = 0; }
  111814. };
  111815. return NullEngine;
  111816. }(BABYLON.Engine));
  111817. BABYLON.NullEngine = NullEngine;
  111818. })(BABYLON || (BABYLON = {}));
  111819. //# sourceMappingURL=babylon.nullEngine.js.map
  111820. var BABYLON;
  111821. (function (BABYLON) {
  111822. /**
  111823. * This class can be used to get instrumentation data from a Babylon engine
  111824. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  111825. */
  111826. var EngineInstrumentation = /** @class */ (function () {
  111827. /**
  111828. * Instantiates a new engine instrumentation.
  111829. * This class can be used to get instrumentation data from a Babylon engine
  111830. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  111831. * @param engine Defines the engine to instrument
  111832. */
  111833. function EngineInstrumentation(
  111834. /**
  111835. * Define the instrumented engine.
  111836. */
  111837. engine) {
  111838. this.engine = engine;
  111839. this._captureGPUFrameTime = false;
  111840. this._gpuFrameTime = new BABYLON.PerfCounter();
  111841. this._captureShaderCompilationTime = false;
  111842. this._shaderCompilationTime = new BABYLON.PerfCounter();
  111843. // Observers
  111844. this._onBeginFrameObserver = null;
  111845. this._onEndFrameObserver = null;
  111846. this._onBeforeShaderCompilationObserver = null;
  111847. this._onAfterShaderCompilationObserver = null;
  111848. }
  111849. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  111850. // Properties
  111851. /**
  111852. * Gets the perf counter used for GPU frame time
  111853. */
  111854. get: function () {
  111855. return this._gpuFrameTime;
  111856. },
  111857. enumerable: true,
  111858. configurable: true
  111859. });
  111860. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  111861. /**
  111862. * Gets the GPU frame time capture status
  111863. */
  111864. get: function () {
  111865. return this._captureGPUFrameTime;
  111866. },
  111867. /**
  111868. * Enable or disable the GPU frame time capture
  111869. */
  111870. set: function (value) {
  111871. var _this = this;
  111872. if (value === this._captureGPUFrameTime) {
  111873. return;
  111874. }
  111875. this._captureGPUFrameTime = value;
  111876. if (value) {
  111877. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  111878. if (!_this._gpuFrameTimeToken) {
  111879. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  111880. }
  111881. });
  111882. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  111883. if (!_this._gpuFrameTimeToken) {
  111884. return;
  111885. }
  111886. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  111887. if (time > -1) {
  111888. _this._gpuFrameTimeToken = null;
  111889. _this._gpuFrameTime.fetchNewFrame();
  111890. _this._gpuFrameTime.addCount(time, true);
  111891. }
  111892. });
  111893. }
  111894. else {
  111895. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111896. this._onBeginFrameObserver = null;
  111897. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111898. this._onEndFrameObserver = null;
  111899. }
  111900. },
  111901. enumerable: true,
  111902. configurable: true
  111903. });
  111904. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  111905. /**
  111906. * Gets the perf counter used for shader compilation time
  111907. */
  111908. get: function () {
  111909. return this._shaderCompilationTime;
  111910. },
  111911. enumerable: true,
  111912. configurable: true
  111913. });
  111914. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  111915. /**
  111916. * Gets the shader compilation time capture status
  111917. */
  111918. get: function () {
  111919. return this._captureShaderCompilationTime;
  111920. },
  111921. /**
  111922. * Enable or disable the shader compilation time capture
  111923. */
  111924. set: function (value) {
  111925. var _this = this;
  111926. if (value === this._captureShaderCompilationTime) {
  111927. return;
  111928. }
  111929. this._captureShaderCompilationTime = value;
  111930. if (value) {
  111931. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  111932. _this._shaderCompilationTime.fetchNewFrame();
  111933. _this._shaderCompilationTime.beginMonitoring();
  111934. });
  111935. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  111936. _this._shaderCompilationTime.endMonitoring();
  111937. });
  111938. }
  111939. else {
  111940. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111941. this._onBeforeShaderCompilationObserver = null;
  111942. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111943. this._onAfterShaderCompilationObserver = null;
  111944. }
  111945. },
  111946. enumerable: true,
  111947. configurable: true
  111948. });
  111949. /**
  111950. * Dispose and release associated resources.
  111951. */
  111952. EngineInstrumentation.prototype.dispose = function () {
  111953. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111954. this._onBeginFrameObserver = null;
  111955. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111956. this._onEndFrameObserver = null;
  111957. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111958. this._onBeforeShaderCompilationObserver = null;
  111959. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111960. this._onAfterShaderCompilationObserver = null;
  111961. this.engine = null;
  111962. };
  111963. return EngineInstrumentation;
  111964. }());
  111965. BABYLON.EngineInstrumentation = EngineInstrumentation;
  111966. })(BABYLON || (BABYLON = {}));
  111967. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  111968. var BABYLON;
  111969. (function (BABYLON) {
  111970. /**
  111971. * This class can be used to get instrumentation data from a Babylon engine
  111972. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111973. */
  111974. var SceneInstrumentation = /** @class */ (function () {
  111975. /**
  111976. * Instantiates a new scene instrumentation.
  111977. * This class can be used to get instrumentation data from a Babylon engine
  111978. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111979. * @param scene Defines the scene to instrument
  111980. */
  111981. function SceneInstrumentation(
  111982. /**
  111983. * Defines the scene to instrument
  111984. */
  111985. scene) {
  111986. var _this = this;
  111987. this.scene = scene;
  111988. this._captureActiveMeshesEvaluationTime = false;
  111989. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  111990. this._captureRenderTargetsRenderTime = false;
  111991. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  111992. this._captureFrameTime = false;
  111993. this._frameTime = new BABYLON.PerfCounter();
  111994. this._captureRenderTime = false;
  111995. this._renderTime = new BABYLON.PerfCounter();
  111996. this._captureInterFrameTime = false;
  111997. this._interFrameTime = new BABYLON.PerfCounter();
  111998. this._captureParticlesRenderTime = false;
  111999. this._particlesRenderTime = new BABYLON.PerfCounter();
  112000. this._captureSpritesRenderTime = false;
  112001. this._spritesRenderTime = new BABYLON.PerfCounter();
  112002. this._capturePhysicsTime = false;
  112003. this._physicsTime = new BABYLON.PerfCounter();
  112004. this._captureAnimationsTime = false;
  112005. this._animationsTime = new BABYLON.PerfCounter();
  112006. this._captureCameraRenderTime = false;
  112007. this._cameraRenderTime = new BABYLON.PerfCounter();
  112008. // Observers
  112009. this._onBeforeActiveMeshesEvaluationObserver = null;
  112010. this._onAfterActiveMeshesEvaluationObserver = null;
  112011. this._onBeforeRenderTargetsRenderObserver = null;
  112012. this._onAfterRenderTargetsRenderObserver = null;
  112013. this._onAfterRenderObserver = null;
  112014. this._onBeforeDrawPhaseObserver = null;
  112015. this._onAfterDrawPhaseObserver = null;
  112016. this._onBeforeAnimationsObserver = null;
  112017. this._onBeforeParticlesRenderingObserver = null;
  112018. this._onAfterParticlesRenderingObserver = null;
  112019. this._onBeforeSpritesRenderingObserver = null;
  112020. this._onAfterSpritesRenderingObserver = null;
  112021. this._onBeforePhysicsObserver = null;
  112022. this._onAfterPhysicsObserver = null;
  112023. this._onAfterAnimationsObserver = null;
  112024. this._onBeforeCameraRenderObserver = null;
  112025. this._onAfterCameraRenderObserver = null;
  112026. // Before render
  112027. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  112028. if (_this._captureActiveMeshesEvaluationTime) {
  112029. _this._activeMeshesEvaluationTime.fetchNewFrame();
  112030. }
  112031. if (_this._captureRenderTargetsRenderTime) {
  112032. _this._renderTargetsRenderTime.fetchNewFrame();
  112033. }
  112034. if (_this._captureFrameTime) {
  112035. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  112036. _this._frameTime.beginMonitoring();
  112037. }
  112038. if (_this._captureInterFrameTime) {
  112039. _this._interFrameTime.endMonitoring();
  112040. }
  112041. if (_this._captureParticlesRenderTime) {
  112042. _this._particlesRenderTime.fetchNewFrame();
  112043. }
  112044. if (_this._captureSpritesRenderTime) {
  112045. _this._spritesRenderTime.fetchNewFrame();
  112046. }
  112047. if (_this._captureAnimationsTime) {
  112048. _this._animationsTime.beginMonitoring();
  112049. }
  112050. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  112051. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  112052. });
  112053. // After render
  112054. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  112055. if (_this._captureFrameTime) {
  112056. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  112057. _this._frameTime.endMonitoring();
  112058. }
  112059. if (_this._captureRenderTime) {
  112060. _this._renderTime.endMonitoring(false);
  112061. }
  112062. if (_this._captureInterFrameTime) {
  112063. _this._interFrameTime.beginMonitoring();
  112064. }
  112065. });
  112066. }
  112067. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  112068. // Properties
  112069. /**
  112070. * Gets the perf counter used for active meshes evaluation time
  112071. */
  112072. get: function () {
  112073. return this._activeMeshesEvaluationTime;
  112074. },
  112075. enumerable: true,
  112076. configurable: true
  112077. });
  112078. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  112079. /**
  112080. * Gets the active meshes evaluation time capture status
  112081. */
  112082. get: function () {
  112083. return this._captureActiveMeshesEvaluationTime;
  112084. },
  112085. /**
  112086. * Enable or disable the active meshes evaluation time capture
  112087. */
  112088. set: function (value) {
  112089. var _this = this;
  112090. if (value === this._captureActiveMeshesEvaluationTime) {
  112091. return;
  112092. }
  112093. this._captureActiveMeshesEvaluationTime = value;
  112094. if (value) {
  112095. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  112096. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  112097. _this._activeMeshesEvaluationTime.beginMonitoring();
  112098. });
  112099. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  112100. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  112101. _this._activeMeshesEvaluationTime.endMonitoring();
  112102. });
  112103. }
  112104. else {
  112105. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  112106. this._onBeforeActiveMeshesEvaluationObserver = null;
  112107. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  112108. this._onAfterActiveMeshesEvaluationObserver = null;
  112109. }
  112110. },
  112111. enumerable: true,
  112112. configurable: true
  112113. });
  112114. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  112115. /**
  112116. * Gets the perf counter used for render targets render time
  112117. */
  112118. get: function () {
  112119. return this._renderTargetsRenderTime;
  112120. },
  112121. enumerable: true,
  112122. configurable: true
  112123. });
  112124. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  112125. /**
  112126. * Gets the render targets render time capture status
  112127. */
  112128. get: function () {
  112129. return this._captureRenderTargetsRenderTime;
  112130. },
  112131. /**
  112132. * Enable or disable the render targets render time capture
  112133. */
  112134. set: function (value) {
  112135. var _this = this;
  112136. if (value === this._captureRenderTargetsRenderTime) {
  112137. return;
  112138. }
  112139. this._captureRenderTargetsRenderTime = value;
  112140. if (value) {
  112141. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  112142. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  112143. _this._renderTargetsRenderTime.beginMonitoring();
  112144. });
  112145. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  112146. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  112147. _this._renderTargetsRenderTime.endMonitoring(false);
  112148. });
  112149. }
  112150. else {
  112151. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  112152. this._onBeforeRenderTargetsRenderObserver = null;
  112153. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  112154. this._onAfterRenderTargetsRenderObserver = null;
  112155. }
  112156. },
  112157. enumerable: true,
  112158. configurable: true
  112159. });
  112160. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  112161. /**
  112162. * Gets the perf counter used for particles render time
  112163. */
  112164. get: function () {
  112165. return this._particlesRenderTime;
  112166. },
  112167. enumerable: true,
  112168. configurable: true
  112169. });
  112170. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  112171. /**
  112172. * Gets the particles render time capture status
  112173. */
  112174. get: function () {
  112175. return this._captureParticlesRenderTime;
  112176. },
  112177. /**
  112178. * Enable or disable the particles render time capture
  112179. */
  112180. set: function (value) {
  112181. var _this = this;
  112182. if (value === this._captureParticlesRenderTime) {
  112183. return;
  112184. }
  112185. this._captureParticlesRenderTime = value;
  112186. if (value) {
  112187. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  112188. BABYLON.Tools.StartPerformanceCounter("Particles");
  112189. _this._particlesRenderTime.beginMonitoring();
  112190. });
  112191. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  112192. BABYLON.Tools.EndPerformanceCounter("Particles");
  112193. _this._particlesRenderTime.endMonitoring(false);
  112194. });
  112195. }
  112196. else {
  112197. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  112198. this._onBeforeParticlesRenderingObserver = null;
  112199. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  112200. this._onAfterParticlesRenderingObserver = null;
  112201. }
  112202. },
  112203. enumerable: true,
  112204. configurable: true
  112205. });
  112206. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  112207. /**
  112208. * Gets the perf counter used for sprites render time
  112209. */
  112210. get: function () {
  112211. return this._spritesRenderTime;
  112212. },
  112213. enumerable: true,
  112214. configurable: true
  112215. });
  112216. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  112217. /**
  112218. * Gets the sprites render time capture status
  112219. */
  112220. get: function () {
  112221. return this._captureSpritesRenderTime;
  112222. },
  112223. /**
  112224. * Enable or disable the sprites render time capture
  112225. */
  112226. set: function (value) {
  112227. var _this = this;
  112228. if (value === this._captureSpritesRenderTime) {
  112229. return;
  112230. }
  112231. this._captureSpritesRenderTime = value;
  112232. if (!this.scene.spriteManagers) {
  112233. return;
  112234. }
  112235. if (value) {
  112236. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  112237. BABYLON.Tools.StartPerformanceCounter("Sprites");
  112238. _this._spritesRenderTime.beginMonitoring();
  112239. });
  112240. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  112241. BABYLON.Tools.EndPerformanceCounter("Sprites");
  112242. _this._spritesRenderTime.endMonitoring(false);
  112243. });
  112244. }
  112245. else {
  112246. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  112247. this._onBeforeSpritesRenderingObserver = null;
  112248. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  112249. this._onAfterSpritesRenderingObserver = null;
  112250. }
  112251. },
  112252. enumerable: true,
  112253. configurable: true
  112254. });
  112255. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  112256. /**
  112257. * Gets the perf counter used for physics time
  112258. */
  112259. get: function () {
  112260. return this._physicsTime;
  112261. },
  112262. enumerable: true,
  112263. configurable: true
  112264. });
  112265. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  112266. /**
  112267. * Gets the physics time capture status
  112268. */
  112269. get: function () {
  112270. return this._capturePhysicsTime;
  112271. },
  112272. /**
  112273. * Enable or disable the physics time capture
  112274. */
  112275. set: function (value) {
  112276. var _this = this;
  112277. if (value === this._capturePhysicsTime) {
  112278. return;
  112279. }
  112280. if (!this.scene.onBeforePhysicsObservable) {
  112281. return;
  112282. }
  112283. this._capturePhysicsTime = value;
  112284. if (value) {
  112285. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  112286. BABYLON.Tools.StartPerformanceCounter("Physics");
  112287. _this._physicsTime.beginMonitoring();
  112288. });
  112289. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  112290. BABYLON.Tools.EndPerformanceCounter("Physics");
  112291. _this._physicsTime.endMonitoring();
  112292. });
  112293. }
  112294. else {
  112295. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  112296. this._onBeforePhysicsObserver = null;
  112297. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  112298. this._onAfterPhysicsObserver = null;
  112299. }
  112300. },
  112301. enumerable: true,
  112302. configurable: true
  112303. });
  112304. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  112305. /**
  112306. * Gets the perf counter used for animations time
  112307. */
  112308. get: function () {
  112309. return this._animationsTime;
  112310. },
  112311. enumerable: true,
  112312. configurable: true
  112313. });
  112314. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  112315. /**
  112316. * Gets the animations time capture status
  112317. */
  112318. get: function () {
  112319. return this._captureAnimationsTime;
  112320. },
  112321. /**
  112322. * Enable or disable the animations time capture
  112323. */
  112324. set: function (value) {
  112325. var _this = this;
  112326. if (value === this._captureAnimationsTime) {
  112327. return;
  112328. }
  112329. this._captureAnimationsTime = value;
  112330. if (value) {
  112331. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  112332. _this._animationsTime.endMonitoring();
  112333. });
  112334. }
  112335. else {
  112336. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  112337. this._onAfterAnimationsObserver = null;
  112338. }
  112339. },
  112340. enumerable: true,
  112341. configurable: true
  112342. });
  112343. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  112344. /**
  112345. * Gets the perf counter used for frame time capture
  112346. */
  112347. get: function () {
  112348. return this._frameTime;
  112349. },
  112350. enumerable: true,
  112351. configurable: true
  112352. });
  112353. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  112354. /**
  112355. * Gets the frame time capture status
  112356. */
  112357. get: function () {
  112358. return this._captureFrameTime;
  112359. },
  112360. /**
  112361. * Enable or disable the frame time capture
  112362. */
  112363. set: function (value) {
  112364. this._captureFrameTime = value;
  112365. },
  112366. enumerable: true,
  112367. configurable: true
  112368. });
  112369. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  112370. /**
  112371. * Gets the perf counter used for inter-frames time capture
  112372. */
  112373. get: function () {
  112374. return this._interFrameTime;
  112375. },
  112376. enumerable: true,
  112377. configurable: true
  112378. });
  112379. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  112380. /**
  112381. * Gets the inter-frames time capture status
  112382. */
  112383. get: function () {
  112384. return this._captureInterFrameTime;
  112385. },
  112386. /**
  112387. * Enable or disable the inter-frames time capture
  112388. */
  112389. set: function (value) {
  112390. this._captureInterFrameTime = value;
  112391. },
  112392. enumerable: true,
  112393. configurable: true
  112394. });
  112395. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  112396. /**
  112397. * Gets the perf counter used for render time capture
  112398. */
  112399. get: function () {
  112400. return this._renderTime;
  112401. },
  112402. enumerable: true,
  112403. configurable: true
  112404. });
  112405. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  112406. /**
  112407. * Gets the render time capture status
  112408. */
  112409. get: function () {
  112410. return this._captureRenderTime;
  112411. },
  112412. /**
  112413. * Enable or disable the render time capture
  112414. */
  112415. set: function (value) {
  112416. var _this = this;
  112417. if (value === this._captureRenderTime) {
  112418. return;
  112419. }
  112420. this._captureRenderTime = value;
  112421. if (value) {
  112422. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  112423. _this._renderTime.beginMonitoring();
  112424. BABYLON.Tools.StartPerformanceCounter("Main render");
  112425. });
  112426. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  112427. _this._renderTime.endMonitoring(false);
  112428. BABYLON.Tools.EndPerformanceCounter("Main render");
  112429. });
  112430. }
  112431. else {
  112432. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  112433. this._onBeforeDrawPhaseObserver = null;
  112434. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  112435. this._onAfterDrawPhaseObserver = null;
  112436. }
  112437. },
  112438. enumerable: true,
  112439. configurable: true
  112440. });
  112441. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  112442. /**
  112443. * Gets the perf counter used for camera render time capture
  112444. */
  112445. get: function () {
  112446. return this._cameraRenderTime;
  112447. },
  112448. enumerable: true,
  112449. configurable: true
  112450. });
  112451. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  112452. /**
  112453. * Gets the camera render time capture status
  112454. */
  112455. get: function () {
  112456. return this._captureCameraRenderTime;
  112457. },
  112458. /**
  112459. * Enable or disable the camera render time capture
  112460. */
  112461. set: function (value) {
  112462. var _this = this;
  112463. if (value === this._captureCameraRenderTime) {
  112464. return;
  112465. }
  112466. this._captureCameraRenderTime = value;
  112467. if (value) {
  112468. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  112469. _this._cameraRenderTime.beginMonitoring();
  112470. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  112471. });
  112472. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  112473. _this._cameraRenderTime.endMonitoring(false);
  112474. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  112475. });
  112476. }
  112477. else {
  112478. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  112479. this._onBeforeCameraRenderObserver = null;
  112480. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  112481. this._onAfterCameraRenderObserver = null;
  112482. }
  112483. },
  112484. enumerable: true,
  112485. configurable: true
  112486. });
  112487. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  112488. /**
  112489. * Gets the perf counter used for draw calls
  112490. */
  112491. get: function () {
  112492. return this.scene.getEngine()._drawCalls;
  112493. },
  112494. enumerable: true,
  112495. configurable: true
  112496. });
  112497. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  112498. /**
  112499. * Gets the perf counter used for texture collisions
  112500. */
  112501. get: function () {
  112502. return this.scene.getEngine()._textureCollisions;
  112503. },
  112504. enumerable: true,
  112505. configurable: true
  112506. });
  112507. /**
  112508. * Dispose and release associated resources.
  112509. */
  112510. SceneInstrumentation.prototype.dispose = function () {
  112511. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  112512. this._onAfterRenderObserver = null;
  112513. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  112514. this._onBeforeActiveMeshesEvaluationObserver = null;
  112515. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  112516. this._onAfterActiveMeshesEvaluationObserver = null;
  112517. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  112518. this._onBeforeRenderTargetsRenderObserver = null;
  112519. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  112520. this._onAfterRenderTargetsRenderObserver = null;
  112521. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  112522. this._onBeforeAnimationsObserver = null;
  112523. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  112524. this._onBeforeParticlesRenderingObserver = null;
  112525. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  112526. this._onAfterParticlesRenderingObserver = null;
  112527. if (this._onBeforeSpritesRenderingObserver) {
  112528. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  112529. this._onBeforeSpritesRenderingObserver = null;
  112530. }
  112531. if (this._onAfterSpritesRenderingObserver) {
  112532. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  112533. this._onAfterSpritesRenderingObserver = null;
  112534. }
  112535. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  112536. this._onBeforeDrawPhaseObserver = null;
  112537. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  112538. this._onAfterDrawPhaseObserver = null;
  112539. if (this._onBeforePhysicsObserver) {
  112540. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  112541. this._onBeforePhysicsObserver = null;
  112542. }
  112543. if (this._onAfterPhysicsObserver) {
  112544. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  112545. this._onAfterPhysicsObserver = null;
  112546. }
  112547. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  112548. this._onAfterAnimationsObserver = null;
  112549. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  112550. this._onBeforeCameraRenderObserver = null;
  112551. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  112552. this._onAfterCameraRenderObserver = null;
  112553. this.scene = null;
  112554. };
  112555. return SceneInstrumentation;
  112556. }());
  112557. BABYLON.SceneInstrumentation = SceneInstrumentation;
  112558. })(BABYLON || (BABYLON = {}));
  112559. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  112560. var BABYLON;
  112561. (function (BABYLON) {
  112562. /**
  112563. * @hidden
  112564. **/
  112565. var _TimeToken = /** @class */ (function () {
  112566. function _TimeToken() {
  112567. this._timeElapsedQueryEnded = false;
  112568. }
  112569. return _TimeToken;
  112570. }());
  112571. BABYLON._TimeToken = _TimeToken;
  112572. })(BABYLON || (BABYLON = {}));
  112573. //# sourceMappingURL=babylon.timeToken.js.map
  112574. var BABYLON;
  112575. (function (BABYLON) {
  112576. /**
  112577. * Background material defines definition.
  112578. * @hidden Mainly internal Use
  112579. */
  112580. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  112581. __extends(BackgroundMaterialDefines, _super);
  112582. /**
  112583. * Constructor of the defines.
  112584. */
  112585. function BackgroundMaterialDefines() {
  112586. var _this = _super.call(this) || this;
  112587. /**
  112588. * True if the diffuse texture is in use.
  112589. */
  112590. _this.DIFFUSE = false;
  112591. /**
  112592. * The direct UV channel to use.
  112593. */
  112594. _this.DIFFUSEDIRECTUV = 0;
  112595. /**
  112596. * True if the diffuse texture is in gamma space.
  112597. */
  112598. _this.GAMMADIFFUSE = false;
  112599. /**
  112600. * True if the diffuse texture has opacity in the alpha channel.
  112601. */
  112602. _this.DIFFUSEHASALPHA = false;
  112603. /**
  112604. * True if you want the material to fade to transparent at grazing angle.
  112605. */
  112606. _this.OPACITYFRESNEL = false;
  112607. /**
  112608. * True if an extra blur needs to be added in the reflection.
  112609. */
  112610. _this.REFLECTIONBLUR = false;
  112611. /**
  112612. * True if you want the material to fade to reflection at grazing angle.
  112613. */
  112614. _this.REFLECTIONFRESNEL = false;
  112615. /**
  112616. * True if you want the material to falloff as far as you move away from the scene center.
  112617. */
  112618. _this.REFLECTIONFALLOFF = false;
  112619. /**
  112620. * False if the current Webgl implementation does not support the texture lod extension.
  112621. */
  112622. _this.TEXTURELODSUPPORT = false;
  112623. /**
  112624. * True to ensure the data are premultiplied.
  112625. */
  112626. _this.PREMULTIPLYALPHA = false;
  112627. /**
  112628. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  112629. */
  112630. _this.USERGBCOLOR = false;
  112631. /**
  112632. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  112633. * stays aligned with the desired configuration.
  112634. */
  112635. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  112636. /**
  112637. * True to add noise in order to reduce the banding effect.
  112638. */
  112639. _this.NOISE = false;
  112640. /**
  112641. * is the reflection texture in BGR color scheme?
  112642. * Mainly used to solve a bug in ios10 video tag
  112643. */
  112644. _this.REFLECTIONBGR = false;
  112645. _this.IMAGEPROCESSING = false;
  112646. _this.VIGNETTE = false;
  112647. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  112648. _this.VIGNETTEBLENDMODEOPAQUE = false;
  112649. _this.TONEMAPPING = false;
  112650. _this.TONEMAPPING_ACES = false;
  112651. _this.CONTRAST = false;
  112652. _this.COLORCURVES = false;
  112653. _this.COLORGRADING = false;
  112654. _this.COLORGRADING3D = false;
  112655. _this.SAMPLER3DGREENDEPTH = false;
  112656. _this.SAMPLER3DBGRMAP = false;
  112657. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  112658. _this.EXPOSURE = false;
  112659. // Reflection.
  112660. _this.REFLECTION = false;
  112661. _this.REFLECTIONMAP_3D = false;
  112662. _this.REFLECTIONMAP_SPHERICAL = false;
  112663. _this.REFLECTIONMAP_PLANAR = false;
  112664. _this.REFLECTIONMAP_CUBIC = false;
  112665. _this.REFLECTIONMAP_PROJECTION = false;
  112666. _this.REFLECTIONMAP_SKYBOX = false;
  112667. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  112668. _this.REFLECTIONMAP_EXPLICIT = false;
  112669. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  112670. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  112671. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  112672. _this.INVERTCUBICMAP = false;
  112673. _this.REFLECTIONMAP_OPPOSITEZ = false;
  112674. _this.LODINREFLECTIONALPHA = false;
  112675. _this.GAMMAREFLECTION = false;
  112676. _this.RGBDREFLECTION = false;
  112677. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  112678. // Default BJS.
  112679. _this.MAINUV1 = false;
  112680. _this.MAINUV2 = false;
  112681. _this.UV1 = false;
  112682. _this.UV2 = false;
  112683. _this.CLIPPLANE = false;
  112684. _this.CLIPPLANE2 = false;
  112685. _this.CLIPPLANE3 = false;
  112686. _this.CLIPPLANE4 = false;
  112687. _this.POINTSIZE = false;
  112688. _this.FOG = false;
  112689. _this.NORMAL = false;
  112690. _this.NUM_BONE_INFLUENCERS = 0;
  112691. _this.BonesPerMesh = 0;
  112692. _this.INSTANCES = false;
  112693. _this.SHADOWFLOAT = false;
  112694. _this.rebuild();
  112695. return _this;
  112696. }
  112697. return BackgroundMaterialDefines;
  112698. }(BABYLON.MaterialDefines));
  112699. /**
  112700. * Background material used to create an efficient environement around your scene.
  112701. */
  112702. var BackgroundMaterial = /** @class */ (function (_super) {
  112703. __extends(BackgroundMaterial, _super);
  112704. /**
  112705. * Instantiates a Background Material in the given scene
  112706. * @param name The friendly name of the material
  112707. * @param scene The scene to add the material to
  112708. */
  112709. function BackgroundMaterial(name, scene) {
  112710. var _this = _super.call(this, name, scene) || this;
  112711. /**
  112712. * Key light Color (multiply against the environement texture)
  112713. */
  112714. _this.primaryColor = BABYLON.Color3.White();
  112715. _this._primaryColorShadowLevel = 0;
  112716. _this._primaryColorHighlightLevel = 0;
  112717. /**
  112718. * Reflection Texture used in the material.
  112719. * Should be author in a specific way for the best result (refer to the documentation).
  112720. */
  112721. _this.reflectionTexture = null;
  112722. /**
  112723. * Reflection Texture level of blur.
  112724. *
  112725. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  112726. * texture twice.
  112727. */
  112728. _this.reflectionBlur = 0;
  112729. /**
  112730. * Diffuse Texture used in the material.
  112731. * Should be author in a specific way for the best result (refer to the documentation).
  112732. */
  112733. _this.diffuseTexture = null;
  112734. _this._shadowLights = null;
  112735. /**
  112736. * Specify the list of lights casting shadow on the material.
  112737. * All scene shadow lights will be included if null.
  112738. */
  112739. _this.shadowLights = null;
  112740. /**
  112741. * Helps adjusting the shadow to a softer level if required.
  112742. * 0 means black shadows and 1 means no shadows.
  112743. */
  112744. _this.shadowLevel = 0;
  112745. /**
  112746. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  112747. * It is usually zero but might be interesting to modify according to your setup.
  112748. */
  112749. _this.sceneCenter = BABYLON.Vector3.Zero();
  112750. /**
  112751. * This helps specifying that the material is falling off to the sky box at grazing angle.
  112752. * This helps ensuring a nice transition when the camera goes under the ground.
  112753. */
  112754. _this.opacityFresnel = true;
  112755. /**
  112756. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  112757. * This helps adding a mirror texture on the ground.
  112758. */
  112759. _this.reflectionFresnel = false;
  112760. /**
  112761. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  112762. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  112763. */
  112764. _this.reflectionFalloffDistance = 0.0;
  112765. /**
  112766. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  112767. */
  112768. _this.reflectionAmount = 1.0;
  112769. /**
  112770. * This specifies the weight of the reflection at grazing angle.
  112771. */
  112772. _this.reflectionReflectance0 = 0.05;
  112773. /**
  112774. * This specifies the weight of the reflection at a perpendicular point of view.
  112775. */
  112776. _this.reflectionReflectance90 = 0.5;
  112777. /**
  112778. * Helps to directly use the maps channels instead of their level.
  112779. */
  112780. _this.useRGBColor = true;
  112781. /**
  112782. * This helps reducing the banding effect that could occur on the background.
  112783. */
  112784. _this.enableNoise = false;
  112785. _this._fovMultiplier = 1.0;
  112786. /**
  112787. * Enable the FOV adjustment feature controlled by fovMultiplier.
  112788. */
  112789. _this.useEquirectangularFOV = false;
  112790. _this._maxSimultaneousLights = 4;
  112791. /**
  112792. * Number of Simultaneous lights allowed on the material.
  112793. */
  112794. _this.maxSimultaneousLights = 4;
  112795. /**
  112796. * Keep track of the image processing observer to allow dispose and replace.
  112797. */
  112798. _this._imageProcessingObserver = null;
  112799. /**
  112800. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  112801. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  112802. */
  112803. _this.switchToBGR = false;
  112804. // Temp values kept as cache in the material.
  112805. _this._renderTargets = new BABYLON.SmartArray(16);
  112806. _this._reflectionControls = BABYLON.Vector4.Zero();
  112807. _this._white = BABYLON.Color3.White();
  112808. _this._primaryShadowColor = BABYLON.Color3.Black();
  112809. _this._primaryHighlightColor = BABYLON.Color3.Black();
  112810. // Setup the default processing configuration to the scene.
  112811. _this._attachImageProcessingConfiguration(null);
  112812. _this.getRenderTargetTextures = function () {
  112813. _this._renderTargets.reset();
  112814. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  112815. _this._renderTargets.push(_this._diffuseTexture);
  112816. }
  112817. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  112818. _this._renderTargets.push(_this._reflectionTexture);
  112819. }
  112820. return _this._renderTargets;
  112821. };
  112822. return _this;
  112823. }
  112824. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  112825. /**
  112826. * Experimental Internal Use Only.
  112827. *
  112828. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  112829. * This acts as a helper to set the primary color to a more "human friendly" value.
  112830. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  112831. * output color as close as possible from the chosen value.
  112832. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  112833. * part of lighting setup.)
  112834. */
  112835. get: function () {
  112836. return this.__perceptualColor;
  112837. },
  112838. set: function (value) {
  112839. this.__perceptualColor = value;
  112840. this._computePrimaryColorFromPerceptualColor();
  112841. this._markAllSubMeshesAsLightsDirty();
  112842. },
  112843. enumerable: true,
  112844. configurable: true
  112845. });
  112846. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  112847. /**
  112848. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  112849. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  112850. */
  112851. get: function () {
  112852. return this._primaryColorShadowLevel;
  112853. },
  112854. set: function (value) {
  112855. this._primaryColorShadowLevel = value;
  112856. this._computePrimaryColors();
  112857. this._markAllSubMeshesAsLightsDirty();
  112858. },
  112859. enumerable: true,
  112860. configurable: true
  112861. });
  112862. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  112863. /**
  112864. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  112865. * The primary color is used at the level chosen to define what the white area would look.
  112866. */
  112867. get: function () {
  112868. return this._primaryColorHighlightLevel;
  112869. },
  112870. set: function (value) {
  112871. this._primaryColorHighlightLevel = value;
  112872. this._computePrimaryColors();
  112873. this._markAllSubMeshesAsLightsDirty();
  112874. },
  112875. enumerable: true,
  112876. configurable: true
  112877. });
  112878. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  112879. /**
  112880. * Sets the reflection reflectance fresnel values according to the default standard
  112881. * empirically know to work well :-)
  112882. */
  112883. set: function (value) {
  112884. var reflectionWeight = value;
  112885. if (reflectionWeight < 0.5) {
  112886. reflectionWeight = reflectionWeight * 2.0;
  112887. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  112888. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  112889. }
  112890. else {
  112891. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  112892. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  112893. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  112894. }
  112895. },
  112896. enumerable: true,
  112897. configurable: true
  112898. });
  112899. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  112900. /**
  112901. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112902. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  112903. * Recommended to be keep at 1.0 except for special cases.
  112904. */
  112905. get: function () {
  112906. return this._fovMultiplier;
  112907. },
  112908. set: function (value) {
  112909. if (isNaN(value)) {
  112910. value = 1.0;
  112911. }
  112912. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  112913. },
  112914. enumerable: true,
  112915. configurable: true
  112916. });
  112917. /**
  112918. * Attaches a new image processing configuration to the PBR Material.
  112919. * @param configuration (if null the scene configuration will be use)
  112920. */
  112921. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  112922. var _this = this;
  112923. if (configuration === this._imageProcessingConfiguration) {
  112924. return;
  112925. }
  112926. // Detaches observer.
  112927. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  112928. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  112929. }
  112930. // Pick the scene configuration if needed.
  112931. if (!configuration) {
  112932. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  112933. }
  112934. else {
  112935. this._imageProcessingConfiguration = configuration;
  112936. }
  112937. // Attaches observer.
  112938. if (this._imageProcessingConfiguration) {
  112939. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  112940. _this._computePrimaryColorFromPerceptualColor();
  112941. _this._markAllSubMeshesAsImageProcessingDirty();
  112942. });
  112943. }
  112944. };
  112945. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  112946. /**
  112947. * Gets the image processing configuration used either in this material.
  112948. */
  112949. get: function () {
  112950. return this._imageProcessingConfiguration;
  112951. },
  112952. /**
  112953. * Sets the Default image processing configuration used either in the this material.
  112954. *
  112955. * If sets to null, the scene one is in use.
  112956. */
  112957. set: function (value) {
  112958. this._attachImageProcessingConfiguration(value);
  112959. // Ensure the effect will be rebuilt.
  112960. this._markAllSubMeshesAsTexturesDirty();
  112961. },
  112962. enumerable: true,
  112963. configurable: true
  112964. });
  112965. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  112966. /**
  112967. * Gets wether the color curves effect is enabled.
  112968. */
  112969. get: function () {
  112970. return this.imageProcessingConfiguration.colorCurvesEnabled;
  112971. },
  112972. /**
  112973. * Sets wether the color curves effect is enabled.
  112974. */
  112975. set: function (value) {
  112976. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  112977. },
  112978. enumerable: true,
  112979. configurable: true
  112980. });
  112981. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  112982. /**
  112983. * Gets wether the color grading effect is enabled.
  112984. */
  112985. get: function () {
  112986. return this.imageProcessingConfiguration.colorGradingEnabled;
  112987. },
  112988. /**
  112989. * Gets wether the color grading effect is enabled.
  112990. */
  112991. set: function (value) {
  112992. this.imageProcessingConfiguration.colorGradingEnabled = value;
  112993. },
  112994. enumerable: true,
  112995. configurable: true
  112996. });
  112997. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  112998. /**
  112999. * Gets wether tonemapping is enabled or not.
  113000. */
  113001. get: function () {
  113002. return this._imageProcessingConfiguration.toneMappingEnabled;
  113003. },
  113004. /**
  113005. * Sets wether tonemapping is enabled or not
  113006. */
  113007. set: function (value) {
  113008. this._imageProcessingConfiguration.toneMappingEnabled = value;
  113009. },
  113010. enumerable: true,
  113011. configurable: true
  113012. });
  113013. ;
  113014. ;
  113015. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  113016. /**
  113017. * The camera exposure used on this material.
  113018. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  113019. * This corresponds to a photographic exposure.
  113020. */
  113021. get: function () {
  113022. return this._imageProcessingConfiguration.exposure;
  113023. },
  113024. /**
  113025. * The camera exposure used on this material.
  113026. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  113027. * This corresponds to a photographic exposure.
  113028. */
  113029. set: function (value) {
  113030. this._imageProcessingConfiguration.exposure = value;
  113031. },
  113032. enumerable: true,
  113033. configurable: true
  113034. });
  113035. ;
  113036. ;
  113037. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  113038. /**
  113039. * Gets The camera contrast used on this material.
  113040. */
  113041. get: function () {
  113042. return this._imageProcessingConfiguration.contrast;
  113043. },
  113044. /**
  113045. * Sets The camera contrast used on this material.
  113046. */
  113047. set: function (value) {
  113048. this._imageProcessingConfiguration.contrast = value;
  113049. },
  113050. enumerable: true,
  113051. configurable: true
  113052. });
  113053. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  113054. /**
  113055. * Gets the Color Grading 2D Lookup Texture.
  113056. */
  113057. get: function () {
  113058. return this._imageProcessingConfiguration.colorGradingTexture;
  113059. },
  113060. /**
  113061. * Sets the Color Grading 2D Lookup Texture.
  113062. */
  113063. set: function (value) {
  113064. this.imageProcessingConfiguration.colorGradingTexture = value;
  113065. },
  113066. enumerable: true,
  113067. configurable: true
  113068. });
  113069. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  113070. /**
  113071. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  113072. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  113073. * 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;
  113074. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  113075. */
  113076. get: function () {
  113077. return this.imageProcessingConfiguration.colorCurves;
  113078. },
  113079. /**
  113080. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  113081. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  113082. * 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;
  113083. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  113084. */
  113085. set: function (value) {
  113086. this.imageProcessingConfiguration.colorCurves = value;
  113087. },
  113088. enumerable: true,
  113089. configurable: true
  113090. });
  113091. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  113092. /**
  113093. * Gets a boolean indicating that current material needs to register RTT
  113094. */
  113095. get: function () {
  113096. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  113097. return true;
  113098. }
  113099. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  113100. return true;
  113101. }
  113102. return false;
  113103. },
  113104. enumerable: true,
  113105. configurable: true
  113106. });
  113107. /**
  113108. * The entire material has been created in order to prevent overdraw.
  113109. * @returns false
  113110. */
  113111. BackgroundMaterial.prototype.needAlphaTesting = function () {
  113112. return true;
  113113. };
  113114. /**
  113115. * The entire material has been created in order to prevent overdraw.
  113116. * @returns true if blending is enable
  113117. */
  113118. BackgroundMaterial.prototype.needAlphaBlending = function () {
  113119. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  113120. };
  113121. /**
  113122. * Checks wether the material is ready to be rendered for a given mesh.
  113123. * @param mesh The mesh to render
  113124. * @param subMesh The submesh to check against
  113125. * @param useInstances Specify wether or not the material is used with instances
  113126. * @returns true if all the dependencies are ready (Textures, Effects...)
  113127. */
  113128. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  113129. var _this = this;
  113130. if (useInstances === void 0) { useInstances = false; }
  113131. if (subMesh.effect && this.isFrozen) {
  113132. if (this._wasPreviouslyReady) {
  113133. return true;
  113134. }
  113135. }
  113136. if (!subMesh._materialDefines) {
  113137. subMesh._materialDefines = new BackgroundMaterialDefines();
  113138. }
  113139. var scene = this.getScene();
  113140. var defines = subMesh._materialDefines;
  113141. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  113142. if (defines._renderId === scene.getRenderId()) {
  113143. return true;
  113144. }
  113145. }
  113146. var engine = scene.getEngine();
  113147. // Lights
  113148. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  113149. defines._needNormals = true;
  113150. // Textures
  113151. if (defines._areTexturesDirty) {
  113152. defines._needUVs = false;
  113153. if (scene.texturesEnabled) {
  113154. if (scene.getEngine().getCaps().textureLOD) {
  113155. defines.TEXTURELODSUPPORT = true;
  113156. }
  113157. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113158. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  113159. return false;
  113160. }
  113161. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  113162. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  113163. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  113164. defines.OPACITYFRESNEL = this._opacityFresnel;
  113165. }
  113166. else {
  113167. defines.DIFFUSE = false;
  113168. defines.DIFFUSEHASALPHA = false;
  113169. defines.GAMMADIFFUSE = false;
  113170. defines.OPACITYFRESNEL = false;
  113171. }
  113172. var reflectionTexture = this._reflectionTexture;
  113173. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113174. if (!reflectionTexture.isReadyOrNotBlocking()) {
  113175. return false;
  113176. }
  113177. defines.REFLECTION = true;
  113178. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  113179. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  113180. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  113181. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  113182. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  113183. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  113184. defines.REFLECTIONBGR = this.switchToBGR;
  113185. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  113186. defines.INVERTCUBICMAP = true;
  113187. }
  113188. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  113189. switch (reflectionTexture.coordinatesMode) {
  113190. case BABYLON.Texture.EXPLICIT_MODE:
  113191. defines.REFLECTIONMAP_EXPLICIT = true;
  113192. break;
  113193. case BABYLON.Texture.PLANAR_MODE:
  113194. defines.REFLECTIONMAP_PLANAR = true;
  113195. break;
  113196. case BABYLON.Texture.PROJECTION_MODE:
  113197. defines.REFLECTIONMAP_PROJECTION = true;
  113198. break;
  113199. case BABYLON.Texture.SKYBOX_MODE:
  113200. defines.REFLECTIONMAP_SKYBOX = true;
  113201. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  113202. break;
  113203. case BABYLON.Texture.SPHERICAL_MODE:
  113204. defines.REFLECTIONMAP_SPHERICAL = true;
  113205. break;
  113206. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  113207. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  113208. break;
  113209. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  113210. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  113211. break;
  113212. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  113213. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  113214. break;
  113215. case BABYLON.Texture.CUBIC_MODE:
  113216. case BABYLON.Texture.INVCUBIC_MODE:
  113217. default:
  113218. defines.REFLECTIONMAP_CUBIC = true;
  113219. break;
  113220. }
  113221. if (this.reflectionFresnel) {
  113222. defines.REFLECTIONFRESNEL = true;
  113223. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  113224. this._reflectionControls.x = this.reflectionAmount;
  113225. this._reflectionControls.y = this.reflectionReflectance0;
  113226. this._reflectionControls.z = this.reflectionReflectance90;
  113227. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  113228. }
  113229. else {
  113230. defines.REFLECTIONFRESNEL = false;
  113231. defines.REFLECTIONFALLOFF = false;
  113232. }
  113233. }
  113234. else {
  113235. defines.REFLECTION = false;
  113236. defines.REFLECTIONFRESNEL = false;
  113237. defines.REFLECTIONFALLOFF = false;
  113238. defines.REFLECTIONBLUR = false;
  113239. defines.REFLECTIONMAP_3D = false;
  113240. defines.REFLECTIONMAP_SPHERICAL = false;
  113241. defines.REFLECTIONMAP_PLANAR = false;
  113242. defines.REFLECTIONMAP_CUBIC = false;
  113243. defines.REFLECTIONMAP_PROJECTION = false;
  113244. defines.REFLECTIONMAP_SKYBOX = false;
  113245. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  113246. defines.REFLECTIONMAP_EXPLICIT = false;
  113247. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  113248. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  113249. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  113250. defines.INVERTCUBICMAP = false;
  113251. defines.REFLECTIONMAP_OPPOSITEZ = false;
  113252. defines.LODINREFLECTIONALPHA = false;
  113253. defines.GAMMAREFLECTION = false;
  113254. defines.RGBDREFLECTION = false;
  113255. }
  113256. }
  113257. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  113258. defines.USERGBCOLOR = this._useRGBColor;
  113259. defines.NOISE = this._enableNoise;
  113260. }
  113261. if (defines._areLightsDirty) {
  113262. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  113263. }
  113264. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  113265. if (!this._imageProcessingConfiguration.isReady()) {
  113266. return false;
  113267. }
  113268. this._imageProcessingConfiguration.prepareDefines(defines);
  113269. }
  113270. // Misc.
  113271. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  113272. // Values that need to be evaluated on every frame
  113273. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  113274. // Attribs
  113275. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  113276. if (mesh) {
  113277. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  113278. mesh.createNormals(true);
  113279. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  113280. }
  113281. }
  113282. }
  113283. // Get correct effect
  113284. if (defines.isDirty) {
  113285. defines.markAsProcessed();
  113286. scene.resetCachedMaterial();
  113287. // Fallbacks
  113288. var fallbacks = new BABYLON.EffectFallbacks();
  113289. if (defines.FOG) {
  113290. fallbacks.addFallback(0, "FOG");
  113291. }
  113292. if (defines.POINTSIZE) {
  113293. fallbacks.addFallback(1, "POINTSIZE");
  113294. }
  113295. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  113296. if (defines.NUM_BONE_INFLUENCERS > 0) {
  113297. fallbacks.addCPUSkinningFallback(0, mesh);
  113298. }
  113299. //Attributes
  113300. var attribs = [BABYLON.VertexBuffer.PositionKind];
  113301. if (defines.NORMAL) {
  113302. attribs.push(BABYLON.VertexBuffer.NormalKind);
  113303. }
  113304. if (defines.UV1) {
  113305. attribs.push(BABYLON.VertexBuffer.UVKind);
  113306. }
  113307. if (defines.UV2) {
  113308. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  113309. }
  113310. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  113311. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  113312. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  113313. "vFogInfos", "vFogColor", "pointSize",
  113314. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  113315. "vPrimaryColor", "vPrimaryColorShadow",
  113316. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  113317. "shadowLevel", "alpha",
  113318. "vBackgroundCenter", "vReflectionControl",
  113319. "vDiffuseInfos", "diffuseMatrix",
  113320. ];
  113321. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  113322. var uniformBuffers = ["Material", "Scene"];
  113323. if (BABYLON.ImageProcessingConfiguration) {
  113324. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  113325. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  113326. }
  113327. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  113328. uniformsNames: uniforms,
  113329. uniformBuffersNames: uniformBuffers,
  113330. samplers: samplers,
  113331. defines: defines,
  113332. maxSimultaneousLights: this._maxSimultaneousLights
  113333. });
  113334. var onCompiled = function (effect) {
  113335. if (_this.onCompiled) {
  113336. _this.onCompiled(effect);
  113337. }
  113338. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  113339. };
  113340. var join = defines.toString();
  113341. subMesh.setEffect(scene.getEngine().createEffect("background", {
  113342. attributes: attribs,
  113343. uniformsNames: uniforms,
  113344. uniformBuffersNames: uniformBuffers,
  113345. samplers: samplers,
  113346. defines: join,
  113347. fallbacks: fallbacks,
  113348. onCompiled: onCompiled,
  113349. onError: this.onError,
  113350. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  113351. }, engine), defines);
  113352. this.buildUniformLayout();
  113353. }
  113354. if (!subMesh.effect || !subMesh.effect.isReady()) {
  113355. return false;
  113356. }
  113357. defines._renderId = scene.getRenderId();
  113358. this._wasPreviouslyReady = true;
  113359. return true;
  113360. };
  113361. /**
  113362. * Compute the primary color according to the chosen perceptual color.
  113363. */
  113364. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  113365. if (!this.__perceptualColor) {
  113366. return;
  113367. }
  113368. this._primaryColor.copyFrom(this.__perceptualColor);
  113369. // Revert gamma space.
  113370. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  113371. // Revert image processing configuration.
  113372. if (this._imageProcessingConfiguration) {
  113373. // Revert Exposure.
  113374. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  113375. }
  113376. this._computePrimaryColors();
  113377. };
  113378. /**
  113379. * Compute the highlights and shadow colors according to their chosen levels.
  113380. */
  113381. BackgroundMaterial.prototype._computePrimaryColors = function () {
  113382. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  113383. return;
  113384. }
  113385. // Find the highlight color based on the configuration.
  113386. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  113387. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  113388. // Find the shadow color based on the configuration.
  113389. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  113390. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  113391. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  113392. };
  113393. /**
  113394. * Build the uniform buffer used in the material.
  113395. */
  113396. BackgroundMaterial.prototype.buildUniformLayout = function () {
  113397. // Order is important !
  113398. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  113399. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  113400. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  113401. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  113402. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  113403. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  113404. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  113405. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  113406. this._uniformBuffer.addUniform("pointSize", 1);
  113407. this._uniformBuffer.addUniform("shadowLevel", 1);
  113408. this._uniformBuffer.addUniform("alpha", 1);
  113409. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  113410. this._uniformBuffer.addUniform("vReflectionControl", 4);
  113411. this._uniformBuffer.create();
  113412. };
  113413. /**
  113414. * Unbind the material.
  113415. */
  113416. BackgroundMaterial.prototype.unbind = function () {
  113417. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  113418. this._uniformBuffer.setTexture("diffuseSampler", null);
  113419. }
  113420. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  113421. this._uniformBuffer.setTexture("reflectionSampler", null);
  113422. }
  113423. _super.prototype.unbind.call(this);
  113424. };
  113425. /**
  113426. * Bind only the world matrix to the material.
  113427. * @param world The world matrix to bind.
  113428. */
  113429. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  113430. this._activeEffect.setMatrix("world", world);
  113431. };
  113432. /**
  113433. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  113434. * @param world The world matrix to bind.
  113435. * @param subMesh The submesh to bind for.
  113436. */
  113437. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  113438. var scene = this.getScene();
  113439. var defines = subMesh._materialDefines;
  113440. if (!defines) {
  113441. return;
  113442. }
  113443. var effect = subMesh.effect;
  113444. if (!effect) {
  113445. return;
  113446. }
  113447. this._activeEffect = effect;
  113448. // Matrices
  113449. this.bindOnlyWorldMatrix(world);
  113450. // Bones
  113451. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  113452. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  113453. if (mustRebind) {
  113454. this._uniformBuffer.bindToEffect(effect, "Material");
  113455. this.bindViewProjection(effect);
  113456. var reflectionTexture = this._reflectionTexture;
  113457. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  113458. // Texture uniforms
  113459. if (scene.texturesEnabled) {
  113460. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113461. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  113462. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  113463. }
  113464. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113465. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  113466. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  113467. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  113468. }
  113469. }
  113470. if (this.shadowLevel > 0) {
  113471. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  113472. }
  113473. this._uniformBuffer.updateFloat("alpha", this.alpha);
  113474. // Point size
  113475. if (this.pointsCloud) {
  113476. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  113477. }
  113478. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  113479. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  113480. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  113481. }
  113482. else {
  113483. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  113484. }
  113485. }
  113486. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  113487. // Textures
  113488. if (scene.texturesEnabled) {
  113489. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113490. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  113491. }
  113492. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113493. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  113494. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  113495. }
  113496. else if (!defines.REFLECTIONBLUR) {
  113497. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  113498. }
  113499. else {
  113500. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  113501. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  113502. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  113503. }
  113504. if (defines.REFLECTIONFRESNEL) {
  113505. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  113506. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  113507. }
  113508. }
  113509. }
  113510. // Clip plane
  113511. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  113512. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  113513. }
  113514. if (mustRebind || !this.isFrozen) {
  113515. if (scene.lightsEnabled) {
  113516. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  113517. }
  113518. // View
  113519. this.bindView(effect);
  113520. // Fog
  113521. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  113522. // image processing
  113523. if (this._imageProcessingConfiguration) {
  113524. this._imageProcessingConfiguration.bind(this._activeEffect);
  113525. }
  113526. }
  113527. this._uniformBuffer.update();
  113528. this._afterBind(mesh, this._activeEffect);
  113529. };
  113530. /**
  113531. * Dispose the material.
  113532. * @param forceDisposeEffect Force disposal of the associated effect.
  113533. * @param forceDisposeTextures Force disposal of the associated textures.
  113534. */
  113535. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  113536. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  113537. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  113538. if (forceDisposeTextures) {
  113539. if (this.diffuseTexture) {
  113540. this.diffuseTexture.dispose();
  113541. }
  113542. if (this.reflectionTexture) {
  113543. this.reflectionTexture.dispose();
  113544. }
  113545. }
  113546. this._renderTargets.dispose();
  113547. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  113548. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  113549. }
  113550. _super.prototype.dispose.call(this, forceDisposeEffect);
  113551. };
  113552. /**
  113553. * Clones the material.
  113554. * @param name The cloned name.
  113555. * @returns The cloned material.
  113556. */
  113557. BackgroundMaterial.prototype.clone = function (name) {
  113558. var _this = this;
  113559. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  113560. };
  113561. /**
  113562. * Serializes the current material to its JSON representation.
  113563. * @returns The JSON representation.
  113564. */
  113565. BackgroundMaterial.prototype.serialize = function () {
  113566. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  113567. serializationObject.customType = "BABYLON.BackgroundMaterial";
  113568. return serializationObject;
  113569. };
  113570. /**
  113571. * Gets the class name of the material
  113572. * @returns "BackgroundMaterial"
  113573. */
  113574. BackgroundMaterial.prototype.getClassName = function () {
  113575. return "BackgroundMaterial";
  113576. };
  113577. /**
  113578. * Parse a JSON input to create back a background material.
  113579. * @param source The JSON data to parse
  113580. * @param scene The scene to create the parsed material in
  113581. * @param rootUrl The root url of the assets the material depends upon
  113582. * @returns the instantiated BackgroundMaterial.
  113583. */
  113584. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  113585. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  113586. };
  113587. /**
  113588. * Standard reflectance value at parallel view angle.
  113589. */
  113590. BackgroundMaterial.StandardReflectance0 = 0.05;
  113591. /**
  113592. * Standard reflectance value at grazing angle.
  113593. */
  113594. BackgroundMaterial.StandardReflectance90 = 0.5;
  113595. __decorate([
  113596. BABYLON.serializeAsColor3()
  113597. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  113598. __decorate([
  113599. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  113600. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  113601. __decorate([
  113602. BABYLON.serializeAsColor3()
  113603. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  113604. __decorate([
  113605. BABYLON.serialize()
  113606. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  113607. __decorate([
  113608. BABYLON.serialize()
  113609. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  113610. __decorate([
  113611. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  113612. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  113613. __decorate([
  113614. BABYLON.serializeAsTexture()
  113615. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  113616. __decorate([
  113617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113618. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  113619. __decorate([
  113620. BABYLON.serialize()
  113621. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  113622. __decorate([
  113623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113624. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  113625. __decorate([
  113626. BABYLON.serializeAsTexture()
  113627. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  113628. __decorate([
  113629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113630. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  113631. __decorate([
  113632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113633. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  113634. __decorate([
  113635. BABYLON.serialize()
  113636. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  113637. __decorate([
  113638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113639. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  113640. __decorate([
  113641. BABYLON.serializeAsVector3()
  113642. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  113643. __decorate([
  113644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113645. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  113646. __decorate([
  113647. BABYLON.serialize()
  113648. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  113649. __decorate([
  113650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113651. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  113652. __decorate([
  113653. BABYLON.serialize()
  113654. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  113655. __decorate([
  113656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113657. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  113658. __decorate([
  113659. BABYLON.serialize()
  113660. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  113661. __decorate([
  113662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113663. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  113664. __decorate([
  113665. BABYLON.serialize()
  113666. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  113667. __decorate([
  113668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113669. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  113670. __decorate([
  113671. BABYLON.serialize()
  113672. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  113673. __decorate([
  113674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113675. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  113676. __decorate([
  113677. BABYLON.serialize()
  113678. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  113679. __decorate([
  113680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113681. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  113682. __decorate([
  113683. BABYLON.serialize()
  113684. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  113685. __decorate([
  113686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113687. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  113688. __decorate([
  113689. BABYLON.serialize()
  113690. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  113691. __decorate([
  113692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113693. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  113694. __decorate([
  113695. BABYLON.serialize()
  113696. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  113697. __decorate([
  113698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113699. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  113700. __decorate([
  113701. BABYLON.serializeAsImageProcessingConfiguration()
  113702. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  113703. return BackgroundMaterial;
  113704. }(BABYLON.PushMaterial));
  113705. BABYLON.BackgroundMaterial = BackgroundMaterial;
  113706. })(BABYLON || (BABYLON = {}));
  113707. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  113708. var __assign = (this && this.__assign) || function () {
  113709. __assign = Object.assign || function(t) {
  113710. for (var s, i = 1, n = arguments.length; i < n; i++) {
  113711. s = arguments[i];
  113712. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  113713. t[p] = s[p];
  113714. }
  113715. return t;
  113716. };
  113717. return __assign.apply(this, arguments);
  113718. };
  113719. var BABYLON;
  113720. (function (BABYLON) {
  113721. /**
  113722. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  113723. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  113724. * It also helps with the default setup of your imageProcessing configuration.
  113725. */
  113726. var EnvironmentHelper = /** @class */ (function () {
  113727. /**
  113728. * constructor
  113729. * @param options
  113730. * @param scene The scene to add the material to
  113731. */
  113732. function EnvironmentHelper(options, scene) {
  113733. var _this = this;
  113734. this._errorHandler = function (message, exception) {
  113735. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  113736. };
  113737. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  113738. this._scene = scene;
  113739. this.onErrorObservable = new BABYLON.Observable();
  113740. this._setupBackground();
  113741. this._setupImageProcessing();
  113742. }
  113743. /**
  113744. * Creates the default options for the helper.
  113745. */
  113746. EnvironmentHelper._getDefaultOptions = function () {
  113747. return {
  113748. createGround: true,
  113749. groundSize: 15,
  113750. groundTexture: this._groundTextureCDNUrl,
  113751. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  113752. groundOpacity: 0.9,
  113753. enableGroundShadow: true,
  113754. groundShadowLevel: 0.5,
  113755. enableGroundMirror: false,
  113756. groundMirrorSizeRatio: 0.3,
  113757. groundMirrorBlurKernel: 64,
  113758. groundMirrorAmount: 1,
  113759. groundMirrorFresnelWeight: 1,
  113760. groundMirrorFallOffDistance: 0,
  113761. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  113762. groundYBias: 0.00001,
  113763. createSkybox: true,
  113764. skyboxSize: 20,
  113765. skyboxTexture: this._skyboxTextureCDNUrl,
  113766. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  113767. backgroundYRotation: 0,
  113768. sizeAuto: true,
  113769. rootPosition: BABYLON.Vector3.Zero(),
  113770. setupImageProcessing: true,
  113771. environmentTexture: this._environmentTextureCDNUrl,
  113772. cameraExposure: 0.8,
  113773. cameraContrast: 1.2,
  113774. toneMappingEnabled: true,
  113775. };
  113776. };
  113777. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  113778. /**
  113779. * Gets the root mesh created by the helper.
  113780. */
  113781. get: function () {
  113782. return this._rootMesh;
  113783. },
  113784. enumerable: true,
  113785. configurable: true
  113786. });
  113787. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  113788. /**
  113789. * Gets the skybox created by the helper.
  113790. */
  113791. get: function () {
  113792. return this._skybox;
  113793. },
  113794. enumerable: true,
  113795. configurable: true
  113796. });
  113797. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  113798. /**
  113799. * Gets the skybox texture created by the helper.
  113800. */
  113801. get: function () {
  113802. return this._skyboxTexture;
  113803. },
  113804. enumerable: true,
  113805. configurable: true
  113806. });
  113807. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  113808. /**
  113809. * Gets the skybox material created by the helper.
  113810. */
  113811. get: function () {
  113812. return this._skyboxMaterial;
  113813. },
  113814. enumerable: true,
  113815. configurable: true
  113816. });
  113817. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  113818. /**
  113819. * Gets the ground mesh created by the helper.
  113820. */
  113821. get: function () {
  113822. return this._ground;
  113823. },
  113824. enumerable: true,
  113825. configurable: true
  113826. });
  113827. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  113828. /**
  113829. * Gets the ground texture created by the helper.
  113830. */
  113831. get: function () {
  113832. return this._groundTexture;
  113833. },
  113834. enumerable: true,
  113835. configurable: true
  113836. });
  113837. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  113838. /**
  113839. * Gets the ground mirror created by the helper.
  113840. */
  113841. get: function () {
  113842. return this._groundMirror;
  113843. },
  113844. enumerable: true,
  113845. configurable: true
  113846. });
  113847. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  113848. /**
  113849. * Gets the ground mirror render list to helps pushing the meshes
  113850. * you wish in the ground reflection.
  113851. */
  113852. get: function () {
  113853. if (this._groundMirror) {
  113854. return this._groundMirror.renderList;
  113855. }
  113856. return null;
  113857. },
  113858. enumerable: true,
  113859. configurable: true
  113860. });
  113861. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  113862. /**
  113863. * Gets the ground material created by the helper.
  113864. */
  113865. get: function () {
  113866. return this._groundMaterial;
  113867. },
  113868. enumerable: true,
  113869. configurable: true
  113870. });
  113871. /**
  113872. * Updates the background according to the new options
  113873. * @param options
  113874. */
  113875. EnvironmentHelper.prototype.updateOptions = function (options) {
  113876. var newOptions = __assign({}, this._options, options);
  113877. if (this._ground && !newOptions.createGround) {
  113878. this._ground.dispose();
  113879. this._ground = null;
  113880. }
  113881. if (this._groundMaterial && !newOptions.createGround) {
  113882. this._groundMaterial.dispose();
  113883. this._groundMaterial = null;
  113884. }
  113885. if (this._groundTexture) {
  113886. if (this._options.groundTexture != newOptions.groundTexture) {
  113887. this._groundTexture.dispose();
  113888. this._groundTexture = null;
  113889. }
  113890. }
  113891. if (this._skybox && !newOptions.createSkybox) {
  113892. this._skybox.dispose();
  113893. this._skybox = null;
  113894. }
  113895. if (this._skyboxMaterial && !newOptions.createSkybox) {
  113896. this._skyboxMaterial.dispose();
  113897. this._skyboxMaterial = null;
  113898. }
  113899. if (this._skyboxTexture) {
  113900. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  113901. this._skyboxTexture.dispose();
  113902. this._skyboxTexture = null;
  113903. }
  113904. }
  113905. if (this._groundMirror && !newOptions.enableGroundMirror) {
  113906. this._groundMirror.dispose();
  113907. this._groundMirror = null;
  113908. }
  113909. if (this._scene.environmentTexture) {
  113910. if (this._options.environmentTexture != newOptions.environmentTexture) {
  113911. this._scene.environmentTexture.dispose();
  113912. }
  113913. }
  113914. this._options = newOptions;
  113915. this._setupBackground();
  113916. this._setupImageProcessing();
  113917. };
  113918. /**
  113919. * Sets the primary color of all the available elements.
  113920. * @param color the main color to affect to the ground and the background
  113921. */
  113922. EnvironmentHelper.prototype.setMainColor = function (color) {
  113923. if (this.groundMaterial) {
  113924. this.groundMaterial.primaryColor = color;
  113925. }
  113926. if (this.skyboxMaterial) {
  113927. this.skyboxMaterial.primaryColor = color;
  113928. }
  113929. if (this.groundMirror) {
  113930. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  113931. }
  113932. };
  113933. /**
  113934. * Setup the image processing according to the specified options.
  113935. */
  113936. EnvironmentHelper.prototype._setupImageProcessing = function () {
  113937. if (this._options.setupImageProcessing) {
  113938. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  113939. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  113940. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  113941. this._setupEnvironmentTexture();
  113942. }
  113943. };
  113944. /**
  113945. * Setup the environment texture according to the specified options.
  113946. */
  113947. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  113948. if (this._scene.environmentTexture) {
  113949. return;
  113950. }
  113951. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  113952. this._scene.environmentTexture = this._options.environmentTexture;
  113953. return;
  113954. }
  113955. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  113956. this._scene.environmentTexture = environmentTexture;
  113957. };
  113958. /**
  113959. * Setup the background according to the specified options.
  113960. */
  113961. EnvironmentHelper.prototype._setupBackground = function () {
  113962. if (!this._rootMesh) {
  113963. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  113964. }
  113965. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  113966. var sceneSize = this._getSceneSize();
  113967. if (this._options.createGround) {
  113968. this._setupGround(sceneSize);
  113969. this._setupGroundMaterial();
  113970. this._setupGroundDiffuseTexture();
  113971. if (this._options.enableGroundMirror) {
  113972. this._setupGroundMirrorTexture(sceneSize);
  113973. }
  113974. this._setupMirrorInGroundMaterial();
  113975. }
  113976. if (this._options.createSkybox) {
  113977. this._setupSkybox(sceneSize);
  113978. this._setupSkyboxMaterial();
  113979. this._setupSkyboxReflectionTexture();
  113980. }
  113981. this._rootMesh.position.x = sceneSize.rootPosition.x;
  113982. this._rootMesh.position.z = sceneSize.rootPosition.z;
  113983. this._rootMesh.position.y = sceneSize.rootPosition.y;
  113984. };
  113985. /**
  113986. * Get the scene sizes according to the setup.
  113987. */
  113988. EnvironmentHelper.prototype._getSceneSize = function () {
  113989. var _this = this;
  113990. var groundSize = this._options.groundSize;
  113991. var skyboxSize = this._options.skyboxSize;
  113992. var rootPosition = this._options.rootPosition;
  113993. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  113994. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  113995. }
  113996. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  113997. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  113998. });
  113999. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  114000. if (this._options.sizeAuto) {
  114001. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  114002. this._scene.activeCamera.upperRadiusLimit) {
  114003. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  114004. skyboxSize = groundSize;
  114005. }
  114006. var sceneDiagonalLenght = sceneDiagonal.length();
  114007. if (sceneDiagonalLenght > groundSize) {
  114008. groundSize = sceneDiagonalLenght * 2;
  114009. skyboxSize = groundSize;
  114010. }
  114011. // 10 % bigger.
  114012. groundSize *= 1.1;
  114013. skyboxSize *= 1.5;
  114014. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  114015. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  114016. }
  114017. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  114018. };
  114019. /**
  114020. * Setup the ground according to the specified options.
  114021. */
  114022. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  114023. var _this = this;
  114024. if (!this._ground || this._ground.isDisposed()) {
  114025. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  114026. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  114027. this._ground.parent = this._rootMesh;
  114028. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  114029. }
  114030. this._ground.receiveShadows = this._options.enableGroundShadow;
  114031. };
  114032. /**
  114033. * Setup the ground material according to the specified options.
  114034. */
  114035. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  114036. if (!this._groundMaterial) {
  114037. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  114038. }
  114039. this._groundMaterial.alpha = this._options.groundOpacity;
  114040. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  114041. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  114042. this._groundMaterial.primaryColor = this._options.groundColor;
  114043. this._groundMaterial.useRGBColor = false;
  114044. this._groundMaterial.enableNoise = true;
  114045. if (this._ground) {
  114046. this._ground.material = this._groundMaterial;
  114047. }
  114048. };
  114049. /**
  114050. * Setup the ground diffuse texture according to the specified options.
  114051. */
  114052. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  114053. if (!this._groundMaterial) {
  114054. return;
  114055. }
  114056. if (this._groundTexture) {
  114057. return;
  114058. }
  114059. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  114060. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  114061. return;
  114062. }
  114063. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  114064. diffuseTexture.gammaSpace = false;
  114065. diffuseTexture.hasAlpha = true;
  114066. this._groundMaterial.diffuseTexture = diffuseTexture;
  114067. };
  114068. /**
  114069. * Setup the ground mirror texture according to the specified options.
  114070. */
  114071. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  114072. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114073. if (!this._groundMirror) {
  114074. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  114075. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  114076. this._groundMirror.anisotropicFilteringLevel = 1;
  114077. this._groundMirror.wrapU = wrapping;
  114078. this._groundMirror.wrapV = wrapping;
  114079. this._groundMirror.gammaSpace = false;
  114080. if (this._groundMirror.renderList) {
  114081. for (var i = 0; i < this._scene.meshes.length; i++) {
  114082. var mesh = this._scene.meshes[i];
  114083. if (mesh !== this._ground &&
  114084. mesh !== this._skybox &&
  114085. mesh !== this._rootMesh) {
  114086. this._groundMirror.renderList.push(mesh);
  114087. }
  114088. }
  114089. }
  114090. }
  114091. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  114092. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  114093. };
  114094. /**
  114095. * Setup the ground to receive the mirror texture.
  114096. */
  114097. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  114098. if (this._groundMaterial) {
  114099. this._groundMaterial.reflectionTexture = this._groundMirror;
  114100. this._groundMaterial.reflectionFresnel = true;
  114101. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  114102. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  114103. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  114104. }
  114105. };
  114106. /**
  114107. * Setup the skybox according to the specified options.
  114108. */
  114109. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  114110. var _this = this;
  114111. if (!this._skybox || this._skybox.isDisposed()) {
  114112. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  114113. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  114114. }
  114115. this._skybox.parent = this._rootMesh;
  114116. };
  114117. /**
  114118. * Setup the skybox material according to the specified options.
  114119. */
  114120. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  114121. if (!this._skybox) {
  114122. return;
  114123. }
  114124. if (!this._skyboxMaterial) {
  114125. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  114126. }
  114127. this._skyboxMaterial.useRGBColor = false;
  114128. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  114129. this._skyboxMaterial.enableNoise = true;
  114130. this._skybox.material = this._skyboxMaterial;
  114131. };
  114132. /**
  114133. * Setup the skybox reflection texture according to the specified options.
  114134. */
  114135. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  114136. if (!this._skyboxMaterial) {
  114137. return;
  114138. }
  114139. if (this._skyboxTexture) {
  114140. return;
  114141. }
  114142. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  114143. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  114144. return;
  114145. }
  114146. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  114147. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  114148. this._skyboxTexture.gammaSpace = false;
  114149. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  114150. };
  114151. /**
  114152. * Dispose all the elements created by the Helper.
  114153. */
  114154. EnvironmentHelper.prototype.dispose = function () {
  114155. if (this._groundMaterial) {
  114156. this._groundMaterial.dispose(true, true);
  114157. }
  114158. if (this._skyboxMaterial) {
  114159. this._skyboxMaterial.dispose(true, true);
  114160. }
  114161. this._rootMesh.dispose(false);
  114162. };
  114163. /**
  114164. * Default ground texture URL.
  114165. */
  114166. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  114167. /**
  114168. * Default skybox texture URL.
  114169. */
  114170. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  114171. /**
  114172. * Default environment texture URL.
  114173. */
  114174. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  114175. return EnvironmentHelper;
  114176. }());
  114177. BABYLON.EnvironmentHelper = EnvironmentHelper;
  114178. })(BABYLON || (BABYLON = {}));
  114179. //# sourceMappingURL=babylon.environmentHelper.js.map
  114180. var BABYLON;
  114181. (function (BABYLON) {
  114182. /** Internal class used to store shapes for emitters */
  114183. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  114184. function ParticleSystemSetEmitterCreationOptions() {
  114185. }
  114186. return ParticleSystemSetEmitterCreationOptions;
  114187. }());
  114188. /**
  114189. * Represents a set of particle systems working together to create a specific effect
  114190. */
  114191. var ParticleSystemSet = /** @class */ (function () {
  114192. function ParticleSystemSet() {
  114193. /**
  114194. * Gets the particle system list
  114195. */
  114196. this.systems = new Array();
  114197. }
  114198. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  114199. /**
  114200. * Gets the emitter node used with this set
  114201. */
  114202. get: function () {
  114203. return this._emitterNode;
  114204. },
  114205. enumerable: true,
  114206. configurable: true
  114207. });
  114208. /**
  114209. * Creates a new emitter mesh as a sphere
  114210. * @param options defines the options used to create the sphere
  114211. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  114212. * @param scene defines the hosting scene
  114213. */
  114214. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  114215. if (this._emitterNode) {
  114216. this._emitterNode.dispose();
  114217. }
  114218. this._emitterCreationOptions = {
  114219. kind: "Sphere",
  114220. options: options,
  114221. renderingGroupId: renderingGroupId
  114222. };
  114223. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  114224. emitterMesh.renderingGroupId = renderingGroupId;
  114225. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  114226. material.emissiveColor = options.color;
  114227. emitterMesh.material = material;
  114228. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114229. var system = _a[_i];
  114230. system.emitter = emitterMesh;
  114231. }
  114232. this._emitterNode = emitterMesh;
  114233. };
  114234. /**
  114235. * Starts all particle systems of the set
  114236. * @param emitter defines an optional mesh to use as emitter for the particle systems
  114237. */
  114238. ParticleSystemSet.prototype.start = function (emitter) {
  114239. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114240. var system = _a[_i];
  114241. if (emitter) {
  114242. system.emitter = emitter;
  114243. }
  114244. system.start();
  114245. }
  114246. };
  114247. /**
  114248. * Release all associated resources
  114249. */
  114250. ParticleSystemSet.prototype.dispose = function () {
  114251. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114252. var system = _a[_i];
  114253. system.dispose();
  114254. }
  114255. this.systems = [];
  114256. if (this._emitterNode) {
  114257. this._emitterNode.dispose();
  114258. this._emitterNode = null;
  114259. }
  114260. };
  114261. /**
  114262. * Serialize the set into a JSON compatible object
  114263. * @returns a JSON compatible representation of the set
  114264. */
  114265. ParticleSystemSet.prototype.serialize = function () {
  114266. var result = {};
  114267. result.systems = [];
  114268. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114269. var system = _a[_i];
  114270. result.systems.push(system.serialize());
  114271. }
  114272. if (this._emitterNode) {
  114273. result.emitter = this._emitterCreationOptions;
  114274. }
  114275. return result;
  114276. };
  114277. /**
  114278. * Parse a new ParticleSystemSet from a serialized source
  114279. * @param data defines a JSON compatible representation of the set
  114280. * @param scene defines the hosting scene
  114281. * @param gpu defines if we want GPU particles or CPU particles
  114282. * @returns a new ParticleSystemSet
  114283. */
  114284. ParticleSystemSet.Parse = function (data, scene, gpu) {
  114285. if (gpu === void 0) { gpu = false; }
  114286. var result = new ParticleSystemSet();
  114287. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  114288. scene = scene || BABYLON.Engine.LastCreatedScene;
  114289. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  114290. var system = _a[_i];
  114291. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  114292. }
  114293. if (data.emitter) {
  114294. var options = data.emitter.options;
  114295. switch (data.emitter.kind) {
  114296. case "Sphere":
  114297. result.setEmitterAsSphere({
  114298. diameter: options.diameter,
  114299. segments: options.segments,
  114300. color: BABYLON.Color3.FromArray(options.color)
  114301. }, data.emitter.renderingGroupId, scene);
  114302. break;
  114303. }
  114304. }
  114305. return result;
  114306. };
  114307. return ParticleSystemSet;
  114308. }());
  114309. BABYLON.ParticleSystemSet = ParticleSystemSet;
  114310. })(BABYLON || (BABYLON = {}));
  114311. //# sourceMappingURL=babylon.particleSystemSet.js.map
  114312. var BABYLON;
  114313. (function (BABYLON) {
  114314. /**
  114315. * This class is made for on one-liner static method to help creating particle system set.
  114316. */
  114317. var ParticleHelper = /** @class */ (function () {
  114318. function ParticleHelper() {
  114319. }
  114320. /**
  114321. * Create a default particle system that you can tweak
  114322. * @param emitter defines the emitter to use
  114323. * @param capacity defines the system capacity (default is 500 particles)
  114324. * @param scene defines the hosting scene
  114325. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  114326. * @returns the new Particle system
  114327. */
  114328. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  114329. if (capacity === void 0) { capacity = 500; }
  114330. if (useGPU === void 0) { useGPU = false; }
  114331. var system;
  114332. if (useGPU) {
  114333. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  114334. }
  114335. else {
  114336. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  114337. }
  114338. system.emitter = emitter;
  114339. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  114340. system.createConeEmitter(0.1, Math.PI / 4);
  114341. // Particle color
  114342. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  114343. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  114344. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  114345. // Particle Size
  114346. system.minSize = 0.1;
  114347. system.maxSize = 0.1;
  114348. // Emission speed
  114349. system.minEmitPower = 2;
  114350. system.maxEmitPower = 2;
  114351. // Update speed
  114352. system.updateSpeed = 1 / 60;
  114353. system.emitRate = 30;
  114354. return system;
  114355. };
  114356. /**
  114357. * This is the main static method (one-liner) of this helper to create different particle systems
  114358. * @param type This string represents the type to the particle system to create
  114359. * @param scene The scene where the particle system should live
  114360. * @param gpu If the system will use gpu
  114361. * @returns the ParticleSystemSet created
  114362. */
  114363. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  114364. if (gpu === void 0) { gpu = false; }
  114365. if (!scene) {
  114366. scene = BABYLON.Engine.LastCreatedScene;
  114367. ;
  114368. }
  114369. var token = {};
  114370. scene._addPendingData(token);
  114371. return new Promise(function (resolve, reject) {
  114372. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  114373. scene._removePendingData(token);
  114374. return reject("Particle system with GPU is not supported.");
  114375. }
  114376. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  114377. scene._removePendingData(token);
  114378. var newData = JSON.parse(data.toString());
  114379. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  114380. }, undefined, undefined, undefined, function (req, exception) {
  114381. scene._removePendingData(token);
  114382. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  114383. });
  114384. });
  114385. };
  114386. /**
  114387. * Static function used to export a particle system to a ParticleSystemSet variable.
  114388. * Please note that the emitter shape is not exported
  114389. * @param systems defines the particle systems to export
  114390. * @returns the created particle system set
  114391. */
  114392. ParticleHelper.ExportSet = function (systems) {
  114393. var set = new BABYLON.ParticleSystemSet();
  114394. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  114395. var system = systems_1[_i];
  114396. set.systems.push(system);
  114397. }
  114398. return set;
  114399. };
  114400. /**
  114401. * Gets or sets base Assets URL
  114402. */
  114403. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  114404. return ParticleHelper;
  114405. }());
  114406. BABYLON.ParticleHelper = ParticleHelper;
  114407. })(BABYLON || (BABYLON = {}));
  114408. //# sourceMappingURL=babylon.particleHelper.js.map
  114409. var BABYLON;
  114410. (function (BABYLON) {
  114411. /**
  114412. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  114413. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  114414. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  114415. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  114416. */
  114417. var VideoDome = /** @class */ (function (_super) {
  114418. __extends(VideoDome, _super);
  114419. /**
  114420. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  114421. * @param name Element's name, child elements will append suffixes for their own names.
  114422. * @param urlsOrVideo defines the url(s) or the video element to use
  114423. * @param options An object containing optional or exposed sub element properties
  114424. */
  114425. function VideoDome(name, urlsOrVideo, options, scene) {
  114426. var _this = _super.call(this, name, scene) || this;
  114427. _this._useDirectMapping = false;
  114428. // set defaults and manage values
  114429. name = name || "videoDome";
  114430. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  114431. options.clickToPlay = Boolean(options.clickToPlay);
  114432. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  114433. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  114434. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  114435. if (options.useDirectMapping === undefined) {
  114436. _this._useDirectMapping = true;
  114437. }
  114438. else {
  114439. _this._useDirectMapping = options.useDirectMapping;
  114440. }
  114441. _this._setReady(false);
  114442. // create
  114443. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  114444. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  114445. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  114446. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  114447. texture.onLoadObservable.addOnce(function () {
  114448. _this._setReady(true);
  114449. });
  114450. // configure material
  114451. material.useEquirectangularFOV = true;
  114452. material.fovMultiplier = 1.0;
  114453. material.opacityFresnel = false;
  114454. if (_this._useDirectMapping) {
  114455. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114456. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114457. material.diffuseTexture = texture;
  114458. }
  114459. else {
  114460. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  114461. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114462. material.reflectionTexture = texture;
  114463. }
  114464. // configure mesh
  114465. _this._mesh.material = material;
  114466. _this._mesh.parent = _this;
  114467. // optional configuration
  114468. if (options.clickToPlay) {
  114469. scene.onPointerUp = function () {
  114470. _this._videoTexture.video.play();
  114471. };
  114472. }
  114473. return _this;
  114474. }
  114475. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  114476. /**
  114477. * Gets the video texture being displayed on the sphere
  114478. */
  114479. get: function () {
  114480. return this._videoTexture;
  114481. },
  114482. enumerable: true,
  114483. configurable: true
  114484. });
  114485. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  114486. /**
  114487. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114488. * Also see the options.resolution property.
  114489. */
  114490. get: function () {
  114491. return this._material.fovMultiplier;
  114492. },
  114493. set: function (value) {
  114494. this._material.fovMultiplier = value;
  114495. },
  114496. enumerable: true,
  114497. configurable: true
  114498. });
  114499. /**
  114500. * Releases resources associated with this node.
  114501. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  114502. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  114503. */
  114504. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  114505. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  114506. this._videoTexture.dispose();
  114507. this._mesh.dispose();
  114508. this._material.dispose();
  114509. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  114510. };
  114511. return VideoDome;
  114512. }(BABYLON.TransformNode));
  114513. BABYLON.VideoDome = VideoDome;
  114514. })(BABYLON || (BABYLON = {}));
  114515. //# sourceMappingURL=babylon.videoDome.js.map
  114516. var BABYLON;
  114517. (function (BABYLON) {
  114518. /**
  114519. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  114520. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  114521. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  114522. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  114523. */
  114524. var PhotoDome = /** @class */ (function (_super) {
  114525. __extends(PhotoDome, _super);
  114526. /**
  114527. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  114528. * @param name Element's name, child elements will append suffixes for their own names.
  114529. * @param urlsOfPhoto defines the url of the photo to display
  114530. * @param options defines an object containing optional or exposed sub element properties
  114531. * @param onError defines a callback called when an error occured while loading the texture
  114532. */
  114533. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  114534. if (onError === void 0) { onError = null; }
  114535. var _this = _super.call(this, name, scene) || this;
  114536. _this._useDirectMapping = false;
  114537. /**
  114538. * Observable raised when an error occured while loading the 360 image
  114539. */
  114540. _this.onLoadErrorObservable = new BABYLON.Observable();
  114541. // set defaults and manage values
  114542. name = name || "photoDome";
  114543. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  114544. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  114545. if (options.useDirectMapping === undefined) {
  114546. _this._useDirectMapping = true;
  114547. }
  114548. else {
  114549. _this._useDirectMapping = options.useDirectMapping;
  114550. }
  114551. _this._setReady(false);
  114552. // create
  114553. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  114554. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  114555. // configure material
  114556. material.opacityFresnel = false;
  114557. material.useEquirectangularFOV = true;
  114558. material.fovMultiplier = 1.0;
  114559. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  114560. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  114561. if (onError) {
  114562. onError(message, exception);
  114563. }
  114564. });
  114565. _this.photoTexture.onLoadObservable.addOnce(function () {
  114566. _this._setReady(true);
  114567. });
  114568. // configure mesh
  114569. _this._mesh.material = material;
  114570. _this._mesh.parent = _this;
  114571. return _this;
  114572. }
  114573. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  114574. /**
  114575. * Gets or sets the texture being displayed on the sphere
  114576. */
  114577. get: function () {
  114578. return this._photoTexture;
  114579. },
  114580. set: function (value) {
  114581. if (this._photoTexture === value) {
  114582. return;
  114583. }
  114584. this._photoTexture = value;
  114585. if (this._useDirectMapping) {
  114586. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114587. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114588. this._material.diffuseTexture = this._photoTexture;
  114589. }
  114590. else {
  114591. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  114592. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114593. this._material.reflectionTexture = this._photoTexture;
  114594. }
  114595. },
  114596. enumerable: true,
  114597. configurable: true
  114598. });
  114599. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  114600. /**
  114601. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114602. * Also see the options.resolution property.
  114603. */
  114604. get: function () {
  114605. return this._material.fovMultiplier;
  114606. },
  114607. set: function (value) {
  114608. this._material.fovMultiplier = value;
  114609. },
  114610. enumerable: true,
  114611. configurable: true
  114612. });
  114613. /**
  114614. * Releases resources associated with this node.
  114615. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  114616. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  114617. */
  114618. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  114619. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  114620. this._photoTexture.dispose();
  114621. this._mesh.dispose();
  114622. this._material.dispose();
  114623. this.onLoadErrorObservable.clear();
  114624. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  114625. };
  114626. return PhotoDome;
  114627. }(BABYLON.TransformNode));
  114628. BABYLON.PhotoDome = PhotoDome;
  114629. })(BABYLON || (BABYLON = {}));
  114630. //# sourceMappingURL=babylon.photoDome.js.map
  114631. var BABYLON;
  114632. (function (BABYLON) {
  114633. /** @hidden */
  114634. var _OcclusionDataStorage = /** @class */ (function () {
  114635. function _OcclusionDataStorage() {
  114636. /** @hidden */
  114637. this.occlusionInternalRetryCounter = 0;
  114638. /** @hidden */
  114639. this.isOcclusionQueryInProgress = false;
  114640. /** @hidden */
  114641. this.isOccluded = false;
  114642. /** @hidden */
  114643. this.occlusionRetryCount = -1;
  114644. /** @hidden */
  114645. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  114646. /** @hidden */
  114647. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  114648. }
  114649. return _OcclusionDataStorage;
  114650. }());
  114651. BABYLON.Engine.prototype.createQuery = function () {
  114652. return this._gl.createQuery();
  114653. };
  114654. BABYLON.Engine.prototype.deleteQuery = function (query) {
  114655. this._gl.deleteQuery(query);
  114656. return this;
  114657. };
  114658. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  114659. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  114660. };
  114661. BABYLON.Engine.prototype.getQueryResult = function (query) {
  114662. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  114663. };
  114664. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  114665. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  114666. this._gl.beginQuery(glAlgorithm, query);
  114667. return this;
  114668. };
  114669. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  114670. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  114671. this._gl.endQuery(glAlgorithm);
  114672. return this;
  114673. };
  114674. BABYLON.Engine.prototype._createTimeQuery = function () {
  114675. var timerQuery = this.getCaps().timerQuery;
  114676. if (timerQuery.createQueryEXT) {
  114677. return timerQuery.createQueryEXT();
  114678. }
  114679. return this.createQuery();
  114680. };
  114681. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  114682. var timerQuery = this.getCaps().timerQuery;
  114683. if (timerQuery.deleteQueryEXT) {
  114684. timerQuery.deleteQueryEXT(query);
  114685. return;
  114686. }
  114687. this.deleteQuery(query);
  114688. };
  114689. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  114690. var timerQuery = this.getCaps().timerQuery;
  114691. if (timerQuery.getQueryObjectEXT) {
  114692. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  114693. }
  114694. return this.getQueryResult(query);
  114695. };
  114696. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  114697. var timerQuery = this.getCaps().timerQuery;
  114698. if (timerQuery.getQueryObjectEXT) {
  114699. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  114700. }
  114701. return this.isQueryResultAvailable(query);
  114702. };
  114703. BABYLON.Engine.prototype.startTimeQuery = function () {
  114704. var caps = this.getCaps();
  114705. var timerQuery = caps.timerQuery;
  114706. if (!timerQuery) {
  114707. return null;
  114708. }
  114709. var token = new BABYLON._TimeToken();
  114710. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  114711. if (caps.canUseTimestampForTimerQuery) {
  114712. token._startTimeQuery = this._createTimeQuery();
  114713. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  114714. }
  114715. else {
  114716. if (this._currentNonTimestampToken) {
  114717. return this._currentNonTimestampToken;
  114718. }
  114719. token._timeElapsedQuery = this._createTimeQuery();
  114720. if (timerQuery.beginQueryEXT) {
  114721. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  114722. }
  114723. else {
  114724. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  114725. }
  114726. this._currentNonTimestampToken = token;
  114727. }
  114728. return token;
  114729. };
  114730. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  114731. var caps = this.getCaps();
  114732. var timerQuery = caps.timerQuery;
  114733. if (!timerQuery || !token) {
  114734. return -1;
  114735. }
  114736. if (caps.canUseTimestampForTimerQuery) {
  114737. if (!token._startTimeQuery) {
  114738. return -1;
  114739. }
  114740. if (!token._endTimeQuery) {
  114741. token._endTimeQuery = this._createTimeQuery();
  114742. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  114743. }
  114744. }
  114745. else if (!token._timeElapsedQueryEnded) {
  114746. if (!token._timeElapsedQuery) {
  114747. return -1;
  114748. }
  114749. if (timerQuery.endQueryEXT) {
  114750. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  114751. }
  114752. else {
  114753. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  114754. }
  114755. token._timeElapsedQueryEnded = true;
  114756. }
  114757. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  114758. var available = false;
  114759. if (token._endTimeQuery) {
  114760. available = this._getTimeQueryAvailability(token._endTimeQuery);
  114761. }
  114762. else if (token._timeElapsedQuery) {
  114763. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  114764. }
  114765. if (available && !disjoint) {
  114766. var result = 0;
  114767. if (caps.canUseTimestampForTimerQuery) {
  114768. if (!token._startTimeQuery || !token._endTimeQuery) {
  114769. return -1;
  114770. }
  114771. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  114772. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  114773. result = timeEnd - timeStart;
  114774. this._deleteTimeQuery(token._startTimeQuery);
  114775. this._deleteTimeQuery(token._endTimeQuery);
  114776. token._startTimeQuery = null;
  114777. token._endTimeQuery = null;
  114778. }
  114779. else {
  114780. if (!token._timeElapsedQuery) {
  114781. return -1;
  114782. }
  114783. result = this._getTimeQueryResult(token._timeElapsedQuery);
  114784. this._deleteTimeQuery(token._timeElapsedQuery);
  114785. token._timeElapsedQuery = null;
  114786. token._timeElapsedQueryEnded = false;
  114787. this._currentNonTimestampToken = null;
  114788. }
  114789. return result;
  114790. }
  114791. return -1;
  114792. };
  114793. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  114794. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  114795. };
  114796. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  114797. get: function () {
  114798. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  114799. },
  114800. enumerable: false,
  114801. configurable: true
  114802. });
  114803. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  114804. get: function () {
  114805. if (!this.__occlusionDataStorage) {
  114806. this.__occlusionDataStorage = new _OcclusionDataStorage();
  114807. }
  114808. return this.__occlusionDataStorage;
  114809. },
  114810. enumerable: false,
  114811. configurable: true
  114812. });
  114813. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  114814. get: function () {
  114815. return this._occlusionDataStorage.isOccluded;
  114816. },
  114817. set: function (value) {
  114818. this._occlusionDataStorage.isOccluded = value;
  114819. },
  114820. enumerable: true,
  114821. configurable: true
  114822. });
  114823. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  114824. get: function () {
  114825. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  114826. },
  114827. set: function (value) {
  114828. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  114829. },
  114830. enumerable: true,
  114831. configurable: true
  114832. });
  114833. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  114834. get: function () {
  114835. return this._occlusionDataStorage.occlusionType;
  114836. },
  114837. set: function (value) {
  114838. this._occlusionDataStorage.occlusionType = value;
  114839. },
  114840. enumerable: true,
  114841. configurable: true
  114842. });
  114843. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  114844. get: function () {
  114845. return this._occlusionDataStorage.occlusionRetryCount;
  114846. },
  114847. set: function (value) {
  114848. this._occlusionDataStorage.occlusionRetryCount = value;
  114849. },
  114850. enumerable: true,
  114851. configurable: true
  114852. });
  114853. // We also need to update AbstractMesh as there is a portion of the code there
  114854. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  114855. var dataStorage = this._occlusionDataStorage;
  114856. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  114857. dataStorage.isOccluded = false;
  114858. return false;
  114859. }
  114860. var engine = this.getEngine();
  114861. if (engine.webGLVersion < 2) {
  114862. dataStorage.isOccluded = false;
  114863. return false;
  114864. }
  114865. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  114866. dataStorage.isOccluded = false;
  114867. return false;
  114868. }
  114869. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  114870. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  114871. if (isOcclusionQueryAvailable) {
  114872. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  114873. dataStorage.isOcclusionQueryInProgress = false;
  114874. dataStorage.occlusionInternalRetryCounter = 0;
  114875. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  114876. }
  114877. else {
  114878. dataStorage.occlusionInternalRetryCounter++;
  114879. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  114880. dataStorage.isOcclusionQueryInProgress = false;
  114881. dataStorage.occlusionInternalRetryCounter = 0;
  114882. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  114883. // if strict continue the last state of the object.
  114884. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  114885. }
  114886. else {
  114887. return false;
  114888. }
  114889. }
  114890. }
  114891. var scene = this.getScene();
  114892. if (scene.getBoundingBoxRenderer) {
  114893. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  114894. if (!this._occlusionQuery) {
  114895. this._occlusionQuery = engine.createQuery();
  114896. }
  114897. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  114898. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  114899. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  114900. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  114901. }
  114902. return dataStorage.isOccluded;
  114903. };
  114904. })(BABYLON || (BABYLON = {}));
  114905. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  114906. var BABYLON;
  114907. (function (BABYLON) {
  114908. /**
  114909. * Class used to generate noise procedural textures
  114910. */
  114911. var NoiseProceduralTexture = /** @class */ (function (_super) {
  114912. __extends(NoiseProceduralTexture, _super);
  114913. /**
  114914. * Creates a new NoiseProceduralTexture
  114915. * @param name defines the name fo the texture
  114916. * @param size defines the size of the texture (default is 256)
  114917. * @param scene defines the hosting scene
  114918. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  114919. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  114920. */
  114921. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  114922. if (size === void 0) { size = 256; }
  114923. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  114924. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  114925. _this._time = 0;
  114926. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  114927. _this.brightness = 0.2;
  114928. /** Defines the number of octaves to process */
  114929. _this.octaves = 3;
  114930. /** Defines the level of persistence (0.8 by default) */
  114931. _this.persistence = 0.8;
  114932. /** Gets or sets animation speed factor (default is 1) */
  114933. _this.animationSpeedFactor = 1;
  114934. _this._updateShaderUniforms();
  114935. return _this;
  114936. }
  114937. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  114938. var scene = this.getScene();
  114939. if (!scene) {
  114940. return;
  114941. }
  114942. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  114943. this.setFloat("brightness", this.brightness);
  114944. this.setFloat("persistence", this.persistence);
  114945. this.setFloat("timeScale", this._time);
  114946. };
  114947. NoiseProceduralTexture.prototype._getDefines = function () {
  114948. return "#define OCTAVES " + (this.octaves | 0);
  114949. };
  114950. /** Generate the current state of the procedural texture */
  114951. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  114952. this._updateShaderUniforms();
  114953. _super.prototype.render.call(this, useCameraPostProcess);
  114954. };
  114955. /**
  114956. * Serializes this noise procedural texture
  114957. * @returns a serialized noise procedural texture object
  114958. */
  114959. NoiseProceduralTexture.prototype.serialize = function () {
  114960. var serializationObject = {};
  114961. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  114962. serializationObject.brightness = this.brightness;
  114963. serializationObject.octaves = this.octaves;
  114964. serializationObject.persistence = this.persistence;
  114965. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  114966. serializationObject.size = this.getSize().width;
  114967. serializationObject.generateMipMaps = this._generateMipMaps;
  114968. return serializationObject;
  114969. };
  114970. /**
  114971. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  114972. * @param parsedTexture defines parsed texture data
  114973. * @param scene defines the current scene
  114974. * @param rootUrl defines the root URL containing noise procedural texture information
  114975. * @returns a parsed NoiseProceduralTexture
  114976. */
  114977. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  114978. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  114979. texture.brightness = parsedTexture.brightness;
  114980. texture.octaves = parsedTexture.octaves;
  114981. texture.persistence = parsedTexture.persistence;
  114982. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  114983. return texture;
  114984. };
  114985. return NoiseProceduralTexture;
  114986. }(BABYLON.ProceduralTexture));
  114987. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  114988. })(BABYLON || (BABYLON = {}));
  114989. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  114990. var __assign = (this && this.__assign) || function () {
  114991. __assign = Object.assign || function(t) {
  114992. for (var s, i = 1, n = arguments.length; i < n; i++) {
  114993. s = arguments[i];
  114994. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  114995. t[p] = s[p];
  114996. }
  114997. return t;
  114998. };
  114999. return __assign.apply(this, arguments);
  115000. };
  115001. var BABYLON;
  115002. (function (BABYLON) {
  115003. /**
  115004. * This can helps recording videos from BabylonJS.
  115005. * This is based on the available WebRTC functionalities of the browser.
  115006. *
  115007. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  115008. */
  115009. var VideoRecorder = /** @class */ (function () {
  115010. /**
  115011. * Create a new VideoCapture object which can help converting what you see in Babylon to
  115012. * a video file.
  115013. * @param engine Defines the BabylonJS Engine you wish to record
  115014. * @param options Defines options that can be used to customized the capture
  115015. */
  115016. function VideoRecorder(engine, options) {
  115017. if (options === void 0) { options = null; }
  115018. if (!VideoRecorder.IsSupported(engine)) {
  115019. throw "Your browser does not support recording so far.";
  115020. }
  115021. var canvas = engine.getRenderingCanvas();
  115022. if (!canvas) {
  115023. throw "The babylon engine must have a canvas to be recorded";
  115024. }
  115025. this._canvas = canvas;
  115026. this._canvas.isRecording = false;
  115027. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  115028. var stream = this._canvas.captureStream(this._options.fps);
  115029. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  115030. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  115031. this._mediaRecorder.onerror = this._handleError.bind(this);
  115032. this._mediaRecorder.onstop = this._handleStop.bind(this);
  115033. }
  115034. /**
  115035. * Returns wehther or not the VideoRecorder is available in your browser.
  115036. * @param engine Defines the Babylon Engine to check the support for
  115037. * @returns true if supported otherwise false
  115038. */
  115039. VideoRecorder.IsSupported = function (engine) {
  115040. var canvas = engine.getRenderingCanvas();
  115041. return (!!canvas && typeof canvas.captureStream === "function");
  115042. };
  115043. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  115044. /**
  115045. * True wether a recording is already in progress.
  115046. */
  115047. get: function () {
  115048. return !!this._canvas && this._canvas.isRecording;
  115049. },
  115050. enumerable: true,
  115051. configurable: true
  115052. });
  115053. /**
  115054. * Stops the current recording before the default capture timeout passed in the startRecording
  115055. * functions.
  115056. */
  115057. VideoRecorder.prototype.stopRecording = function () {
  115058. if (!this._canvas || !this._mediaRecorder) {
  115059. return;
  115060. }
  115061. if (!this.isRecording) {
  115062. return;
  115063. }
  115064. this._canvas.isRecording = false;
  115065. this._mediaRecorder.stop();
  115066. };
  115067. /**
  115068. * Starts recording the canvas for a max duration specified in parameters.
  115069. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  115070. * @param maxDuration Defines the maximum recording time in seconds.
  115071. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  115072. * @return a promise callback at the end of the recording with the video data in Blob.
  115073. */
  115074. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  115075. var _this = this;
  115076. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  115077. if (maxDuration === void 0) { maxDuration = 7; }
  115078. if (!this._canvas || !this._mediaRecorder) {
  115079. throw "Recorder has already been disposed";
  115080. }
  115081. if (this.isRecording) {
  115082. throw "Recording already in progress";
  115083. }
  115084. if (maxDuration > 0) {
  115085. setTimeout(function () {
  115086. _this.stopRecording();
  115087. }, maxDuration * 1000);
  115088. }
  115089. this._fileName = fileName;
  115090. this._recordedChunks = [];
  115091. this._resolve = null;
  115092. this._reject = null;
  115093. this._canvas.isRecording = true;
  115094. this._mediaRecorder.start(this._options.recordChunckSize);
  115095. return new Promise(function (resolve, reject) {
  115096. _this._resolve = resolve;
  115097. _this._reject = reject;
  115098. });
  115099. };
  115100. /**
  115101. * Releases internal resources used during the recording.
  115102. */
  115103. VideoRecorder.prototype.dispose = function () {
  115104. this._canvas = null;
  115105. this._mediaRecorder = null;
  115106. this._recordedChunks = [];
  115107. this._fileName = null;
  115108. this._resolve = null;
  115109. this._reject = null;
  115110. };
  115111. VideoRecorder.prototype._handleDataAvailable = function (event) {
  115112. if (event.data.size > 0) {
  115113. this._recordedChunks.push(event.data);
  115114. }
  115115. };
  115116. VideoRecorder.prototype._handleError = function (event) {
  115117. this.stopRecording();
  115118. if (this._reject) {
  115119. this._reject(event.error);
  115120. }
  115121. else {
  115122. throw new event.error;
  115123. }
  115124. };
  115125. VideoRecorder.prototype._handleStop = function () {
  115126. this.stopRecording();
  115127. var superBuffer = new Blob(this._recordedChunks);
  115128. if (this._resolve) {
  115129. this._resolve(superBuffer);
  115130. }
  115131. window.URL.createObjectURL(superBuffer);
  115132. if (this._fileName) {
  115133. BABYLON.Tools.Download(superBuffer, this._fileName);
  115134. }
  115135. };
  115136. VideoRecorder._defaultOptions = {
  115137. mimeType: "video/webm",
  115138. fps: 25,
  115139. recordChunckSize: 3000
  115140. };
  115141. return VideoRecorder;
  115142. }());
  115143. BABYLON.VideoRecorder = VideoRecorder;
  115144. })(BABYLON || (BABYLON = {}));
  115145. //# sourceMappingURL=babylon.videoRecorder.js.map
  115146. var BABYLON;
  115147. (function (BABYLON) {
  115148. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  115149. if (replace === void 0) { replace = false; }
  115150. // Dispose existing light in replace mode.
  115151. if (replace) {
  115152. if (this.lights) {
  115153. for (var i = 0; i < this.lights.length; i++) {
  115154. this.lights[i].dispose();
  115155. }
  115156. }
  115157. }
  115158. // Light
  115159. if (this.lights.length === 0) {
  115160. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  115161. }
  115162. };
  115163. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  115164. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  115165. if (replace === void 0) { replace = false; }
  115166. if (attachCameraControls === void 0) { attachCameraControls = false; }
  115167. // Dispose existing camera in replace mode.
  115168. if (replace) {
  115169. if (this.activeCamera) {
  115170. this.activeCamera.dispose();
  115171. this.activeCamera = null;
  115172. }
  115173. }
  115174. // Camera
  115175. if (!this.activeCamera) {
  115176. var worldExtends = this.getWorldExtends();
  115177. var worldSize = worldExtends.max.subtract(worldExtends.min);
  115178. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  115179. var camera;
  115180. var radius = worldSize.length() * 1.5;
  115181. // empty scene scenario!
  115182. if (!isFinite(radius)) {
  115183. radius = 1;
  115184. worldCenter.copyFromFloats(0, 0, 0);
  115185. }
  115186. if (createArcRotateCamera) {
  115187. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  115188. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  115189. arcRotateCamera.wheelPrecision = 100 / radius;
  115190. camera = arcRotateCamera;
  115191. }
  115192. else {
  115193. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  115194. freeCamera.setTarget(worldCenter);
  115195. camera = freeCamera;
  115196. }
  115197. camera.minZ = radius * 0.01;
  115198. camera.maxZ = radius * 1000;
  115199. camera.speed = radius * 0.2;
  115200. this.activeCamera = camera;
  115201. var canvas = this.getEngine().getRenderingCanvas();
  115202. if (attachCameraControls && canvas) {
  115203. camera.attachControl(canvas);
  115204. }
  115205. }
  115206. };
  115207. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  115208. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  115209. if (replace === void 0) { replace = false; }
  115210. if (attachCameraControls === void 0) { attachCameraControls = false; }
  115211. this.createDefaultLight(replace);
  115212. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  115213. };
  115214. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  115215. if (pbr === void 0) { pbr = false; }
  115216. if (scale === void 0) { scale = 1000; }
  115217. if (blur === void 0) { blur = 0; }
  115218. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  115219. if (!environmentTexture) {
  115220. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  115221. return null;
  115222. }
  115223. if (setGlobalEnvTexture) {
  115224. if (environmentTexture) {
  115225. this.environmentTexture = environmentTexture;
  115226. }
  115227. }
  115228. // Skybox
  115229. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  115230. if (pbr) {
  115231. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  115232. hdrSkyboxMaterial.backFaceCulling = false;
  115233. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  115234. if (hdrSkyboxMaterial.reflectionTexture) {
  115235. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115236. }
  115237. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  115238. hdrSkyboxMaterial.disableLighting = true;
  115239. hdrSkyboxMaterial.twoSidedLighting = true;
  115240. hdrSkybox.infiniteDistance = true;
  115241. hdrSkybox.material = hdrSkyboxMaterial;
  115242. }
  115243. else {
  115244. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  115245. skyboxMaterial.backFaceCulling = false;
  115246. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  115247. if (skyboxMaterial.reflectionTexture) {
  115248. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115249. }
  115250. skyboxMaterial.disableLighting = true;
  115251. hdrSkybox.infiniteDistance = true;
  115252. hdrSkybox.material = skyboxMaterial;
  115253. }
  115254. return hdrSkybox;
  115255. };
  115256. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  115257. if (BABYLON.EnvironmentHelper) {
  115258. return new BABYLON.EnvironmentHelper(options, this);
  115259. }
  115260. return null;
  115261. };
  115262. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  115263. if (webVROptions === void 0) { webVROptions = {}; }
  115264. return new BABYLON.VRExperienceHelper(this, webVROptions);
  115265. };
  115266. })(BABYLON || (BABYLON = {}));
  115267. //# sourceMappingURL=babylon.sceneHelpers.js.map
  115268. 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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\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;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\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#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*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\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\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 RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\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}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\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#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,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#ifdef RAMPGRADIENT\nremapRanges=remapData;\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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\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}","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\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\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}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\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)-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.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\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)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\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 POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\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 CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\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\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\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\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\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() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\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\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\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,abs(randY),randZ);\ndirection=position+directionRandomizer*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(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\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#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*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","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}","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}","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;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\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;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\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\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\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}","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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  115269. 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\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\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};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(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;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(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 REFLECTION\nuniform mat4 reflectionMatrix;\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\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\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\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\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\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>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}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(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#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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 vec4 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 vec4 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 vec4 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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\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;\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}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","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","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};","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};"};
  115270. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  115271. globalObject["BABYLON"] = BABYLON;
  115272. //backwards compatibility
  115273. if(typeof earcut !== 'undefined') {
  115274. globalObject["Earcut"] = {
  115275. earcut: earcut
  115276. };
  115277. }
  115278. return BABYLON;
  115279. });